@v360-tech/v360-player 1.7.2 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -6
- package/dist/types/components/v360-player.d.ts +63 -0
- package/dist/types/icons/index.d.ts +3 -0
- package/dist/types/main.d.ts +2 -2
- package/dist/types/player/auto-hide-controller.d.ts +17 -0
- package/dist/types/player/format.d.ts +1 -0
- package/dist/types/player/fullscreen.d.ts +4 -0
- package/dist/types/player/speeds.d.ts +4 -0
- package/dist/types/player/stream-controller.d.ts +29 -0
- package/dist/types/player/styles.d.ts +1 -0
- package/dist/types/player/templates.d.ts +12 -0
- package/dist/types/player/types.d.ts +1 -0
- package/dist/types/player/volume.d.ts +1 -0
- package/dist/v360-player.browser.js +315 -268
- package/dist/v360-player.js +768 -492
- package/package.json +2 -4
- package/dist/types/components/V360Player.d.ts +0 -61
- /package/dist/types/styles/{progressBar.d.ts → progress-bar.d.ts} +0 -0
|
@@ -1,48 +1,4 @@
|
|
|
1
|
-
(function(Ki,se){typeof exports=="object"&&typeof module<"u"?se(exports):typeof define=="function"&&define.amd?define(["exports"],se):(Ki=typeof globalThis<"u"?globalThis:Ki||self,se(Ki.V360Player={}))})(this,(function(Ki){"use strict";const se=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},qc=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=zc},zc=Number.MAX_SAFE_INTEGER||9007199254740991;let me=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),U=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",n.UNKNOWN="unknown",n})({}),E=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});function Xc(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Gr={exports:{}},Na;function Zc(){return Na||(Na=1,(function(n,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,h){if(h=h||{},l=l.trim(),u=u.trim(),!u){if(!h.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var g=o.parseURL(u);if(!g)throw new Error("Error trying to parse relative URL.");if(g.scheme)return h.alwaysNormalize?(g.path=o.normalizePath(g.path),o.buildURLFromParts(g)):u;var m=o.parseURL(l);if(!m)throw new Error("Error trying to parse base URL.");if(!m.netLoc&&m.path&&m.path[0]!=="/"){var A=s.exec(m.path);m.netLoc=A[1],m.path=A[2]}m.netLoc&&!m.path&&(m.path="/");var C={scheme:m.scheme,netLoc:g.netLoc,path:null,params:g.params,query:g.query,fragment:g.fragment};if(!g.netLoc&&(C.netLoc=m.netLoc,g.path[0]!=="/"))if(!g.path)C.path=m.path,g.params||(C.params=m.params,g.query||(C.query=m.query));else{var v=m.path,x=v.substring(0,v.lastIndexOf("/")+1)+g.path;C.path=o.normalizePath(x)}return C.path===null&&(C.path=h.alwaysNormalize?o.normalizePath(g.path):g.path),o.buildURLFromParts(C)},parseURL:function(l){var u=i.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(Gr)),Gr.exports}var Hr=Zc();class Vr{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}let ke=(function(n){return n.MANIFEST="manifest",n.LEVEL="level",n.AUDIO_TRACK="audioTrack",n.SUBTITLE_TRACK="subtitleTrack",n.MEDIA_FRAGMENT="media-fragment",n.KEY="key",n.STEERING_MANIFEST="steering-manifest",n.SERVER_CERTIFICATE="server-certificate",n.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",n})({}),ge=(function(n){return n.MAIN="main",n.AUDIO="audio",n.SUBTITLE="subtitle",n})({});var ze={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Ba{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Jc(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ze.AUDIO]:null,[ze.VIDEO]:null,[ze.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Vr),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Hr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ze.AUDIO]=null,e[ze.VIDEO]=null,e[ze.AUDIOVIDEO]=null,this.url=null}}function st(n){return n.sn!=="initSegment"}function cs(n,e){return n.sn===e?.sn&&n.level===e.level}function Kr(n,e){return n.sn===e?.sn&&n.level===e.level&&n.cc===e.cc}class Hs extends Ba{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(se(e)&&se(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const i=Object.keys(t);if(i.length===1){const s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=se(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!se(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return st(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}}class Qc extends Ba{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,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||this.fragment.type===ge.SUBTITLE&&this.stats.loading.end>0)}}function Ua(n,e){const t=Object.getPrototypeOf(n);if(t){const i=Object.getOwnPropertyDescriptor(t,e);return i||Ua(t,e)}}function Jc(n,e){const t=Ua(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}function eh(n,e,t){return(e=sh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function je(){return je=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(n[i]=t[i])}return n},je.apply(null,arguments)}function $a(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),t.push.apply(t,i)}return t}function Ae(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?$a(Object(t),!0).forEach(function(i){eh(n,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):$a(Object(t)).forEach(function(i){Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(t,i))})}return n}function Vs(n,e){if(n==null)return{};var t,i,s=th(n,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);for(i=0;i<r.length;i++)t=r[i],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(n,t)&&(s[t]=n[t])}return s}function th(n,e){if(n==null)return{};var t={};for(var i in n)if({}.hasOwnProperty.call(n,i)){if(e.indexOf(i)!==-1)continue;t[i]=n[i]}return t}function ih(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function sh(n){var e=ih(n,"string");return typeof e=="symbol"?e:e+""}function Ks(n){switch(n.details){case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_TIMEOUT:case U.LEVEL_LOAD_TIMEOUT:case U.MANIFEST_LOAD_TIMEOUT:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:case U.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Ga(n){return n.details.startsWith("key")}function Ha(n){return Ga(n)&&!!n.frag&&!n.frag.decryptdata}function Va(n,e){const t=Ks(e);return n.default[`${t?"timeout":"error"}Retry`]}function Yr(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Ka(n){return Ae(Ae({},n),{errorRetry:null,timeoutRetry:null})}function hs(n,e,t,i){if(!n)return!1;const s=i?.code,r=e<n.maxNumRetry&&(rh(s)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,i,r):r}function rh(n){return ds(n)||!!n&&(n<400||n>499)}function ds(n){return n===0&&navigator.onLine===!1}function Ya(n,e){return e>0&&n.loadError>0&&n.loadErrorTime!==0&&self.performance.now()-n.loadErrorTime>e}class Yi{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 nh{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 Yi(e),this.fast_=new Yi(t),this.defaultTTFB_=s,this.ttfb_=new Yi(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Yi(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Yi(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Yi(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;const i=Math.min(this.minDelayMs_,t/1e5),s=8*t,r=Math.max(e,i)/1e3,a=s/r;this.fast_.sample(r,a),this.slow_.sample(r,a)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class wt{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=vi,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 vi=function(){},ah={trace:vi,debug:vi,log:vi,warn:vi,info:vi,error:vi};function Wr(){return je({},ah)}function oh(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):vi}function Wa(n,e,t){return e[n]?e[n].bind(e):oh(n,t)}const jr=Wr();function lh(n,e,t){const i=Wr();if(typeof console=="object"&&n===!0||typeof n=="object"){const s=["debug","log","info","warn","error"];s.forEach(r=>{i[r]=Wa(r,n,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return Wr()}s.forEach(r=>{jr[r]=Wa(r,n)})}else je(jr,i);return i}const Ge=jr;function Ei(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function uh(n){return typeof self<"u"&&n===self.ManagedMediaSource}function ja(n,e){const t=Object.keys(n),i=Object.keys(e),s=t.length,r=i.length;return!s||!r||s===r&&!t.some(a=>i.indexOf(a)===-1)}function ch(n){return btoa(String.fromCharCode(...n))}function Ys(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}const hh="utf-16",qr="utf-16be",qa="utf-16le",Ws="utf-8";function dh(n,e={}){let t;Ys(n)?t=new DataView(n):t=new DataView(n.buffer,n.byteOffset,n.byteLength);let i=0,{encoding:s}=e;if(!s){const u=t.getUint8(0),h=t.getUint8(1);u==239&&h==187&&t.getUint8(2)==191?(s=Ws,i=3):u==254&&h==255?(s=qr,i=2):u==255&&h==254?(s=qa,i=2):s=Ws}if(typeof TextDecoder<"u")return new TextDecoder(s).decode(t);const{byteLength:r}=t,a=s!==qr;let o="",l;for(;i<r;){switch(s){case Ws:if(l=t.getUint8(i),l<128)i++;else if(l>=194&&l<=223)if(i+1<r){const u=t.getUint8(i+1);u>=128&&u<=191?(l=(l&31)<<6|u&63,i+=2):i++}else i++;else if(l>=224&&l<=239)if(i+2<=r-1){const u=t.getUint8(i+1),h=t.getUint8(i+2);u>=128&&u<=191&&h>=128&&h<=191?(l=(l&15)<<12|(u&63)<<6|h&63,i+=3):i++}else i++;else if(l>=240&&l<=244)if(i+3<=r-1){const u=t.getUint8(i+1),h=t.getUint8(i+2),d=t.getUint8(i+3);u>=128&&u<=191&&h>=128&&h<=191&&d>=128&&d<=191?(l=(l&7)<<18|(u&63)<<12|(h&63)<<6|d&63,i+=4):i++}else i++;else i++;break;case qr:case hh:case qa:l=t.getUint16(i,a),i+=2;break}o+=String.fromCodePoint(l)}return o}function fh(n){const e=typeof n=="string"?new URL(n):n;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function za(n,e){if(n<0)return-za(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const i=Math.floor(n*t);return(i%2===0?i:i+1)/t}else return Math.round(n*t)/t}function gh(n,e){let t;try{t=new URL(n)}catch{return n}const i=new URL(e);if(t.origin!==i.origin)return n;const s=t.pathname.split("/").slice(1),r=i.pathname.split("/").slice(1,-1),a=Math.min(s.length,r.length);for(let o=0;o<a&&s[o]===r[o];o++)s.shift(),r.shift();for(;r.length;)r.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}function Xa(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?s:s&3|8).toString(16)})}}}function zr(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function js(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function ph(n,e){return zr(n,e)&&js(n,e+6)+10<=n.length-e}function Za(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function fs(n,e){const t=e;let i=0;for(;zr(n,e);){i+=10;const s=js(n,e+6);i+=s,Za(n,e+10)&&(i+=10),e+=i}if(i>0)return n.subarray(t,t+i)}function mh(n){return Ys(n)?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function Xr(n,e=0,t=1/0){return Ah(n,e,t,Uint8Array)}function Ah(n,e,t,i){const s=Ih(n);let r=1;"BYTES_PER_ELEMENT"in i&&(r=i.BYTES_PER_ELEMENT);const a=Ch(n)?n.byteOffset:0,o=(a+n.byteLength)/r,l=(a+e)/r,u=Math.floor(Math.max(0,Math.min(l,o)));return new i(s,u,Math.floor(Math.min(u+Math.max(t,0),o))-u)}function Ih(n){return Ys(n)?n:n.buffer}function Ch(n){return n&&Ys(n.buffer)&&n.byteLength!==void 0&&n.byteOffset!==void 0}function Mt(n,e=!1){const t=e?n.indexOf(0):n.length,i=dh(new DataView(n.buffer,n.byteOffset,t),{encoding:Ws});return e?i:i.replace(/\0/g,"")}function yh(n){const e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const i=n.data.subarray(1).indexOf(0);if(i===-1)return;const s=Mt(Xr(n.data,1,i)),r=n.data[2+i],a=n.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=Mt(Xr(n.data,3+i,a));let l;return s==="-->"?l=Mt(Xr(n.data,4+i+a)):l=mh(n.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=r,e.description=o,e.data=l,e}function vh(n){if(n.size<2)return;const e=Mt(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function Eh(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const{data:i}=n,s=Mt(i.subarray(t),!0);t+=s.length+1;const r=Mt(i.subarray(t));return{key:n.type,info:s,data:r}}const e=Mt(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Th(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const i=Mt(n.data.subarray(t),!0);t+=i.length+1;const s=Mt(n.data.subarray(t));return{key:n.type,info:i,data:s}}const e=Mt(n.data);return{key:n.type,info:"",data:e}}function Sh(n){return n.type==="PRIV"?vh(n):n.type[0]==="W"?Th(n):n.type==="APIC"?yh(n):Eh(n)}function xh(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=js(n,4),i=10;return{type:e,size:t,data:n.subarray(i,i+t)}}const qs=10,bh=10;function Qa(n){let e=0;const t=[];for(;zr(n,e);){const i=js(n,e+6);n[e+5]>>6&1&&(e+=qs),e+=qs;const s=e+i;for(;e+bh<s;){const r=xh(n.subarray(e)),a=Sh(r);a&&t.push(a),e+=r.size+qs}Za(n,e)&&(e+=qs)}return t}function Ja(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Lh(n){if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Zr(n){const e=Qa(n);for(const t of e)if(Ja(t))return Lh(t)}function ut(n){let e="";for(let t=0;t<n.length;t++){let i=n[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function eo(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Qr(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Yt(n){return String.fromCharCode.apply(null,n)}const Jt=Math.pow(2,32)-1,Te={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},to={video:1,audio:2,id3:3,text:4};function io(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function ce(n,e){const t=n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3];return t<0?4294967296+t:t}function so(n,e){let t=ce(n,e);return t*=Math.pow(2,32),t+=ce(n,e+4),t}function zs(n,e){let t="";for(let i=e;i<n.length;i++)if(t+=String.fromCharCode(n[i]),n[i]===0)return t;return null}function Jr(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function lt(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function ro(n,e,t){const i=e.byteOffset-n.byteOffset-8,s=8+t,r=e.byteLength+8-s;r<8||(lt(n,i,s),lt(n,i+s,r),lt(n,i+s+4,Te.free))}function en(n,e){return[n.byteOffset-e-8,n.byteOffset-e+n.byteLength]}function no(n,e){e.sort((o,l)=>o[0]-l[0]);const t=e.reduce((o,[l,u])=>o+u-l,0),i=new Uint8Array(n.byteLength-t);let s=0,r=0;for(let o=0;o<e.length;o++){const[l,u]=e[o];i.set(n.subarray(s,l),r),r+=l-s,s=u}return i.set(n.subarray(s),r),{result:i,dropped:t,droppedBefore:o=>e.reduce((l,[u,h])=>h<=o?l+h-u:l,0)}}function Rh(n){const e=xe(n,["moov"]);if(e.length!==1||xe(n,["moof"]).length)return null;const t=n.byteOffset,i=[],s=[];let r=!1;const a=xe(e[0],["trak"]);for(let m=0;m<a.length;m++){const A=a[m],C=xe(A,["mdia","hdlr"])[0];if((C?Yt(C.subarray(8,12)):"")==="vide"){r=!0;continue}const x=xe(A,["tkhd"])[0];if(!x)return null;const R=x[0];s.push(ce(x,R===0?12:20)),i.push(en(A,t))}if(!r||!i.length)return null;const o=xe(e[0],["mvex"])[0];let l=0;if(o){const m=xe(o,["trex"]);for(let A=0;A<m.length;A++){const C=m[A];s.indexOf(ce(C,4))!==-1&&(i.push(en(C,t)),l+=C.byteLength+8)}}const{result:u,dropped:h,droppedBefore:d}=no(n,i),g=e[0].byteOffset-t-8;if(lt(u,g,e[0].byteLength+8-h),o&&l){const m=o.byteOffset-t-8;lt(u,m-d(m),o.byteLength+8-l)}return u}function Dh(n,e,t,i,s){if(t<1)return null;const r=xe(n,["moof"]);if(r.length!==1)return null;const a=r[0],o=n.byteOffset,l=[],u=[],h=xe(a,["traf"]);let d=!0;for(let C=0;C<h.length;C++){const v=h[C],x=xe(v,["tfhd"])[0];if(!x)return null;ce(x,4)===e?(l.push(v),ce(x,0)&131072||(d=!1)):u.push(en(v,o))}if(!l.length||u.length&&!d)return null;if(i!==void 0){let C=t;for(let x=0;x<l.length;x++){const R=l[x];let b=0;const D=xe(R,["trun"]);for(let p=0;p<D.length;p++){const $=D[p],N=Math.min(C,ce($,4));if(N){lt(n,$.byteOffset-o+4,N);const O=ce($,0)&16777215,W=(O&256?4:0)+(O&512?4:0)+(O&1024?4:0)+(O&2048?4:0);ro(n,$,8+(O&1?4:0)+(O&4?4:0)+N*W)}else lt(n,$.byteOffset-o-4,Te.free);C-=N,b+=N}const _=xe(R,["senc"])[0];_&<(n,_.byteOffset-o+4,b);const M=xe(R,["saiz"])[0];if(M){const p=M[1]<<16|M[2]<<8|M[3];let $=4;p&1&&($+=8);const N=M[$];$+=1,lt(n,M.byteOffset-o+$,b),ro(n,M,$+4+(N===0?b:0))}}const v=xe(n,["mdat"]);if(v.length===1){const x=v[0].byteOffset-o-8;lt(n,x,i-x)}}let g=n,m=0,A=()=>0;if(u.length){({result:g,dropped:m,droppedBefore:A}=no(n,u)),lt(g,a.byteOffset-o-8,a.byteLength+8-m);for(let C=0;C<l.length;C++){const v=l[C],x=A(v.byteOffset-o),R=xe(v,["trun"]);for(let b=0;b<R.length;b++){const D=R[b];ce(D,0)&1&<(g,D.byteOffset-o-x+8,ce(D,8)-m)}if(x){const b=xe(v,["saio"]);for(let D=0;D<b.length;D++){const _=b[D],M=_[0]===0?4:8;let p=ce(_,0)&1?12:4,$=ce(_,p);for(p+=4;$--;p+=M){const N=p+M-4;lt(g,_.byteOffset-o-x+N,ce(_,N)-x)}}}}}if(s){const{durationOffset:C,value:v}=s;lt(g,C-A(C),v)}return i!==void 0?g.subarray(0,i-m):g}function Ph(n,e){const t=n.byteLength;for(let i=0;i<t;){const s=ce(n,i);if(s>8&&ce(n,i+4)===Te[e])return!0;i=s>1?i+s:t}return!1}function xe(n,e){const t=[];return e.length&&ao(n,e,0,0,n.byteLength,t),t}function ao(n,e,t,i,s,r){const a=e[t];if(a?.length!==4)return;const o=a.charCodeAt(0),l=a.charCodeAt(1),u=a.charCodeAt(2),h=a.charCodeAt(3),d=e.length-1;for(let g=i;g<s;){const m=g+8<=s,A=g+4<=s?n[g]*16777216+(n[g+1]<<16|n[g+2]<<8|n[g+3]):ce(n,g),C=A>1?g+A:s;if(m&&n[g+4]===o&&n[g+5]===l&&n[g+6]===u&&n[g+7]===h){const v=Math.min(C,s);t===d?r.push(n.subarray(g+8,v)):ao(n,e,t+1,g+8,v,r)}g=C}}function _h(n){const e=[],t=n[0];let i=8;const s=ce(n,i);i+=4;let r=0,a=0;t===0?(r=ce(n,i),a=ce(n,i+4),i+=8):(r=so(n,i),a=so(n,i+8),i+=16),i+=2;let o=n.length+a;const l=io(n,i);i+=2;for(let u=0;u<l;u++){let h=i;const d=ce(n,h);h+=4;const g=d&2147483647;if((d&2147483648)>>>31===1)return Ge.warn("SIDX has hierarchical references (not supported)"),null;const A=ce(n,h);h+=4,e.push({referenceSize:g,subsegmentDuration:A,info:{duration:A/s,start:o,end:o+g-1}}),o+=g,h+=4,i=h}return{earliestPresentationTime:r,timescale:s,version:t,referencesCount:l,references:e}}function oo(n){const e=[],t=xe(n,["moov","trak"]);for(let s=0;s<t.length;s++){const r=t[s],a=xe(r,["tkhd"])[0];if(a){let o=a[0];const l=ce(a,o===0?12:20),u=xe(r,["mdia","mdhd"])[0];if(u){o=u[0];const h=ce(u,o===0?12:20),d=xe(r,["mdia","hdlr"])[0];if(d){const g=Yt(d.subarray(8,12)),m={soun:ze.AUDIO,vide:ze.VIDEO}[g],A=xe(r,["mdia","minf","stbl","stsd"])[0],C=kh(A);m?(e[l]={timescale:h,type:m,stsd:C},e[m]=Ae({timescale:h,id:l},C)):e[l]={timescale:h,type:g,stsd:C}}}}}return xe(n,["moov","mvex","trex"]).forEach(s=>{const r=ce(s,4),a=e[r];a&&(a.default={duration:ce(s,12),sampleSize:ce(s,16),flags:ce(s,20)})}),e}function kh(n){const e=n.subarray(8),t=e.subarray(86),i=Yt(e.subarray(4,8));let s=i,r;const a=i==="enca"||i==="encv";if(a){const u=xe(e,[i])[0].subarray(i==="enca"?28:78);xe(u,["sinf"]).forEach(d=>{const g=xe(d,["schm"])[0];if(g){const m=Yt(g.subarray(4,8));if(m==="cbcs"||m==="cenc"){const A=xe(d,["frma"])[0];A&&(s=Yt(A))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const l=xe(t,["avcC"])[0];l&&l.length>3&&(s+="."+Zs(l[1])+Zs(l[2])+Zs(l[3]),r=Xs(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=xe(e,[i])[0],u=xe(l.subarray(28),["esds"])[0];if(u&&u.length>7){let h=4;if(u[h++]!==3)break;h=tn(u,h),h+=2;const d=u[h++];if(d&128&&(h+=2),d&64&&(h+=u[h++]),u[h++]!==4)break;h=tn(u,h);const g=u[h++];if(g===64)s+="."+Zs(g);else break;if(h+=12,u[h++]!==5)break;h=tn(u,h);const m=u[h++];let A=(m&248)>>3;A===31&&(A+=1+((m&7)<<3)+((u[h]&224)>>5)),s+="."+A}break}case"hvc1":case"hev1":{const l=xe(t,["hvcC"])[0];if(l&&l.length>12){const u=l[1],h=["","A","B","C"][u>>6],d=u&31,g=ce(l,2),m=(u&32)>>5?"H":"L",A=l[12],C=l.subarray(6,12);s+="."+h+d,s+="."+wh(g).toString(16).toUpperCase(),s+="."+m+A;let v="";for(let x=C.length;x--;){const R=C[x];(R||v)&&(v="."+R.toString(16).toUpperCase()+v)}s+=v}r=Xs(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Xs(s,t)||s;break}case"vp09":{const l=xe(t,["vpcC"])[0];if(l&&l.length>6){const u=l[4],h=l[5],d=l[6]>>4&15;s+="."+ei(u)+"."+ei(h)+"."+ei(d)}break}case"av01":{const l=xe(t,["av1C"])[0];if(l&&l.length>2){const u=l[1]>>>5,h=l[1]&31,d=l[2]>>>7?"H":"M",g=(l[2]&64)>>6,m=(l[2]&32)>>5,A=u===2&&g?m?12:10:g?10:8,C=(l[2]&16)>>4,v=(l[2]&8)>>3,x=(l[2]&4)>>2,R=l[2]&3;s+="."+u+"."+ei(h)+d+"."+ei(A)+"."+C+"."+v+x+R+"."+ei(1)+"."+ei(1)+"."+ei(1)+"."+0,r=Xs("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:r}}function Xs(n,e){const t=xe(e,["dvvC"]),i=t.length?t[0]:xe(e,["dvcC"])[0];if(i){const s=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return n+"."+ei(s)+"."+ei(r)}}function wh(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function tn(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Zs(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function ei(n){return(n<10?"0":"")+n}function Mh(n,e){if(!n||!e)return;const t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&lo(n,(i,s)=>{const r=i.subarray(8,24);r.some(a=>a!==0)||(Ge.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ut(r)} -> ${ut(t)}`),i.set(t,8))})}function Oh(n){const e=[];return lo(n,t=>e.push(t.subarray(8,24))),e}function lo(n,e){xe(n,["moov","trak"]).forEach(i=>{const s=xe(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let a=xe(r,["enca"]);const o=a.length>0;o||(a=xe(r,["encv"])),a.forEach(l=>{const u=o?l.subarray(28):l.subarray(78);xe(u,["sinf"]).forEach(d=>{const g=uo(d);g&&e(g,o)})})})}function uo(n){const e=xe(n,["schm"])[0];if(e){const t=Yt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const i=xe(n,["schi","tenc"])[0];if(i)return i}}}let co;function Fh(n){return typeof TextDecoder>"u"?Mt(n):(co||(co=new TextDecoder("utf-8"))).decode(n).replace(/\0/g,"")}function Nh(n){const e=n.byteLength,t=[];for(let i=0;i<e;){const s=i+8<=e,r=i+4<=e?n[i]*16777216+(n[i+1]<<16|n[i+2]<<8|n[i+3]):ce(n,i),a=r>1?i+r:e;if(s&&n[i+4]===109&&n[i+5]===111&&n[i+6]===111&&n[i+7]===102){const o=Math.min(a,e);for(let l=i+8;l<o;){const u=l+8<=o,h=l+4<=o?n[l]*16777216+(n[l+1]<<16|n[l+2]<<8|n[l+3]):ce(n,l),d=h>1?l+h:o;if(u&&n[l+4]===116&&n[l+5]===114&&n[l+6]===97&&n[l+7]===102){const g=Math.min(d,o);let m,A;const C=[];for(let v=l+8;v<g;){const x=v+8<=g,R=v+4<=g?n[v]*16777216+(n[v+1]<<16|n[v+2]<<8|n[v+3]):ce(n,v),b=R>1?v+R:g;if(x&&n[v+4]===116){const D=Math.min(b,g);n[v+5]===102&&n[v+6]===104&&n[v+7]===100?A||(A=n.subarray(v+8,D)):n[v+5]===102&&n[v+6]===100&&n[v+7]===116?m||(m=n.subarray(v+8,D)):n[v+5]===114&&n[v+6]===117&&n[v+7]===110&&C.push(n.subarray(v+8,D))}v=b}t.push({moofOffset:n.byteOffset+i,tfdt:m,tfhd:A,truns:C})}l=d}}i=a}return t}function Bh(n,e,t,i,s=!0){return ho(n,e,i,s)}function Uh(n,e,t,i,s=!1){const r=[],a=e.samples,o=ho(a,t,i,s,{isHEVCFlavor:gs(e.codec),samples:r,timeOffset:n,timescale:e.timescale,trackId:e.id});return{samples:r,sampleData:{includeSampleDetails:s,tracks:o}}}function ho(n,e,t,i,s){const r={};let a=!1;const o=Nh(n),l=n.byteLength;for(let d=0;d<o.length;d++){const{moofOffset:g,tfdt:m,tfhd:A,truns:C}=o[d],v=ce(A,4),x=e[v];if(!x)continue;const R=r[v]||(r[v]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:x.timescale,type:x.type});let b;if(m){const Z=m[0];b=ce(m,4),Z===1&&(b===Jt?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(b*=Jt+1,b+=ce(m,8))),se(b)&&(!se(R.start)||b<R.start)&&(R.start=b),s&&se(b)&&(s.timeOffset=b/s.timescale)}const D=s?.trackId===v&&x.type===ze.VIDEO,_=x.default,M=ce(A,0)&16777215;let p=_?.duration||0,$,N=_?.sampleSize||0,O=8;M&1&&(O+=8),M&2&&(O+=4),M&8&&(p=ce(A,O),$=A.byteOffset-n.byteOffset+O,O+=4),M&16&&(N=ce(A,O));let W=0;const q=(M&1)!==0,z=!q&&(M&131072)!==0;q?(W=ce(A,8),W*=Math.pow(2,32),W+=ce(A,12)):z&&(W=g);let oe=b||0,re=0,J=p;for(let Z=0;Z<C.length;Z++){const Q=C[Z],ee=ce(Q,4),he=R.sampleCount;R.sampleCount+=ee;const te=Q[3]&1;let ne=0;const Ee=Q[3]&4,Ie=Q[2]&1,_e=Q[2]&2,ye=Q[2]&4,Oe=Q[2]&8;let Le=8;te&&(ne=Jr(Q,Le),Le+=4),Ee&&(!(Q[Le+1]&1)&&R.keyFrameIndex===void 0&&(R.keyFrameIndex=he),Le+=4);let Fe=W+ne;if(!i&&Q[1]===0&&Q[2]===6&&Q[3]===1){var u,h;const We=oe,St=Fe,$t=Le;let pe=-1,we=0,Re=0,nt=(u=s?.timeOffset)!=null?u:0;const it=p/((h=s?.timescale)!=null?h:1),At=s?.isHEVCFlavor===!0,at=At?2:1;for(let rt=0;rt<ee;rt++){const ue=Q[Le]===0?Q[Le+1]<<16|Q[Le+2]<<8|Q[Le+3]:ce(Q,Le),Ze=pe===-1&&R.keyFrameIndex===void 0&&(Q[Le+5]&1)===0;Le+=8;const xt=Fe+ue;if(D){if(ue>0){let ft=Fe;do{const li=n[ft]===0?n[ft+1]<<16|n[ft+2]<<8|n[ft+3]:ce(n,ft);ft+=4;const Gt=n[ft],Dt=At?Gt>>1&63:Gt&31;(At?Dt===39||Dt===40:Dt===6)&&ps(n.subarray(ft,ft+li),at,nt,s.samples),ft+=li}while(ft<xt)}nt+=it}Fe=xt,Ze&&(pe=rt,we=Fe)}if(Fe<=l)Re=ee;else{let rt=St,ue=$t;for(let Ze=0;Ze<ee;Ze++){const xt=Q[ue]===0?Q[ue+1]<<16|Q[ue+2]<<8|Q[ue+3]:ce(Q,ue);if(rt+=xt,rt>l)break;Re=Ze+1,ue+=8}}if(D&&(s.timeOffset=nt),pe!==-1&&we<=l&&R.keyFrameIndex===void 0&&(R.keyFrameIndex=pe,R.keyFrameStart=We+pe*p),Re){(!se(R.ptsMin)||We<R.ptsMin)&&(R.ptsMin=We);const rt=We+Re*p;(!se(R.ptsMax)||rt>R.ptsMax)&&(R.ptsMax=rt)}const Nt=p*ee;oe=We+Nt,re+=Nt;continue}let Ye,Ct;i&&(Ye=[],Ct={sampleOffset:Fe,samples:Ye,defaultSampleDurationOffset:$},Fe<=l&&R.trun.push(Ct));let yt;for(let We=0;We<ee;We++){let St;Ie?(i&&(St=Q.byteOffset-n.byteOffset+Le),J=ce(Q,Le),Le+=4):J=p,_e?(yt=ce(Q,Le),Le+=4):yt=N;let $t,pe;ye&&(pe=Q[Le+1]&1?1:0,i&&($t={isNonSync:pe,dependsOn:(Q[Le]&3)===1?1:2}),Le+=4);let we=0;if(Oe&&(we=Q[0]===0?ce(Q,Le):Jr(Q,Le),Le+=4),D){let Re=Fe,nt=0;for(;nt<yt;){const it=ce(n,Re);Re+=4,fo(s.isHEVCFlavor,n[Re])&&ps(n.subarray(Re,Re+it),s.isHEVCFlavor?2:1,s.timeOffset+we/s.timescale,s.samples),Re+=it,nt+=it+4}s.timeOffset+=J/s.timescale}if(Fe+=yt,Fe<=l){Ct&&St!==void 0&&(Ct.lastSampleDurationOffset=St),pe===0&&R.keyFrameIndex===void 0&&(R.keyFrameIndex=We,R.keyFrameStart=oe);const Re=oe+we;(!se(R.ptsMin)||Re<R.ptsMin)&&(R.ptsMin=Re),(!se(R.ptsMax)||Re+J>R.ptsMax)&&(R.ptsMax=Re+J),Ye&&(Ye[We]={cts:we,duration:J,flags:$t,size:yt})}oe+=J,re+=J}!re&&p&&(re+=p*ee)}R.duration+=re,R.duration&&(a=!0)}if(!a){let d=1/0,g=0;const m=xe(n,["sidx"]);for(let A=0;A<m.length;A++){const C=_h(m[A]);if(C!=null&&C.references){d=Math.min(d,C.earliestPresentationTime/C.timescale);const v=C.references.reduce((x,R)=>x+R.info.duration||0,0);g=Math.max(g,v+C.earliestPresentationTime/C.timescale)}}g&&se(g)&&Object.keys(r).forEach(A=>{r[A].duration||(r[A].duration=g*r[A].timescale-r[A].start)})}return r}function $h(n){const e={valid:null,remainder:null},t=xe(n,["moof"]);if(t.length<2)return e.remainder=n,e;const i=t[t.length-1];return e.valid=n.slice(0,i.byteOffset-8),e.remainder=n.slice(i.byteOffset-8),e}function Bt(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Gh(n,e){const t=[],i=e.samples,s=e.timescale,r=e.id;let a=!1;return xe(i,["moof"]).map(l=>{const u=l.byteOffset-8;xe(l,["traf"]).map(d=>{const g=xe(d,["tfdt"]).map(m=>{const A=m[0];let C=ce(m,4);return A===1&&(C*=Math.pow(2,32),C+=ce(m,8)),C/s})[0];return g!==void 0&&(n=g),xe(d,["tfhd"]).map(m=>{const A=ce(m,4),C=ce(m,0)&16777215,v=(C&1)!==0;let x=0;const R=(C&2)!==0,b=(C&8)!==0;let D=0;const _=(C&16)!==0;let M=0;const p=(C&32)!==0,$=!v&&(C&131072)!==0;let N=8;A===r&&(v?(x=ce(m,N),N+=4,x*=Math.pow(2,32),x+=ce(m,N),N+=4):$&&(x=u),R&&(N+=4),b&&(D=ce(m,N),N+=4),_&&(M=ce(m,N),N+=4),p&&(N+=4),e.type==="video"&&(a=gs(e.codec)),xe(d,["trun"]).map(O=>{const W=O[0],q=ce(O,0)&16777215,z=(q&1)!==0;let oe=0;const re=(q&4)!==0,J=(q&256)!==0;let Z=0;const Q=(q&512)!==0;let ee=0;const he=(q&1024)!==0,te=(q&2048)!==0;let ne=0;const Ee=ce(O,4);let Ie=8;z&&(oe=ce(O,Ie),Ie+=4),re&&(Ie+=4);let _e=x+oe;for(let ye=0;ye<Ee;ye++){if(J?(Z=ce(O,Ie),Ie+=4):Z=D,Q?(ee=ce(O,Ie),Ie+=4):ee=M,he&&(Ie+=4),te&&(W===0?ne=ce(O,Ie):ne=Jr(O,Ie),Ie+=4),e.type===ze.VIDEO){let Oe=0;for(;Oe<ee;){const Le=ce(i,_e);if(_e+=4,fo(a,i[_e])){const Fe=i.subarray(_e,_e+Le);ps(Fe,a?2:1,n+ne/s,t)}_e+=Le,Oe+=Le+4}}n+=Z/s}}))})})}),t}function gs(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function fo(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ps(n,e,t,i){const s=go(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<s.length;){a=0;do{if(r>=s.length)break;l=s[r++],a+=l}while(l===255);o=0;do{if(r>=s.length)break;l=s[r++],o+=l}while(l===255);const u=s.length-r;let h=r;if(o<u)r+=o;else if(o>u){Ge.error(`Malformed SEI payload. ${o} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(s[h++]===181){const g=io(s,h);if(h+=2,g===49){const m=ce(s,h);if(h+=4,m===1195456820){const A=s[h++];if(A===3){const C=s[h++],v=31&C,x=64&C,R=x?2+v*3:0,b=new Uint8Array(R);if(x){b[0]=C;for(let D=1;D<R;D++)b[D]=s[h++]}i.push({type:A,payloadType:a,pts:t,bytes:b})}}}}}else if(a===5&&o>16){const d=[];for(let A=0;A<16;A++){const C=s[h++].toString(16);d.push(C.length==1?"0"+C:C),(A===3||A===5||A===7||A===9)&&d.push("-")}const g=o-16,m=new Uint8Array(g);for(let A=0;A<g;A++)m[A]=s[h++];i.push({payloadType:a,pts:t,uuid:d.join(""),userData:Fh(m),userDataBytes:m})}}}function go(n){const e=n.byteLength;let t,i=n.indexOf(3,3);for(;i!==-1;)n[i-1]===0&&n[i-2]===0&&(t||(t=[])).push(i),i=n.indexOf(3,i+1);if(!t)return n;const s=e-t.length,r=new Uint8Array(s);let a=0,o=0;for(let l=0;l<s;o++,l++)o===t[a]&&(o++,a++),r[l]=n[o];return r}function Hh(n){const e=n[0];let t="",i="",s=0,r=0,a,o=0,l=0,u=4;if(e===0){const d=zs(n,u),g=d!==null?zs(n,u+d.length):null;d!==null&&g!==null?(t=d,i=g,u+=d.length+g.length,s=ce(n,u),u+=4,r=ce(n,u),u+=4,o=ce(n,u),u+=4,l=ce(n,u),u+=4):(Ge.warn(`Unterminated ${d===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),u=n.length)}else if(e===1){s=ce(n,u),u+=4;const d=ce(n,u);u+=4;const g=ce(n,u);u+=4,a=2**32*d+g,qc(a)||(a=Number.MAX_SAFE_INTEGER,Ge.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ce(n,u),u+=4,l=ce(n,u),u+=4;const m=zs(n,u),A=m!==null?zs(n,u+m.length):null;m!==null&&(t=m,u+=m.length),A!==null?(i=A,u+=A.length):(Ge.warn(`Unterminated ${m===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${m===null?"strings and payload":"value and payload"}`),u=n.length)}const h=n.subarray(u,n.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function Vh(n,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const r=new Uint8Array(i);for(r[0]=i>>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(n,4),s=0,i=8;s<t;s++)r.set(e[s],i),i+=e[s].byteLength;return r}function Kh(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let r;i>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Vh([112,115,115,104],new Uint8Array([i,0,0,0]),n,r,s,a,t)}function po(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let i=0;for(;i+32<t;){const s=new DataView(n,i),r=Wh(s);e.push(r),i+=r.size}}return e}function Yh(n){const e=[];for(let t=0;t<n.length;){const i=n[t++],s=i&7;if(s===0){for(;n[t++]&128;);continue}if(s!==2){t+=s===1?8:4;continue}let r=0;for(let a=0,o=128;o&128;a+=7)r|=((o=n[t++])&127)<<a;if(i>>3===2)if(r===32){const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(n[t+o*2],n[t+o*2+1]),16);e.push(a)}else r===16&&e.push(n.subarray(t,t+16));t+=r}return e}function Wh(n){const e=n.getUint32(0),t=n.byteOffset,i=n.byteLength;if(i<e)return{offset:t,size:i};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=ut(new Uint8Array(a,t+12,16));let l=null,u=null,h=0;if(r===0)h=28;else{const g=n.getUint32(28);if(!g||i<32+g*16)return{offset:t,size:e};l=[];for(let m=0;m<g;m++)l.push(new Uint8Array(a,t+32+m*16,16));h=32+g*16}if(!h)return{offset:t,size:e};const d=n.getUint32(h);return e-32<d?{offset:t,size:e}:(u=new Uint8Array(a,t+h+4,d),r===0&&(l=Yh(u)),{version:r,systemId:o,kids:l,data:u,offset:t,size:e})}const Wi=mo("userAgent"),jh=mo("vendor");let sn,rn,nn;function mo(n){try{return navigator[n]||""}catch{}return""}function qh(){if(nn===void 0){const n=Wi.match(/Safari\/(\d+)/i);nn=n?parseInt(n[1]):0}return nn}function ms(){if(sn===void 0){const n=Wi.match(/Chrome\/(\d+)/i);sn=n?parseInt(n[1]):0}return sn}function zh(){if(rn===void 0){const n=Wi.match(/Firefox\/(\d+)/i);rn=n?parseInt(n[1]):0}return rn}function Ao(){return/\(Windows.+Firefox\//i.test(Wi)}function Xh(){return jh.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Wi)}function Zh(){return/Android/.test(Wi)}const ji={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function an(n,e){const t=ji[e];return!!t&&!!t[n.slice(0,4)]}function As(n,e,t=!0){return!n.split(",").some(i=>!on(i,e,t))}function on(n,e,t=!0){var i;const s=Ei(t);return(i=s?.isTypeSupported(Is(n,e)))!=null?i:!1}function Is(n,e){return`${e}/mp4;codecs=${n}`}function Io(n){if(n){const e=n.substring(0,4);return ji.video[e]}return 2}function Qs(n){const e=Ao();return n.split(",").reduce((t,i)=>{const r=e&&gs(i)?9:ji.video[i];return r?(r*2+t)/(t?3:2):(ji.audio[i]+t)/(t?2:1)},0)}const ln={};function Qh(n,e=!0){if(ln[n])return ln[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let s=0;s<t.length;s++){var i;if(on(t[s],"audio",e))return ln[n]=t[s],t[s];if(t[s]==="mp3"&&(i=Ei(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return n}const Jh=/flac|opus|mp4a\.40\.34/i;function Js(n,e=!0){return n.replace(Jh,t=>Qh(t.toLowerCase(),e))}function ed(n,e){const t=[];if(n){const i=n.split(",");for(let s=0;s<i.length;s++)an(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function er(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Co(n,"audio")||Co(n,"video")))return n;if(e){const t=e.split(",");if(t.length>1){if(n){for(let i=t.length;i--;)if(t[i].substring(0,4)===n.substring(0,4))return t[i]}return t[0]}}return e||n}function Co(n,e){return an(n,e)&&on(n,e)}function td(n){const e=n.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function id(n){if(n.startsWith("av01.")){const e=n.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return n}function yo(n){const e=Ei(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function un(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const sd={supported:!0,powerEfficient:!0,smooth:!0},rd={supported:!1,smooth:!1,powerEfficient:!1},vo={supported:!0,configurations:[],decodingInfoResults:[sd]};function Eo(n,e){return{supported:!1,configurations:e,decodingInfoResults:[rd],error:n}}function nd(n,e,t,i,s,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,l=r?.audioCodec,u=r?.channels,h=u?parseInt(u):l?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((g,m)=>{if(m){const A=e.groups[m];if(!A)throw new Error(`Audio track group ${m} not found`);Object.keys(A.channels).forEach(C=>{g[C]=(g[C]||0)+A.channels[C]})}return g},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(g=>gs(g))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(i,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(s,8e6))||!!d&&se(h)&&Object.keys(d).some(g=>parseInt(g)>h)}function To(n,e,t,i={}){const s=n.videoCodec;if(!s&&!n.audioCodec||!t)return Promise.resolve(vo);const r=[],a=ad(n),o=a.length,l=od(n,e,o>0),u=l.length;for(let h=o||1*u||1;h--;){const d={type:"media-source"};if(o&&(d.video=a[h%o]),u){d.audio=l[h%u];const g=d.audio.bitrate;d.video&&g&&(d.video.bitrate-=g)}r.push(d)}if(s){const h=navigator.userAgent;if(s.split(",").some(d=>gs(d))&&Ao())return Promise.resolve(Eo(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const d=ld(h);return i[d]||(i[d]=t.decodingInfo(h))})).then(h=>({supported:!h.some(d=>!d.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function ad(n){var e;const t=(e=n.videoCodec)==null?void 0:e.split(","),i=xo(n),s=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(l=>{const u={contentType:Is(id(l),"video"),width:s,height:r,bitrate:i,framerate:a};return o!=="sdr"&&(u.transferFunction=o),u}):[]}function od(n,e,t){var i;const s=(i=n.audioCodec)==null?void 0:i.split(","),r=xo(n);return s&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var l;const u=o?(l=e.groups[o])==null?void 0:l.tracks:null;return u?u.reduce((h,d)=>{if(d.groupId===o){const g=parseFloat(d.channels||"");s.forEach(m=>{const A={contentType:Is(m,"audio"),bitrate:t?So(m,r):r};g&&(A.channels=""+g),h.push(A)})}return h},a):a},[]):[]}function So(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function xo(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function ld(n){let e="";const{audio:t,video:i}=n;if(i){const s=un(i.contentType);e+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){const s=un(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}function Ti(n,e,t){const i=encodeURIComponent(e),s=`${i}=${encodeURIComponent(t)}`;let r=!1;const a=[];n.search.substring(1).split("&").forEach(o=>{o===i||o.startsWith(i+"=")?r||(a.push(s),r=!0):o&&a.push(o)}),r||a.push(s),n.search=a.join("&")}const cn=["NONE","TYPE-0","TYPE-1",null];function ud(n){return cn.indexOf(n)>-1}const tr=["SDR","PQ","HLG"];function cd(n){return!!n&&tr.indexOf(n)>-1}var ir={No:"",Yes:"YES",v2:"v2"};function bo(n){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=n,s=i<e/2;return e&&s?t?ir.v2:ir.Yes:ir.No}class Lo{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&Ti(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Ti(t,"_HLS_part",this.part.toString()),this.skip&&Ti(t,"_HLS_skip",this.skip),t.href}}class Cs{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Ro(this._audioGroups,e)}hasSubtitleGroup(e){return Ro(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Ro(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function hd(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function dd(n,e){let t=!1,i=[];if(n&&(t=n!=="SDR",i=[n]),e){i=e.allowedVideoRanges||tr.slice(0);const s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&hd(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}const fd=n=>{const e=new WeakSet;return(t,i)=>{if(n&&(i=n(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},Xe=(n,e)=>JSON.stringify(n,fd(e));function gd(n,e,t,i,s){const r=Object.keys(n),a=i?.channels,o=i?.audioCodec,l=s?.videoCodec,u=a&&parseInt(a)===2;let h=!1,d=!1,g=1/0,m=1/0,A=1/0,C=1/0,v=0,x=[];const{preferHDR:R,allowedVideoRanges:b}=dd(e,s);for(let $=r.length;$--;){const N=n[r[$]];h||(h=N.channels[2]>0),g=Math.min(g,N.minHeight),m=Math.min(m,N.minFramerate),A=Math.min(A,N.minBitrate),b.filter(W=>N.videoRanges[W]>0).length>0&&(d=!0)}g=se(g)?g:0,m=se(m)?m:0;const D=Math.max(1080,g),_=Math.max(30,m);A=se(A)?A:t,t=Math.max(A,t),d||(e=void 0);const M=r.length>1;return{codecSet:r.reduce(($,N)=>{const O=n[N];if(N===$)return $;if(x=d?b.filter(W=>O.videoRanges[W]>0):[],M){if(O.minBitrate>t)return ti(N,`min bitrate of ${O.minBitrate} > current estimate of ${t}`),$;if(!O.hasDefaultAudio)return ti(N,"no renditions with default or auto-select sound found"),$;if(o&&N.indexOf(o.substring(0,4))%5!==0)return ti(N,`audio codec preference "${o}" not found`),$;if(a&&!u){if(!O.channels[a])return ti(N,`no renditions with ${a} channel sound found (channels options: ${Object.keys(O.channels)})`),$}else if((!o||u)&&h&&O.channels[2]===0)return ti(N,"no renditions with stereo sound found"),$;if(O.minHeight>D)return ti(N,`min resolution of ${O.minHeight} > maximum of ${D}`),$;if(O.minFramerate>_)return ti(N,`min framerate of ${O.minFramerate} > maximum of ${_}`),$;if(!x.some(W=>O.videoRanges[W]>0))return ti(N,`no variants with VIDEO-RANGE of ${Xe(x)} found`),$;if(l&&N.indexOf(l.substring(0,4))%5!==0)return ti(N,`video codec preference "${l}" not found`),$;if(O.maxScore<v)return ti(N,`max score of ${O.maxScore} < selected max of ${v}`),$}return $&&(Qs(N)>=Qs($)||O.fragmentError>n[$].fragmentError)?$:(C=O.minIndex,v=O.maxScore,N)},void 0),videoRanges:x,preferHDR:R,minFramerate:m,minBitrate:A,minIndex:C}}function ti(n,e){Ge.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Do(n){return n.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 pd(n,e,t,i){return n.slice(t,i+1).reduce((s,r,a)=>{if(!r.codecSet)return s;const o=r.audioGroups;let l=s[r.codecSet];l||(s[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const u=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,u),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const d=e.groups[h];d&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(g=>{l.channels[g]=(l.channels[g]||0)+d.channels[g]}))}),s},{})}function Po(n){if(!n)return n;const{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:r}}function ii(n,e,t){if("attrs"in n){const i=e.indexOf(n);if(i!==-1)return i}for(let i=0;i<e.length;i++){const s=e[i];if(wi(n,s,t))return i}return-1}function wi(n,e,t){const{groupId:i,name:s,lang:r,assocLang:a,default:o}=n,l=n.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(r===void 0||md(r,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in n)||Ad(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function md(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function Ad(n,e=""){const t=n.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function Mi(n,e){const{audioCodec:t,channels:i}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Id(n,e,t,i,s){const r=e[i],o=e.reduce((g,m,A)=>{const C=m.uri;return(g[C]||(g[C]=[])).push(A),g},{})[r.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=r.videoRange,u=r.frameRate,h=r.codecSet.substring(0,4),d=_o(e,i,g=>{if(g.videoRange!==l||g.frameRate!==u||g.codecSet.substring(0,4)!==h)return!1;const m=g.audioGroups,A=t.filter(C=>ys(C.groupId,m));return ii(n,A,s)>-1});return d>-1?d:_o(e,i,g=>{const m=g.audioGroups,A=t.filter(C=>ys(C.groupId,m));return ii(n,A,s)>-1})}function _o(n,e,t){for(let i=e;i>-1;i--)if(t(n[i]))return i;for(let i=e+1;i<n.length;i++)if(t(n[i]))return i;return-1}function sr(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}function ys(n,e){return e?e.indexOf(n)!==-1:!0}function ko(n,e){if(e||n){const t=je({},e);return n&&(n.videoCodec&&(t.videoCodec=n.videoCodec),n.videoRange&&(t.allowedVideoRanges=[n.videoRange])),t}}class Cd extends wt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!s||!l)return;const u=performance.now(),h=r?r.stats:s.stats,d=r?r.duration:s.duration,g=u-h.loading.start,m=a.minAutoLevel,A=s.level,C=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||A<=m){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=C>-1&&C!==A,x=!!t||v;if(!x&&(l.paused||!l.playbackRate||!l.readyState))return;const R=a.mainForwardBufferInfo;if(!x&&R===null)return;const b=this.bwEstimator.getEstimateTTFB(),D=Math.abs(l.playbackRate);if(g<=Math.max(b,1e3*(d/(D*2))))return;const _=R?R.len/D:0,M=h.loading.first?h.loading.first-h.loading.start:-1,p=h.loaded&&M>-1,$=this.getBwEstimate(),N=a.levels,O=N[A],W=Math.max(h.loaded,Math.round(d*(s.bitrate||O.averageBitrate)/8));let q=p?g-M:g;q<1&&p&&(q=Math.min(g,h.loaded*8/$));const z=p?h.loaded*1e3/q:0,oe=b/1e3,re=z?(W-h.loaded)/z:W*8/$+oe;if(re<=_)return;const J=z?z*8:$,Z=((i=t?.details||a.latestLevelDetails)==null?void 0:i.live)===!0,Q=a.config.abrBandWidthUpFactor;let ee=Number.POSITIVE_INFINITY,he;for(he=A-1;he>m;he--){const Ie=N[he].maxBitrate,_e=!N[he].details||Z;if(ee=this.getTimeToLoadFrag(oe,J,d*Ie,_e),ee<Math.min(_,d+oe))break}if(ee>=re||ee>d*10)return;p?this.bwEstimator.sample(g-Math.min(b,M),h.loaded):this.bwEstimator.sampleTTFB(g);const te=N[he].maxBitrate;this.getBwEstimate()*Q>te&&(this.firstAutoFloor=Math.min(he,a.firstLevel),this.resetEstimator(te));const ne=this.findBestLevel(te,m,he,0,_,1,1);ne>-1&&(he=ne),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${A} is loading too slowly;
|
|
2
|
-
Fragment duration: ${s.duration.toFixed(3)}
|
|
3
|
-
Time to underbuffer: ${_.toFixed(3)} s
|
|
4
|
-
Estimated load time for current fragment: ${re.toFixed(3)} s
|
|
5
|
-
Estimated load time for down switch fragment: ${ee.toFixed(3)} s
|
|
6
|
-
TTFB estimate: ${M|0} ms
|
|
7
|
-
Current BW estimate: ${se($)?$|0:"Unknown"} bps
|
|
8
|
-
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
9
|
-
Switching to level ${he} @ ${te|0} bps`),a.nextLoadLevel=a.nextAutoLevel=he,this.clearTimer();const Ee=()=>{this.clearTimer();const Ie=this.hls;if(this.fragCurrent===s&&Ie.loadLevel===he&&he>0){const _e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${he>0?"and switching down":""}
|
|
10
|
-
Fragment duration: ${s.duration.toFixed(3)} s
|
|
11
|
-
Time to underbuffer: ${_e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,he>m){let ye=this.findBestLevel(Ie.levels[m].bitrate,m,he,0,_e,1,1);ye===-1&&(ye=m),Ie.nextLoadLevel=Ie.nextAutoLevel=ye,this.firstAutoFloor=Math.min(ye,Ie.firstLevel),this.resetEstimator(Ie.levels[ye].bitrate)}}};v||re>ee*2?Ee():this.timer=self.setInterval(Ee,ee*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new nh(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case U.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&Kr(i,s)){const a=performance.now(),o=r?r.stats:i.stats,l=a-o.loading.start,u=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&u>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,u),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){const r=e+i/t,a=s?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;se(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,t){var i;const{frag:s,part:r}=t,a=r?r.stats:s.stats;if(s.type===ge.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){const o=r?r.duration:s.duration,l=this.hls.levels[s.level],u=(l.loaded?l.loaded.bytes:0)+a.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:h},l.realBitrate=Math.round(8*u/h)}if(s.bitrateTest){const o={stats:a,frag:s,part:r,id:s.type};this.onFragBuffered(E.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const o=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==ge.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:i}=e,s=this.getBwEstimate(),r=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(s,i,t,r/2,a,1,1);if(o>-1)return o;const l=e.firstLevel,u=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,h=Math.min(Math.max(l,i),t,u);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),u=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(u){const v=this.findBestLevel(l,a,s,u,0,h,d);if(v>=0)return this.rebufferNotice=-1,v}let g=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!u){const v=this.bitrateTestDelay;v&&(g=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),h=d=1)}const m=this.findBestLevel(l,a,s,u,g,h,d);if(this.rebufferNotice!==m&&(this.rebufferNotice=m,this.info(`${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${m}`)),m>-1)return m;const A=i.levels[a],C=i.loadLevelObj;return C&&A?.bitrate<C.bitrate?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e?.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,s,r,a,o){const{hls:l,lastLoadedFragLevel:u,fragCurrent:h,partCurrent:d}=this;if(!l)return-1;const g=s+r,m=u===-1?l.firstLevel:u,{levels:A,allAudioTracks:C,loadLevel:v,latestLevelDetails:x,config:R}=l;if(A.length===1)return 0;const b=A[m],D=!!(x!=null&&x.live),_=v===-1||u===-1;let M,p="SDR",$=b?.frameRate||0;const{audioPreference:N,videoPreference:O}=R,W=this.audioTracksByGroup||(this.audioTracksByGroup=Do(C));let q=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;const Z=this.codecTiers||(this.codecTiers=pd(A,W,t,i)),Q=gd(Z,p,e,N,O),{codecSet:ee,videoRanges:he,minFramerate:te,minBitrate:ne,minIndex:Ee,preferHDR:Ie}=Q;q=Ee,M=ee,p=Ie?he[he.length-1]:he[0],$=te,e=Math.max(e,ne),this.log(`picked start tier ${Xe(Q)}`)}else M=b?.codecSet,p=b?.videoRange;const z=d?d.duration:h?h.duration:0,oe=this.bwEstimator.getEstimateTTFB()/1e3,re=[];for(let Z=i;Z>=t;Z--){var J;const Q=A[Z],ee=Z>m;if(!Q)continue;if(R.useMediaCapabilities&&!Q.supportedResult&&!Q.supportedPromise){const ye=navigator.mediaCapabilities;typeof ye?.decodingInfo=="function"&&nd(Q,W,p,$,e,N)?(Q.supportedPromise=To(Q,W,ye,this.supportedCache),Q.supportedPromise.then(Oe=>{if(!this.hls)return;Q.supportedResult=Oe;const Le=this.hls.levels,Fe=Le.indexOf(Q);Oe.error?this.warn(`MediaCapabilities decodingInfo error: "${Oe.error}" for level ${Fe} ${Xe(Oe)}`):Oe.supported?Oe.decodingInfoResults.some(Ye=>Ye.smooth===!1||Ye.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Fe} not smooth or powerEfficient: ${Xe(Oe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Fe} ${Xe(Oe)}`),Fe>-1&&Le.length>1&&(this.log(`Removing unsupported level ${Fe}`),this.hls.removeLevel(Fe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Oe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Oe}`)})):Q.supportedResult=vo}if((M&&Q.codecSet!==M||p&&Q.videoRange!==p||ee&&$>Q.frameRate||!ee&&$>0&&$<Q.frameRate||(J=Q.supportedResult)!=null&&(J=J.decodingInfoResults)!=null&&J.some(ye=>ye.smooth===!1))&&(!_||Z!==q)){re.push(Z);continue}const he=Q.details,te=(d?he?.partTarget:he?.averagetargetduration)||z||1;let ne;ee?ne=o*e:ne=a*e;const Ee=z&&s>=z*2&&r===0?Q.averageBitrate:Q.maxBitrate,Ie=this.getTimeToLoadFrag(oe,ne,Ee*te,!he||he.live);if(ne>=Ee&&(Z===u||Q.loadError===0&&Q.fragmentError===0||Ya(Q,R.errorPenaltyExpireMs))&&(Ie<=oe||!se(Ie)||D&&!this.bitrateTestDelay||Ie<g)){const ye=this.forcedAutoLevel;return Z!==v&&(ye===-1||ye!==v)&&(re.length&&this.trace(`Skipped level(s) ${re.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${A[re[0]].codecs}" ${A[re[0]].videoRange}; not compatible with "${M}" ${p}`),this.info(`switch candidate:${m}->${Z} adjustedbw(${Math.round(ne)})-bitrate=${Math.round(ne-Ee)} ttfb:${oe.toFixed(1)} avgDuration:${te.toFixed(1)} maxFetchDuration:${g.toFixed(1)} fetchDuration:${Ie.toFixed(1)} firstSelection:${_} codecSet:${Q.codecSet} videoRange:${Q.videoRange} hls.loadLevel:${v}`)),_&&(this.firstSelection=Z),Z}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}const wo={search:function(n,e){let t=0,i=n.length-1,s=null,r=null;for(;t<=i;){s=(t+i)/2|0,r=n[s];const a=e(r);if(a>0)t=s+1;else if(a<0)i=s-1;else return r}return null}};function yd(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!se(e))return null;const i=n[0].programDateTime;if(e<(i||0))return null;const s=n[n.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Ed(e,t,a))return a}return null}function qi(n,e,t=0,i=0,s=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&Mo(t,i,r)===0||vd(r,n,Math.min(s,i))))return r;const a=wo.search(e,Mo.bind(null,t,i));return a&&(a!==n||!r)?a:r}function vd(n,e,t){if(e?.start===0&&e.level<n.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((s,r)=>(r[0]==="INF"&&(s+=parseFloat(r[1])),s),t);return n.start<=i}return!1}function Mo(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=n?1:t.start-i>n&&t.start?-1:0}function Ed(n,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>n}function Oo(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let i=n.fragments;const{fragmentHint:s}=n;s&&(i=i.concat(s));let r;return wo.search(i,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function Fo(n,e){return e===n.endSN&&n.fragmentHint?n.fragmentHint:n.fragments[1+e-n.startSN]||null}var gt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},dt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Td extends wt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===ge.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,r=t.context;switch(t.details){case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case U.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=vs();return}case U.FRAG_GAP:case U.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=gt.SendAlternateToPenaltyBox;return}case U.PLAYLIST_UNCHANGED_ERROR:case U.LEVEL_EMPTY_ERROR:case U.LEVEL_PARSING_ERROR:{var a;const o=t.parent===ge.MAIN?t.level:s.loadLevel;t.details===U.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_LOAD_ERROR:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=s.loadLevelObj;if(o&&(r.type===ke.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===ke.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=gt.SendAlternateToPenaltyBox,t.errorAction.flags=dt.MoveAllAlternatesMatchingHost;return}}return;case U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:gt.SendAlternateToPenaltyBox,flags:dt.MoveAllAlternatesMatchingHDCP};return;case U.KEY_SYSTEM_SESSION_UPDATE_FAILED:case U.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case U.KEY_SYSTEM_NO_SESSION:t.errorAction={action:gt.SendAlternateToPenaltyBox,flags:dt.MoveAllAlternatesMatchingKey};return;case U.BUFFER_ADD_CODEC_ERROR:case U.REMUX_ALLOC_ERROR:case U.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case U.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=dt.ResetMediaSource|dt.SwitchToSDR;return;case U.INTERNAL_EXCEPTION:case U.BUFFER_APPENDING_ERROR:case U.BUFFER_APPEND_NO_PROGRESS:case U.BUFFER_FULL_ERROR:case U.LEVEL_SWITCH_ERROR:case U.BUFFER_STALLED_ERROR:case U.BUFFER_SEEK_OVER_HOLE:case U.BUFFER_NUDGE_ON_STALL:t.errorAction=vs();return}t.type===me.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=vs())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=Va(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(hs(s,r,Ks(e),e.response))return{action:gt.RetryRequest,flags:dt.None,retryConfig:s,retryCount:r};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Va(Ga(e)?a:r,e),l=t.levels.reduce((h,d)=>h+d.fragmentError,0);if(s&&(e.details!==U.FRAG_GAP&&s.fragmentError++,!Ha(e)&&hs(o,l,Ks(e),e.response)))return{action:gt.RetryRequest,flags:dt.None,retryConfig:o,retryCount:l};const u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,a;const u=e.details;s.loadError++,s.loadErrorTime=self.performance.now(),u===U.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:d,loadLevel:g,minAutoLevel:m,maxAutoLevel:A}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const C=(r=e.frag)==null?void 0:r.type,x=(C===ge.AUDIO&&u===U.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&No(e))&&d.some(({audioCodec:M})=>s.audioCodec!==M),b=e.sourceBufferName==="video"&&No(e)&&d.some(({codecSet:M,audioCodec:p})=>s.codecSet!==M&&s.audioCodec===p),{type:D,groupId:_}=(a=e.context)!=null?a:{};for(let M=d.length;M--;){const p=(M+g)%d.length;if(p!==g&&p>=m&&p<=A&&(d[p].loadError===0||Ya(d[p],i.config.errorPenaltyExpireMs))){var o,l;const $=d[p];if(u===U.FRAG_GAP&&C===ge.MAIN&&e.frag){const N=d[p].details;if(N){const O=qi(e.frag,N.fragments,e.frag.start);if(O!=null&&O.gap)continue}}else{if(D===ke.AUDIO_TRACK&&$.hasAudioGroup(_)||D===ke.SUBTITLE_TRACK&&$.hasSubtitleGroup(_))continue;if(C===ge.AUDIO&&(o=s.audioGroups)!=null&&o.some(N=>$.hasAudioGroup(N))||C===ge.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(N=>$.hasSubtitleGroup(N))||x&&s.audioCodec===$.audioCodec||b&&s.codecSet===$.codecSet||!x&&s.audioCodec!==$.audioCodec)continue}h=p;break}}if(h>-1&&i.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:gt.SendAlternateToPenaltyBox,flags:dt.None,nextAutoLevel:h}}return{action:gt.SendAlternateToPenaltyBox,flags:dt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,s;switch((i=t.errorAction)==null?void 0:i.action){case gt.DoNothing:break;case gt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==U.FRAG_GAP&&t.details!==U.PLAYLIST_UNCHANGED_ERROR&&!Bo(t)&&(t.fatal=!0);break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&dt.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===dt.None)this.switchLevel(e,s);else if(i.flags&dt.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let u=l;u--;)o[u].videoRange!=="SDR"?(o[u].fragmentError++,o[u].loadError++):s===void 0&&(s=u)}else if(i.flags&dt.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],u=l?.attrs["HDCP-LEVEL"];i.hdcpLevel=u;const h=u==="NONE";u&&!h?(t.maxHdcpLevel=cn[cn.indexOf(u)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(h&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=dt.MoveAllAlternatesMatchingKey)}if(i.flags&dt.MoveAllAlternatesMatchingKey){const o=e.decryptdata;if(o){const l=this.hls.levels,u=l.length;for(let d=u;d--;)if(this.variantHasKey(l[d],o)){var r,a;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(r=l[d].audioGroups)==null?void 0:r.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${ut(o.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const h=e.frag;if(this.hls.levels.length<u)i.resolved=!0;else if(h&&h.type!==ge.MAIN){const d=h.decryptdata;d&&!o.matches(d)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===U.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=un(e.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}}function No(n){const e=n.details;return e===U.BUFFER_ADD_CODEC_ERROR||e===U.MEDIA_SOURCE_REQUIRES_RESET||e===U.BUFFER_APPEND_ERROR&&!Bo(n)}function Bo(n){return n.details===U.BUFFER_APPEND_ERROR&&(n.error.name==="QuotaExceededError"||n.error.name==="InvalidStateError")}function vs(n){const e={action:gt.DoNothing,flags:dt.None};return n&&(e.resolved=!0),e}var et={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Sd{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}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 a=r.length;a--;){const o=s[r[a]];if(o?.body.type===t&&(!i||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,s,r,a){this.timeRanges&&(this.timeRanges[e]=t);const o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{const u=this.fragments[l];if(!u||!this.hls)return;const h=u.body;if(o>=h.sn)return;if(!u.buffered&&(!u.loaded||a)){h.type===i&&this.removeFragment(h);return}const d=u.range[e];if(d){if(d.time.length===0){this.removeFragment(h);return}if(d.time.some(g=>{const m=!this.isTimeBuffered(g.startPTS,g.endPTS,t);return m&&this.removeFragment(h),m}),s&&s!==h&&ms()){const g=s.endPTS,m=h.startPTS;if(g&&m&&u.range.video){const A=m-g;A<0&&A>-.1&&(this.removeFragment(h),this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:g+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s,id:r}=e;if(!t||!st(i))return;const a=zi(i),o=this.fragments[a];if(!o||o.buffered&&i.gap)return;const l=!i.relurl;Object.keys(t).forEach(h=>{const d=i.elementaryStreams[h];if(!d)return;const g=t[h],m=l||d.partial===!0;o.range[h]=this.getBufferedTimes(i,s,m,g),this.detectEvictedFragments(h,g,r,i,s)}),o.loaded=null;const u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),rr(o)||this.removeParts(i.sn-1,i.type),!s){const h=Math.min(.004,i.duration);u.some(d=>{var g;const m=(g=o.range[d])==null?void 0:g.time,A=m.length===0||m.length===1&&m[0].endPTS-m[0].startPTS<h;return A&&this.addAsGap(i),A})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=Uo(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=zi(e);let s=this.fragments[i];return!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e)),s}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,u=e.maxStartPTS||a;for(let h=0;h<s.length;h++){const d=s.start(h)-this.bufferPadding,g=s.end(h)+this.bufferPadding;if(u>=d&&l<=g){r.time.push({startPTS:Math.max(a,s.start(h)),endPTS:Math.min(o,s.end(h))});break}else if(a<g&&o>d){const m=Math.max(a,s.start(h)),A=Math.min(o,s.end(h));A>m&&(r.partial=!0,r.time.push({startPTS:m,endPTS:A}))}else if(o<=d)break}return r}getPartialFragment(e){let t=null,i,s,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(u=>{const h=l[u];h&&rr(h)&&(s=h.body.start-o,r=h.body.end+o,e>=s&&e<=r&&(i=Math.min(e-s,r-e),a<=i&&(t=h.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||rr(t))}getState(e){const t=zi(e),i=this.fragments[t];return i?i.buffered?rr(i)?et.PARTIAL:et.OK:et.APPENDING:et.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,r=i.end(a)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!st(t.frag)||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=zi(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}=t;if(!st(i))return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=zi(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(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){const{fragments:s}=this;let r=0,a=0;const o=Object.keys(s);for(let l=0;l<o.length;l++){const u=s[o[l]];if(!u||!u.buffered||u.body.type!==t)continue;const h=u.body;if(h.gap)return 0;const d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&h.bitrate*8*h.duration;if(h.end<=e&&d&&(r+=d,a=Math.max(a,h.end),r>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=zi(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=Uo(i,r=>r.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}}function rr(n){var e,t,i,s;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(i=n.range.audiovideo)!=null&&i.partial||(s=n.range.subs)!=null&&s.partial)}function zi(n){return`${n.type}_${n.level}_${n.sn}`}function Uo(n,e){return n.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Si={cbc:0,ctr:1};class xd{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 Si.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Si.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function bd(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class Ld{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],a=i[2],o=i[3],l=this.invSubMix,u=l[0],h=l[1],d=l[2],g=l[3],m=new Uint32Array(256);let A=0,C=0,v=0;for(v=0;v<256;v++)v<128?m[v]=v<<1:m[v]=v<<1^283;for(v=0;v<256;v++){let x=C^C<<1^C<<2^C<<3^C<<4;x=x>>>8^x&255^99,e[A]=x,t[x]=A;const R=m[A],b=m[R],D=m[b];let _=m[x]*257^x*16843008;s[A]=_<<24|_>>>8,r[A]=_<<16|_>>>16,a[A]=_<<8|_>>>24,o[A]=_,_=D*16843009^b*65537^R*257^A*16843008,u[x]=_<<24|_>>>8,h[x]=_<<16|_>>>16,d[x]=_<<8|_>>>24,g[x]=_,A?(A=R^m[m[m[D^R]]],C^=m[m[C]]):A=C=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(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const u=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),d=this.sBox,g=this.rcon,m=this.invSubMix,A=m[0],C=m[1],v=m[2],x=m[3];let R,b;for(o=0;o<a;o++){if(o<r){R=u[o]=t[o];continue}b=R,o%r===0?(b=b<<8|b>>>24,b=d[b>>>24]<<24|d[b>>>16&255]<<16|d[b>>>8&255]<<8|d[b&255],b^=g[o/r|0]<<24):r>6&&o%r===4&&(b=d[b>>>24]<<24|d[b>>>16&255]<<16|d[b>>>8&255]<<8|d[b&255]),u[o]=R=(u[o-r]^b)>>>0}for(l=0;l<a;l++)o=a-l,l&3?b=u[o]:b=u[o-4],l<4||o<=4?h[l]=b:h[l]=A[d[b>>>24]]^C[d[b>>>16&255]]^v[d[b>>>8&255]]^x[d[b&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],u=o[1],h=o[2],d=o[3],g=this.uint8ArrayToUint32Array_(i);let m=g[0],A=g[1],C=g[2],v=g[3];const x=new Int32Array(e),R=new Int32Array(x.length);let b,D,_,M,p,$,N,O,W,q,z,oe,re,J;const Z=this.networkToHostOrderSwap;for(;t<x.length;){for(W=Z(x[t]),q=Z(x[t+1]),z=Z(x[t+2]),oe=Z(x[t+3]),p=W^r[0],$=oe^r[1],N=z^r[2],O=q^r[3],re=4,J=1;J<s;J++)b=l[p>>>24]^u[$>>16&255]^h[N>>8&255]^d[O&255]^r[re],D=l[$>>>24]^u[N>>16&255]^h[O>>8&255]^d[p&255]^r[re+1],_=l[N>>>24]^u[O>>16&255]^h[p>>8&255]^d[$&255]^r[re+2],M=l[O>>>24]^u[p>>16&255]^h[$>>8&255]^d[N&255]^r[re+3],p=b,$=D,N=_,O=M,re=re+4;b=a[p>>>24]<<24^a[$>>16&255]<<16^a[N>>8&255]<<8^a[O&255]^r[re],D=a[$>>>24]<<24^a[N>>16&255]<<16^a[O>>8&255]<<8^a[p&255]^r[re+1],_=a[N>>>24]<<24^a[O>>16&255]<<16^a[p>>8&255]<<8^a[$&255]^r[re+2],M=a[O>>>24]<<24^a[p>>16&255]<<16^a[$>>8&255]<<8^a[N&255]^r[re+3],R[t]=Z(b^m),R[t+1]=Z(M^A),R[t+2]=Z(_^C),R[t+3]=Z(D^v),m=W,A=q,C=z,v=oe,t=t+4}return R.buffer}}class Rd{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=Dd(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Dd(n){switch(n){case Si.cbc:return"AES-CBC";case Si.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const Pd=16;class hn{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);this.reset();const s=this.decryptRange;return s?s.start===0&&s.end>=i.length?i:i.slice(s.start,s.end):bd(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s,r){return this.decryptRange=r,this.useSoftware||r?new Promise((a,o)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,s);const u=this.flush();u?a(u.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:a,remainderData:o}=this;if(s!==Si.cbc||t.byteLength!==16)return Ge.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Bt(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;r&&(i=r);let u=this.softwareDecrypter;u||(u=this.softwareDecrypter=new Ld),u.expandKey(t);const h=a;return this.currentResult=u.decrypt(l.buffer,0,i),this.currentIV=l.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 Rd(this.subtle,t,s)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new xd(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Ge.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 a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%Pd;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Ge.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const $o=Math.pow(2,17);class Go{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,i,s){const r=e.url;if(!r)return Promise.reject(new si({type:me.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,o=a.fLoader,l=a.loader;return new Promise((u,h)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(v=>v[0]==="GAP")){h(Vo(e));return}else e.gap=!1;const d=this.loader=o?new o(a):new l(a),g=Ho(e,null,t);e.loader=d;const m=Ka(a.fragLoadPolicy.default),A={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:$o};d.stats.retry=e.stats.retry,e.stats=d.stats;const C={onSuccess:(v,x,R,b)=>{this.resetLoader(e,d);let D=v.data;R.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(D.slice(0,16)),D=D.slice(16)),u({frag:e,part:null,payload:D,networkDetails:b})},onError:(v,x,R,b)=>{this.resetLoader(e,d),h(new si({type:me.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ae({url:r,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:R,stats:b}))},onAbort:(v,x,R)=>{this.resetLoader(e,d),h(new si({type:me.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:R,stats:v}))},onTimeout:(v,x,R)=>{this.resetLoader(e,d),h(new si({type:me.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${A.timeout}ms`),networkDetails:R,stats:v}))}};if(i){const v=this.gateProgress(i,s);C.onProgress=(x,R,b,D)=>v({frag:e,part:null,payload:b,networkDetails:D})}d.load(g,A,C)})}gateProgress(e,t){let i=e;if(t){const s=[];let r=!1;t.then(()=>{r=!0,s.forEach(a=>e(a)),s.length=0}).catch(()=>{}),i=a=>{r?e(a):s.push(a)}}return i}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Vo(e,t));return}const u=this.loader=r?new r(s):new a(s),h=Ho(e,t);e.loader=u;const d=Ka(s.fragLoadPolicy.default),g={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$o};t.stats=u.stats,u.load(h,g,{onSuccess:(m,A,C,v)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,t);const x={frag:e,part:t,payload:m.data,networkDetails:v};i(x),o(x)},onError:(m,A,C,v)=>{this.resetLoader(e,u),l(new si({type:me.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ae({url:h.url,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:C,stats:v}))},onAbort:(m,A,C)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,u),l(new si({type:me.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:C,stats:m}))},onTimeout:(m,A,C)=>{this.resetLoader(e,u),l(new si({type:me.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:C,stats:m}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const l=Math.round(e.duration/t.duration),u=Math.min(Math.round(i.loaded/r),l),d=(l-u)*Math.round(i.loaded/u);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Ho(n,e=null,t){const i=e||n,s={type:ke.MEDIA_FRAGMENT,frag:n,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=nr(n,e,t);return r.resetIV&&(s.resetIV=!0),r.byteRange&&(s.rangeStart=r.byteRange.start,s.rangeEnd=r.byteRange.end),s}function nr(n,e=null,t){const i={},s=e||n,r=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(se(r)&&se(a)){var o;if((n.sn==="initSegment"||t)&&_d((o=n.decryptdata)==null?void 0:o.method)){let l=Math.floor(r/16)*16;const u=Math.ceil(a/16)*16;i.decryptRange={start:r-l,end:a-l},l>=16&&(i.resetIV=!0,l=l-16),i.byteRange={start:l,end:u}}else i.byteRange={start:r,end:a}}return i}function Vo(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),i={type:me.MEDIA_ERROR,details:U.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(i.part=e),(e||n).stats.aborted=!0,new si(i)}function _d(n){return n==="AES-128"||n==="AES-256"}class si extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ko extends wt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class dn{constructor(e,t,i,s=0,r=-1,a=!1,o,l,u){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=ar(),this.buffering={audio:ar(),video:ar(),audiovideo:ar()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=a,this.duration=o||0,this.decryptRange=u,this.iframe=l||!1}}function ar(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Yo={length:0,start:()=>0,end:()=>0};class ve{static isBuffered(e,t){if(e){const i=ve.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){const t=ve.getBuffered(e);return ve.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=ve.bufferedRanges(e);if(s.length)return ve.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((h,d)=>h.start-d.start||d.end-h.end);let s=-1,r=[];if(i)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(s=h);const d=r.length;if(d){const g=r[d-1].end;e[h].start-g<i?e[h].end>g&&(r[d-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,u=t;for(let h=0;h<r.length;h++){const d=r[h].start,g=r[h].end;if(s===-1&&t>=d&&t<=g&&(s=h),t+i>=d&&t<g)l=d,u=g,a=u-t;else if(t+i<d){o=d;break}}return{len:a,start:l||0,end:u||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Yo}catch(t){return Ge.log("failed to get media.buffered",t),Yo}}}const fn=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wo(n){return fn.lastIndex=0,fn.test(n)}function gn(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(fn,i=>{const s=i.substring(2,i.length-1),r=t?.[s];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):r})}return e}function jo(n,e,t){let i=n.variableList;i||(n.variableList=i={});let s,r;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(s))r=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,r=e.VALUE;s in i?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=r||""}function kd(n,e,t){const i=e.IMPORT;if(t&&i in t){let s=n.variableList;s||(n.variableList=s={}),s[i]=t[i]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const wd=/^(\d+)x(\d+)$/,qo=/(.+?)=(".*?"|.*?)(?:,|$)/g;class tt{constructor(e,t){typeof e=="string"&&(e=tt.parseAttrList(e,t)),je(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,r)=>(s[r.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=wd.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(qo.lastIndex=0;(i=qo.exec(e))!==null;){const a=i[1].trim();let o=i[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let u=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":u=!0}if(t&&(l||u))o=gn(t,o);else if(!u&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ge.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}}const Md="com.apple.hls.interstitial";function Od(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function Fd(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class zo{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){Ge.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=je(new tt({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const r=t?.endDate||new Date(e["END-DATE"]);se(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ge.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(se(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Md}get isValid(){return!!this.id&&!this._badValueForSameId&&se(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:se(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}const Xo=10;class Nd{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?se(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Xo}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function or(n,e){return n.length===e.length?!n.some((t,i)=>t!==e[i]):!1}function Zo(n,e){return!n&&!e?!0:!n||!e?!1:or(n,e)}function Xi(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function pn(n){switch(n){case"AES-128":case"AES-256":return Si.cbc;case"AES-256-CTR":return Si.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function mn(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function Bd(n){const e=mn(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Qo(n){const e=function(i,s,r){const a=i[s];i[s]=i[r],i[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Jo(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const r=s[0]==="base64",a=s[1];r?(i.splice(-1,1),t=Qr(a)):t=Bd(a)}}return t}const lr=typeof self<"u"?self:void 0;var Je={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},pt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ur(n){switch(n){case pt.FAIRPLAY:return Je.FAIRPLAY;case pt.PLAYREADY:return Je.PLAYREADY;case pt.WIDEVINE:return Je.WIDEVINE;case pt.CLEARKEY:return Je.CLEARKEY}}var el={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function An(n){switch(n){case Je.FAIRPLAY:return pt.FAIRPLAY;case Je.PLAYREADY:return pt.PLAYREADY;case Je.WIDEVINE:return pt.WIDEVINE;case Je.CLEARKEY:return pt.CLEARKEY}}function Es(n){const{drmSystems:e,widevineLicenseUrl:t}=n,i=e?[Je.FAIRPLAY,Je.WIDEVINE,Je.PLAYREADY,Je.CLEARKEY].filter(s=>!!e[s]):[];return!i[Je.WIDEVINE]&&t&&i.push(Je.WIDEVINE),i}const tl=(function(n){return lr!=null&&(n=lr.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Ud(n,e,t,i){let s;switch(n){case Je.FAIRPLAY:s=["cenc","sinf"];break;case Je.WIDEVINE:case Je.PLAYREADY:s=["cenc"];break;case Je.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return $d(s,e,t,i)}function $d(n,e,t,i){return[{initDataTypes:n,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Gd(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function In(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=Yt(e),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=Qr(o).subarray(0,16);return Qo(l),l}}return null}let Zi={};class gi{static clearKeyUriToKeyIdMap(){Zi={}}static setKeyIdForUri(e,t){Zi[e]=t}static addKeyIdForUri(e){const t=Object.keys(Zi).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Zi[e]=i,i}constructor(e,t,i,s=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Xi(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(eo(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&or(e.keyFormatVersions,this.keyFormatVersions)&&Zo(e.iv,this.iv)&&Zo(e.keyId,this.keyId)}isSupported(){if(this.method){if(Xi(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case pt.FAIRPLAY:case pt.WIDEVINE:case pt.PLAYREADY:case pt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var i;if(!this.encrypted||!this.uri)return null;if(Xi(this.method)){let a=this.iv;return a||(typeof e!="number"&&(Ge.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=Vd(e)),new gi(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=Zi[this.uri];if(a&&!or(this.keyId,a)&&gi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Jo(this.uri);if(s)switch(this.keyFormat){case pt.WIDEVINE:if(this.pssh=s,!this.keyId){const a=po(s.buffer).filter(o=>o.systemId===el.WIDEVINE);if(a.length){var r;const o=a[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=il(t));break;case pt.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Kh(a,null,s),this.keyId=In(s);break}default:{let a=s.subarray(0,16);if(a.length!==16){const o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((i=this.keyId)==null?void 0:i.byteLength)!==16){let a;a=Hd(t),a||(a=il(t),a||(a=Zi[this.uri])),a&&(this.keyId=a,gi.setKeyIdForUri(this.uri,a))}return this}}function Hd(n){const e=n?.[pt.WIDEVINE];return e?e.keyId:null}function il(n){const e=n?.[pt.PLAYREADY];if(e){const t=Jo(e.uri);if(t)return In(t)}return null}function Vd(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const sl=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,rl=/#EXT-X-MEDIA:(.*)/g,Kd=/^#EXT(?:INF|-X-TARGETDURATION):/m,Cn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Yd=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ri{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 Hr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Kd.test(e)}static parseMasterPlaylist(e,t){const i=Wo(e),s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];if(sl.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=sl.exec(e))!=null;)if(a[1]){const l=new tt(a[1],s),u=nl(l,a[2],t,s,r);u&&s.levels.push(u)}else if(a[3]){const l=a[3],u=a[4];switch(l){case"I-FRAME-STREAM-INF":{const h=new tt(u,s),d=nl(h,h.URI,t,s,r,!0);d&&s.iframeVariants.push(d)}break;case"SESSION-DATA":{const h=new tt(u,s),d=h["DATA-ID"];d&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[d]=h);break}case"SESSION-KEY":{const h=ol(u,t,s);h.encrypted&&h.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(h)):Ge.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new tt(u,s);jo(s,h,t)}break}case"CONTENT-STEERING":{const h=new tt(u,s);s.contentSteering={uri:ri.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=ll(u);break}}}const o=r.length>0&&r.length<s.levels.length;return s.levels=o?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const r={},a=i.levels,o={AUDIO:a.map(u=>({id:u.attrs.AUDIO,audioCodec:u.audioCodec})),SUBTITLES:a.map(u=>({id:u.attrs.SUBTITLES,textCodec:u.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(rl.lastIndex=0;(s=rl.exec(e))!==null;){const u=new tt(s[1],i),h=u.TYPE;if(h){const d=o[h],g=r[h]||[];r[h]=g;const m=u.LANGUAGE,A=u["ASSOC-LANGUAGE"],C=u.CHANNELS,v=u.CHARACTERISTICS,x=u["INSTREAM-ID"],R={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||m||"",type:h,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:m,url:u.URI?ri.resolve(u.URI,t):""};if(A&&(R.assocLang=A),C&&(R.channels=C),v&&(R.characteristics=v),x&&(R.instreamId=x),d!=null&&d.length){const b=ri.findGroup(d,R.groupId)||d[0];cl(R,b,"audioCodec"),cl(R,b,"textCodec")}g.push(R)}}return r}static parseLevelPlaylist(e,t,i,s,r,a){var o;const l={url:t},u=new Nd(t),h=u.fragments,d=[];let g=null,m=0,A=0,C=0,v=0,x=0,R=null,b=new Hs(s,l),D,_,M,p=-1,$=!1,N=null,O;if(Cn.lastIndex=0,u.m3u8=e,u.hasVariableRefs=Wo(e),((o=Cn.exec(e))==null?void 0:o[0])!=="#EXTM3U")return u.playlistParsingError=new Error("Missing format identifier #EXTM3U"),u;for(;(D=Cn.exec(e))!==null;){$&&($=!1,b=new Hs(s,l),b.playlistOffset=C,b.setStart(C),b.sn=m,b.cc=v,x&&(b.bitrate=x),b.level=i,g&&(b.initSegment=g,g.rawProgramDateTime&&(b.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),N&&(b.setByteRange(N),N=null)));const re=D[1];if(re){b.duration=parseFloat(re);const J=(" "+D[2]).slice(1);b.title=J||null,b.tagList.push(J?["INF",re,J]:["INF",re])}else if(D[3]){if(se(b.duration)){var W;b.playlistOffset=C,b.setStart(C),M&&dl(b,M,u),b.sn=m,b.level=i,b.cc=v;const J=(" "+D[3]).slice(1);b.relurl=gn(u,J),yn(b,R,d),R=b,C+=b.duration,m++,A=0;const Z=b.byteRange;if(Z.length===2&&(b.bitrate=(Z[1]-Z[0])*8/b.duration|0),u.iframesOnly&&Z[0]&&((W=g)==null?void 0:W.cc)!==v){const Q=new Hs(s,l);Q.relurl=b.relurl,Q.setByteRange(`${Math.min(Z[0],1316)}@0`),Q.level=i,Q.sn="initSegment",M&&(Q.levelkeys=M,M.identity&&(Q._decryptdata=M.identity.getDecryptData(0))),g=Q,b.initSegment=g}h.push(b),$=!0}}else{if(D=D[0].match(Yd),!D){Ge.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<D.length&&D[_]===void 0;_++);const J=(" "+D[_]).slice(1),Z=(" "+D[_+1]).slice(1),Q=D[_+2]?(" "+D[_+2]).slice(1):null;switch(J){case"BYTERANGE":R?b.setByteRange(Z,R):b.setByteRange(Z);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=Z,b.tagList.push(["PROGRAM-DATE-TIME",Z]),p===-1&&(p=h.length);break;case"PLAYLIST-TYPE":u.type&&pi(u,J,D),u.type=Z.toUpperCase();break;case"MEDIA-SEQUENCE":u.startSN!==0?pi(u,J,D):R!==null&&qd(u,J,D),u.startSN=parseInt(Z),m=u.startSN+u.skippedSegments;break;case"SKIP":{u.skippedSegments&&pi(u,J,D);const ee=new tt(Z,u),he=ee.decimalInteger("SKIPPED-SEGMENTS");if(se(he)){u.skippedSegments+=he;for(let ne=he;ne--;)h.push(null);m+=he}const te=ee.enumeratedString("RECENTLY-REMOVED-DATERANGES");te&&(u.recentlyRemovedDateranges=(u.recentlyRemovedDateranges||[]).concat(te.split(" ")));break}case"TARGETDURATION":u.targetduration!==0&&pi(u,J,D),u.targetduration=Math.max(parseInt(Z),1);break;case"VERSION":u.version!==null&&pi(u,J,D),u.version=parseInt(Z);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":u.iframesOnly=!0;break;case"ENDLIST":u.live||pi(u,J,D),u.live=!1;break;case"#":(Z||Q)&&b.tagList.push(Q?[Z,Q]:[Z]);break;case"DISCONTINUITY":v++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([J]);break;case"BITRATE":b.tagList.push([J,Z]),x=parseInt(Z)*1e3,se(x)?b.bitrate=x:x=0;break;case"DATERANGE":{const ee=new tt(Z,u),he=new zo(ee,u.dateRanges[ee.ID],u.dateRangeTagCount);u.dateRangeTagCount++,he.isValid||u.skippedSegments?u.dateRanges[he.id]=he:Ge.log(`Ignoring invalid DATERANGE tag: ${he.invalidReason}: ${Z}`),b.tagList.push(["EXT-X-DATERANGE",Z]);break}case"DEFINE":{{const ee=new tt(Z,u);"IMPORT"in ee?kd(u,ee,a):jo(u,ee,t)}break}case"DISCONTINUITY-SEQUENCE":u.startCC!==0&&pi(u,J,D),u.startCC=v=parseInt(Z),h.forEach(ee=>ee&&(ee.cc=v));break;case"KEY":{const ee=ol(Z,t,u);if(ee.isSupported()){if(ee.method==="NONE"){M=void 0;break}M||(M={});const he=M[ee.keyFormat];he!=null&&he.matches(ee)||(he&&(M=je({},M)),M[ee.keyFormat]=ee)}else Ge.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Z}"`);break}case"START":u.startTimeOffset=ll(Z);break;case"MAP":{const ee=new tt(Z,u);if(b.duration){const he=new Hs(s,l);hl(he,ee,i,M),g=he,b.initSegment=g,g.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=g.rawProgramDateTime)}else{const he=b.byteRangeEndOffset;if(he){const te=b.byteRangeStartOffset;N=`${he-te}@${te}`}else N=null;hl(b,ee,i,M),g=b,$=!0}g.cc=v;break}case"SERVER-CONTROL":{O&&pi(u,J,D),O=new tt(Z),u.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),u.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),u.canSkipDateRanges=u.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),u.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{u.partTarget&&pi(u,J,D);const ee=new tt(Z);u.partTarget=ee.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ee=u.partList;ee||(ee=u.partList=[]);const he=A>0?ee[ee.length-1]:void 0,te=A++,ne=new tt(Z,u),Ee=new Qc(ne,b,l,te,he);ee.push(Ee),b.duration+=Ee.duration;break}case"PRELOAD-HINT":{const ee=new tt(Z,u);u.preloadHint=ee;break}case"RENDITION-REPORT":{const ee=new tt(Z,u);u.renditionReports=u.renditionReports||[],u.renditionReports.push(ee);break}default:Ge.warn(`line parsed but not handled: ${D}`);break}}}R&&!R.relurl?(h.pop(),C-=R.duration,u.partList&&(u.fragmentHint=R)):u.partList&&(yn(b,R,d),b.cc=v,u.fragmentHint=b,M&&dl(b,M,u)),u.targetduration||(u.playlistParsingError=new Error("Missing Target Duration"));const q=h.length,z=h[0],oe=h[q-1];if(C+=u.skippedSegments*u.targetduration,C>0&&q&&oe){u.averagetargetduration=C/q;const re=oe.sn;u.endSN=re!=="initSegment"?re:0,u.live||(oe.endList=!0),p>0&&(jd(h,p,p>q-1?b:null),z&&d.unshift(z))}return u.fragmentHint&&(C+=u.fragmentHint.duration),u.totalduration=C,d.length&&u.dateRangeTagCount&&z&&al(d,u),u.endCC=v,u}}function nl(n,e,t,i,s,r){var a;if(e===void 0)return null;const o=gn(i,e),l={attrs:n,bitrate:n.decimalInteger("BANDWIDTH")||n.decimalInteger("AVERAGE-BANDWIDTH"),name:n.NAME,url:ri.resolve(o,t)},u=n.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),ul(n.CODECS,l);const h=n["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},ul(h,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||s.push(l),r&&(l.iframes=!0),l}function al(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;const i=n[t-1],s=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],u=l.startDate.getTime();l.tagAnchor=i.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;const d=Wd(e,u,n,h,s);if(d){l.tagAnchor=d.ref;break}}}}function Wd(n,e,t,i,s){const r=t[i];if(r){const o=r.programDateTime;if(e>=o||i===0){var a;const l=(((a=t[i+1])==null?void 0:a.start)||s)-r.start;if(e<=o+l*1e3){const u=r.sn-n.startSN,h=n.fragments;if(u>=0&&u<h.length){if(h.length>t.length){const d=t[i+1]||h[h.length-1],g=Math.min(d.sn-n.startSN,h.length-1);for(let m=g;m>u;m--){const A=h[m].programDateTime;if(e>=A&&e<A+h[m].duration*1e3)return h[m]}}return h[u]}}}}return null}function ol(n,e,t){var i,s;const r=new tt(n,t),a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),u=r.KEYFORMATVERSIONS,h=(s=r.KEYFORMAT)!=null?s:"identity";o&&r.IV&&!l&&Ge.error(`Invalid IV: ${r.IV}`);const d=o?ri.resolve(o,e):"",g=(u||"1").split("/").map(Number).filter(Number.isFinite);return new gi(a,d,h,g,l,r.KEYID)}function ll(n){const t=new tt(n).decimalFloatingPoint("TIME-OFFSET");return se(t)?t:null}function ul(n,e){let t=(n||"").split(/[ ,]+/).filter(i=>i);["video","audio","text","image"].forEach(i=>{const s=t.filter(r=>an(r,i));s.length&&(e[`${i}Codec`]=s.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>s.indexOf(r)===-1))}),e.unknownCodecs=t}function cl(n,e,t){const i=e[t];i&&(n[t]=i)}function jd(n,e,t){if(t||(t=n[e]),!!t)for(let i=e;i--;){const s=n[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function yn(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function hl(n,e,t,i){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",i&&(n.levelkeys=i),n.initSegment=null}function dl(n,e,t){n.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(n)}function pi(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function qd(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function vn(n,e){const t=e.startPTS;if(se(t)){let i=0,s;e.sn>n.sn?(i=t-n.start,s=n):(i=n.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function fl(n,e,t,i,s,r,a,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,r=s+e.duration);let u=t,h=i;const d=e.startPTS,g=e.endPTS;if(se(d)){const R=Math.abs(d-t);n&&R>n.totalduration?o.warn(`media timestamps and playlist times differ by ${R}s for level ${e.level} ${n.url}`):se(e.deltaPTS)?e.deltaPTS=Math.max(R,e.deltaPTS):e.deltaPTS=R,u=Math.max(t,d),t=Math.min(t,d),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,h=Math.min(i,g),i=Math.max(i,g),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const m=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=u,e.startDTS=s,e.endPTS=i,e.minEndPTS=h,e.endDTS=r;const A=e.sn;if(!n||A<n.startSN||A>n.endSN)return 0;let C;const v=A-n.startSN,x=n.fragments;for(x[v]=e,C=v;C>0;C--)vn(x[C],x[C-1]);for(C=v;C<x.length-1;C++)vn(x[C],x[C+1]);return n.fragmentHint&&vn(x[x.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,m}function zd(n,e,t){if(n===e)return;let i=null;const s=n.fragments;for(let h=s.length-1;h>=0;h--){const d=s[h].initSegment;if(d){i=d;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;Qd(n,e,(h,d,g,m)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==h.cc){const A=h.cc-d.cc;for(let C=g;C<m.length;C++)m[C].cc+=A;e.endCC=m[m.length-1].cc}se(h.startPTS)&&se(h.endPTS)&&(d.setStart(d.startPTS=h.startPTS),d.startDTS=h.startDTS,d.maxStartPTS=h.maxStartPTS,d.endPTS=h.endPTS,d.endDTS=h.endDTS,d.minEndPTS=h.minEndPTS,d.setDuration(h.endPTS-h.startPTS),d.duration&&(r=d),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(d.elementaryStreams=h.elementaryStreams),d.loader=h.loader,h.hasStats&&(d.stats=h.stats),h.initSegment&&(d.initSegment=h.initSegment,i=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(h=>{var d;h&&(!h.initSegment||h.initSegment.relurl===((d=i)==null?void 0:d.relurl))&&(h.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Xd(n.dateRanges,e,t));const h=n.fragments.filter(d=>d.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&yn(o[d],o[d-1],h);al(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const h=Al(n,e.startSN-1);e.startCC=(l=h?.cc)!=null?l:a[0].cc}if(Zd(n.partList,e.partList,(h,d)=>{d.elementaryStreams=h.elementaryStreams,d.stats=h.stats,d.gap=h.gap||d.gap}),r){const h=e.iframesOnly&&r.type===ge.MAIN;fl(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,h,t)}else pl(n,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const u=e.advancedDateTime;if(e.advanced&&u){const h=e.edge;e.driftStart||(e.driftStartTime=u,e.driftStart=h),e.driftEndTime=u,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function Xd(n,e,t){const{dateRanges:i,recentlyRemovedDateranges:s}=e,r=je({},n);s&&s.forEach(l=>{delete r[l]});const o=Object.keys(r).length;return o?(Object.keys(i).forEach(l=>{const u=r[l],h=new zo(i[l].attr,u);h.isValid?(r[l]=h,u||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Xe(i[l].attr)}"`)}),r):i}function Zd(n,e,t){if(n&&e){let i=0;for(let s=0,r=n.length;s<r;s++){const a=n[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Qd(n,e,t){var i;const s=e.skippedSegments,r=Math.max(n.startSN,e.startSN)-e.startSN,a=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,o=e.startSN-n.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=(i=n.fragmentHint)!=null&&i.duration?n.fragments.concat(n.fragmentHint):n.fragments;for(let h=r;h<=a;h++){const d=u[o+h];let g=l[h];if(s&&!g&&d&&(g=e.fragments[h]=d),d&&g){t(d,g,h,l);const m=d.relurl,A=g.relurl;if(m&&ef(m,A)){e.playlistParsingError=gl(`media sequence mismatch ${g.sn}:`,n,e,d,g);return}else if(d.cc!==g.cc){e.playlistParsingError=gl(`discontinuity sequence mismatch (${d.cc}!=${g.cc})`,n,e,d,g);return}}}}function gl(n,e,t,i,s){return new Error(`${n} ${s.url}
|
|
12
|
-
Playlist starting @${e.startSN}
|
|
13
|
-
${e.m3u8}
|
|
14
|
-
|
|
15
|
-
Playlist starting @${t.startSN}
|
|
16
|
-
${t.m3u8}`)}function pl(n,e,t=!0,i){const s=e.startSN+e.skippedSegments-n.startSN,r=n.fragments,a=s>=0;let o=0;if(a&&s<r.length)o=r[s].start,i?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===n.endSN+1)o=n.fragmentEnd,i?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=n.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=n.fragmentStart,i?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Jd(e,o),o}function Jd(n,e){if(e){const t=n.fragments;for(let i=n.skippedSegments;i<t.length;i++)t[i].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function ml(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const i=n.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r>0&&r<t&&(t=r)}}else t/=2;return Math.round(t)}function Al(n,e,t){var i;if(!n)return null;let s=n.fragments[e-n.startSN];return s||(s=n.fragmentHint,((i=s)==null?void 0:i.sn)===e)?s:t&&e<n.startSN&&t.sn===e?t:null}function Il(n,e,t){return n?Cl(n.partList,e,t):null}function Cl(n,e,t){if(n)for(let i=n.length;i--;){const s=n[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function yl(n){n.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function ef(n,e){return n!==e&&e?vl(n)!==vl(e):!1}function vl(n){return n.replace(/\?[^?]*$/,"")}function Ts(n,e){for(let i=0,s=n.length;i<s;i++){var t;if(((t=n[i])==null?void 0:t.cc)===e)return n[i]}return null}function tf(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function El(n,e){const t=n.start+e;n.setStart(t)}function Tl(n,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)El(t[i],n);e.fragmentHint&&El(e.fragmentHint,n),e.alignedSliding=!0}function cr(n,e,t){n&&(sf(e,n,t),e.alignedSliding||rf(e,n,t),!e.alignedSliding&&!e.skippedSegments&&pl(n,e,!1,t))}function sf(n,e,t){if(!tf(e,n))return;const i=Math.min(e.endCC,n.endCC),s=Ts(e.fragments,i),r=Ts(n.fragments,i);if(!s||!r)return;const a=s.start-r.start;t.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Tl(a,n)}function rf(n,e,t){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const i=n.fragments,s=e.fragments;if(!i.length||!s.length)return;let r,a;const o=Math.min(e.endCC,n.endCC);e.startCC<o&&n.startCC<o&&(r=Ts(s,o),a=Ts(i,o)),(!r||!a)&&(r=s[Math.floor(s.length/2)]||s.filter(g=>!!g)[0],a=Ts(i,r.cc)||i[Math.floor(i.length/2)]);const l=r.programDateTime,u=a.programDateTime;if(!l||!u)return;const h=(u-l)/1e3;if(Math.abs(h)>Math.max(60,n.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${n.totalduration})`);return}const d=h-(a.start-r.start);t.log(`Aligning playlists using PDT (diff: ${d})`),Tl(d,n)}function Ke(n,e,t){Ve(n,e,t),n.addEventListener(e,t)}function Ve(n,e,t){n.removeEventListener(e,t)}function hr(n){let e="";const t=n.length;for(let i=0;i<t;i++)e+=`[${n.start(i).toFixed(3)}-${n.end(i).toFixed(3)}]`;return e}const Y={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class En extends Ko{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Y.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:u,state:h}=this,d=l?l.currentTime:0,g=ve.bufferInfo(u||l,d,a.maxBufferHole),m=g.len;if(this.log(`Media seeking to ${d}, state: ${h}, ${m?"in":"out of"} buffer`),this.state===Y.ENDED)this.resetLoadingState();else if(o){const C=a.maxFragLookUpTolerance,v=o.start-C,x=o.start+o.duration+C;if(!m||x<g.start||v>g.end){const R=d<v,b=d>x;(R||b)&&(o.loader&&(b||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${R?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const C=this.lastCurrentTime;if(d>C&&(this.lastCurrentTime=d),!this.loadingParts){const v=Math.max(g.end,d),x=this.shouldLoadParts(this.getLevelDetails(),v);x&&(this.log(`LL-Part loading ON after seeking to ${d} with buffer @${v}`),this.loadingParts=x)}}const A=!ve.isBuffered(l,d);(!this.hls.hasEnoughToStart||A)&&(this.log(`Setting ${A?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,A&&(this.startPosition=d)),m<1&&this.state===Y.IDLE&&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 Go(e.config),this.initFragmentLoader=new Go(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new hn(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Y.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Y.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){const i=this.getLevelDetails();return i!=null&&i.live?(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=ve.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const h=l[l.length-1];return ve.isBuffered(this.media,h.start+h.duration/2)}const u=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(u.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Ke(i,"seeking",this.onMediaSeeking),Ke(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===Y.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ve(s,"seeking",this.onMediaSeeking),Ve(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Y.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}const o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} chunk: ${o}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===Y.FRAG_LOADING||!this.fragCurrent&&a===Y.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Y.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(E.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===et.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===et.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){const s=t.getPartialFragment(i.end);s&&(t.removeFragment(s),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(E.BUFFER_FLUSHING,s)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(i=>{var s;const r=i.frag;if(!this.levels||!Kr(r,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new si({type:me.NETWORK_ERROR,details:U.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return i}).then(i=>{const{frag:s,payload:r}=i,a=s.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&Xi(a.method)){const o=self.performance.now(),{decryptRange:l}=nr(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,pn(a.method),l).catch(u=>{throw t.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:s}),this.fragmentLoader.abort(),u}).then(u=>{const h=self.performance.now();return t.trigger(E.FRAG_DECRYPTED,{frag:s,part:null,payload:u,stats:{tstart:o,tdecrypt:h}}),i.payload=u,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;if(!this.bitrateTest&&st(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(r=>{throw this.state===Y.STOPPED||this.state===Y.ERROR||("data"in r&&(r.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(r)),this.resetFragmentLoading(e)),r})}}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!Kr(e,t)}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?hr(ve.getBuffered(i)):"(detached)"})`),st(e)){var s;if(e.type!==ge.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=Y.IDLE;return}}const r=(s=this.levels)==null?void 0:s[e.level];r!=null&&r.fragmentError&&(t||this.fragmentTracker.getState(e)!==et.PARTIAL)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,e.stats.retry=0)}this.state=Y.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const i=e.frag,{part:s,partsLoaded:r}=e,a=!r||r.length===0||r.some(u=>!u),{decryptRange:o}=nr(i,s),l=new dn(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a,i.duration,this.iframesOnly,o);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var s;let r=null;return e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Y.KEY_LOADING,r=this.keyLoader.load(e,i).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(E.KEY_LOADED,a),this.state===Y.KEY_LOADING&&(this.state=Y.IDLE),a}),this.hls.trigger(E.KEY_LOADING,{frag:e})):e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),r}_doFragLoad(e,t,i=null,s){this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const a=this.fragPrevious;if(!cs(e,a)){const m=this.shouldLoadParts(t.details,e.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=m)}if(i=Math.max(e.start,i||0),this.loadingParts){const m=r.partList;if(m&&s){i>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const A=this.getNextPart(m,e,i);if(A>-1){const C=m[A];if(e=this.fragCurrent=C.fragment,!cs(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,C)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(C,t.details))return Promise.resolve(null);const v=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${C.index} (${A}/${m.length-1}) of ${this.fragInfo(e,!1,C)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${i}${C.byteRange.length?` range:${C.byteRange.join("-")}`:""}`),this.nextLoadPosition=C.start+C.duration,this.state=Y.FRAG_LOADING;let x;const R=this.loadInitSegmentIfNeeded(e);if(v||R){const b=!!v;x=Promise.all([v,R]).then(([D])=>b&&(!D||this.fragContextChanged(D.frag))?null:this.doFragPartsLoad(e,C,t,s)).catch(D=>this.handleFragLoadError(D))}else x=this.doFragPartsLoad(e,C,t,s).catch(b=>this.handleFragLoadError(b));return this.hls.trigger(E.FRAG_LOADING,{frag:e,part:C,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):x}else if(!e.url||this.loadedEndOfParts(m,i))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(o=r.partList)==null?void 0:o.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(e),u=this.loadKeyFor(e,r,l);if(this.fragContextChanged(e)){var h;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(h=this.fragCurrent)==null?void 0:h.relurl}`),l?.catch(()=>null),u?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),se(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Y.FRAG_LOADING;const d=this.config.progressive&&e.type!==ge.SUBTITLE;let g;return d&&u?g=u.then(m=>!m||this.fragContextChanged(m.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,s,l)).catch(m=>this.handleFragLoadError(m)):g=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,d?s:void 0,d?l:void 0),u,l]).then(([m])=>(!d&&s&&s(m),m)).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([g,l]).then(([m])=>m)}doFragPartsLoad(e,t,i,s){return new Promise((r,a)=>{var o;const l=[],u=(o=i.details)==null?void 0:o.partList,h=d=>{this.fragmentLoader.loadPart(e,d,s).then(g=>{l[d.index]=g;const m=g.part;this.hls.trigger(E.FRAG_LOADED,g);const A=Il(i.details,e.sn,d.index+1)||Cl(u,e.sn,d.index+1);if(A)h(A);else return r({frag:e,part:m,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===U.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===me.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Y.PARSING){!this.fragCurrent&&this.state!==Y.STOPPED&&this.state!==Y.ERROR&&(this.state=Y.IDLE);return}const{frag:i,part:s,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);const o=this.getLevelDetails(),u=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=u),this.updateLevelTiming(i,s,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;const s=e.partList[0],r=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=r&&this.playhead>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:a}=e;if(!(t!=null&&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 o=t[s],l=o.details,u=a>-1?Il(l,r,a):null,h=u?u.fragment:Al(l,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:u,level:o}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==Y.PARSING)return;st(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:a,data2:o}=e;let l=a;if(o&&(l=Bt(a,o)),!l.length)return;const u=this.initPTS[t.cc],h=u?-u.baseTime/u.timescale:void 0,d={type:e.type,frag:t,part:i,chunkMeta:s,offset:h,parent:t.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ve.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=ve.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;const s=this.playhead,a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){const r=ve.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,s);return ve.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const s=e.nextStart;if(s&&i.start>s){const r=e.buffered;if(r){let a=e.len;const o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<i.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t/2),r=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const d=r.initialLiveManifestSize;if(s<d)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${d})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var u;l=this.getInitialLiveFragment(t);const g=this.config.startPosition,m=this.hls.startPosition,A=this.hls.liveSyncPosition,C=((u=l)==null?void 0:u.start)||0;let v,x;if(m!==-1&&m>=a?(v=m,x=m===g?"config":"next load start"):A?(v=A,x="live edge"):(v=e,x="buffer pos"),v<C&&(v=C,x="live frag start"),v<a&&(v=a,x="playlist start"),this.startPosition!=v||this.nextLoadPosition!=v){const b=t.live&&!this.filterReplacedPrimary(l,t)?-1:v;this.log(`Setting startPosition to ${b} next load ${v} ${m===-1?"":`(from ${g}) `}based on ${x}. live edge: ${A} live frag start: ${C} playlist start: ${a} buffer pos: ${e}`),this.startPosition=b,this.nextLoadPosition=v}}}else e<=a&&(l=i[0]);if(!l){const d=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,d,t)}let h=this.filterReplacedPrimary(l,t);return!h&&l&&(h=Fo(t,l.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return!!(i===et.OK||i===et.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,i,s,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(dr(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(dr(this.config)&&("type"in e?e:e.fragment).type!==ge.SUBTITLE){const i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){const r=s.event;if(r){if(!r.appendInPlace&&(Math.abs(e.start-s.start)>1||s.start===0))return null}else if(e.end<=s.start&&t?.live===!1||e.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||e.start-s.end>1))return null}if(Sl(e,i?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let s=-1,r=!1,a=!0;for(let l=0,u=e.length;l<u;l++){const h=e[l];if(a=a&&!h.independent,s>-1&&i<h.start)break;const d=h.loaded||h.gap;d?s=-1:(r||(h.independent||a)&&h.fragment===t)&&(s=l),r=d&&!h.gap}const o=e[s];return o&&o.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(s=yd(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Oo(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,{maxFragLookUpTolerance:u}=s,h=i.partList,d=!!(this.loadingParts&&h!=null&&h.length&&l);d&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),r&&this.fragmentTracker.getState(r)===et.NOT_LOADED&&(r=null);let g;if(e<t){var m;const C=e<this.lastCurrentTime||e>t-u||(m=this.media)!=null&&m.paused||!this.startFragRequested?0:u;g=qi(r,a,e,C)}else g=a[a.length-1];if(g){const A=g.sn-i.startSN,C=this.fragmentTracker.getState(g);if((C===et.OK||C===et.PARTIAL&&g.gap)&&(r=g),cs(g,r)&&(!d||h[0].fragment.sn>g.sn||!i.live)){const v=a[A+1];g.sn<o&&this.fragmentTracker.getState(v)!==et.OK?g=v:g=null}}return g}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&se(r);if(a||!o&&!r){cr(i,e,this);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;if(a!==null&&se(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){const o=this.hls.liveSyncPosition;i=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;const i=(t=this.media)==null?void 0:t.currentTime;return se(i)?i:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==ge.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&st(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Y.FRAG_LOADING_WAITING_RETRY)&&(this.state=Y.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const R=this.getCurrentContext(t.chunkMeta);R&&(t.frag=R.frag)}const{frag:i,part:s}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}const a=t.details===U.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=t.errorAction;if(!o){this.state=Y.ERROR;return}const{action:l,flags:u,retryCount:h=0,retryConfig:d}=o,g=!!d,m=g&&l===gt.RetryRequest,A=g&&!o.resolved&&u&dt.MoveAllAlternatesMatchingHost,C=this.hls.latestLevelDetails,v=C?.live;if(!m&&A&&st(i)&&v&&i.sn<C.endSN&&!Ha(t))this.resetFragmentErrors(e),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((m||A)&&h<d.maxNumRetry){var x;const R=ds((x=t.response)==null?void 0:x.code),b=Yr(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+b,this.state=Y.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,R){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${b}ms`)}else if(d)if(this.resetFragmentErrors(e),h<d.maxNumRetry)!a&&l!==gt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===gt.SendAlternateToPenaltyBox?this.state=Y.WAITING_LEVEL:this.state=Y.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!ds(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Y.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Y.PARSING||this.state===Y.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,t?.duration||10);const a=!r;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&t&&s.nextStart>t.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===ge.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===ge.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Y.STOPPED&&(this.state=Y.IDLE)}afterBufferFlushed(e,t){if(!e)return;const i=ve.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===Y.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Y.STOPPED&&(this.state=Y.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const r=i.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((d,g)=>{const m=e.elementaryStreams[g];if(m){const A=m.endPTS-m.startPTS;if(A<=0)return this.warn(`Could not parse fragment ${e.sn} ${g} duration reliably (${A})`),d||!1;const C=s.partial?0:fl(r,e,m.startPTS,m.endPTS,m.startDTS,m.endDTS,this.iframesOnly,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:r,level:i,drift:C,type:g,frag:e,start:m.startPTS,end:m.endPTS}),!0}return d},!1)){var o,l,u,h;const d=((o=this.transmuxer)==null?void 0:o.error)===null,g=((l=this.transmuxer)==null?void 0:l.error)!=null,m=((u=(h=this.levels)==null?void 0:h.length)!=null?u:0)>1;if((i.fragmentError===0||d&&(i.fragmentError<2||e.endList)||g&&m)&&this.treatAsGap(e,i),d){const A=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(A.message),this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:A,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Y.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN}-${(r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;const i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;const s=i.loading.first>0,a=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0;const{hls:s,media:r,config:a,levels:o,playlistType:l}=this,u=this.getLevelDetails();if(r&&!r.paused&&o){var h;const m=l===ge.AUDIO?So(e.audioCodec,128e3):e.maxBitrate,A=1+s.ttfbEstimate/1e3,C=s.bandwidthEstimate*a.abrBandWidthUpFactor,v=u&&(this.loadingParts?u.partTarget:u.averagetargetduration)||((h=this.fragCurrent)==null?void 0:h.duration)||6;i=A+m*v/C,e.details||(i+=A)}const d=this.playhead,g=!(u!=null&&u.live)||t.end-d>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:g}}scheduleTrackSwitch(e,t,i){const{media:s,playlistType:r}=this;if(!s||!e)return;const a=i?this.getBufferedFrag(this.playhead+t):null;if(a){const l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();const u=l.maxStartPTS?l.maxStartPTS:l.start,h=l.duration,d=Math.max(a.end,u+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>d)return;const m=r===ge.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,m),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){const s=t===ge.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Y.KEY_LOADING:case Y.FRAG_LOADING:case Y.FRAG_LOADING_WAITING_RETRY:case Y.PARSING:case Y.PARSED:this.state=Y.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ve.isBuffered(e,i)?t=this.getAppendedFrag(i):ve.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!cs(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:i,config:s,playlistType:r}=this;if(t!=null&&t.readyState&&e&&i&&s){const a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,r);if(!o)return;const l=r===ge.AUDIO?i.nextAudioTrack:i.nextLoadLevel,u=e[l],{fetchdelay:h,okToFlushForwardBuffer:d}=this.calculateOptimalSwitchPoint(u,o);this.scheduleTrackSwitch(o,h,d)}this.tickImmediate()}}function Sl(n,e,t){if(e)for(let i=e.length;i--;){const s=e[i].interstitial,r=s.startTime,a=Math.min(r+s.duration,s.resumeTime);if(s.appendInPlace&&(n.start>=r&&n.end<=a||t>n.start&&n.end>r&&n.start<a))return!0}return!1}function dr(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class xl{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=nf(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function nf(n,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<n.length;s++){const r=n[s];t.set(r,i),i+=r.length}return t}var Tn={exports:{}},bl;function af(){return bl||(bl=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,u,h){this.fn=l,this.context=u,this.once=h||!1}function r(l,u,h,d,g){if(typeof h!="function")throw new TypeError("The listener must be a function");var m=new s(h,d||l,g),A=t?t+u:u;return l._events[A]?l._events[A].fn?l._events[A]=[l._events[A],m]:l._events[A].push(m):(l._events[A]=m,l._eventsCount++),l}function a(l,u){--l._eventsCount===0?l._events=new i:delete l._events[u]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],h,d;if(this._eventsCount===0)return u;for(d in h=this._events)e.call(h,d)&&u.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(h)):u},o.prototype.listeners=function(u){var h=t?t+u:u,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var g=0,m=d.length,A=new Array(m);g<m;g++)A[g]=d[g].fn;return A},o.prototype.listenerCount=function(u){var h=t?t+u:u,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,h,d,g,m,A){var C=t?t+u:u;if(!this._events[C])return!1;var v=this._events[C],x=arguments.length,R,b;if(v.fn){switch(v.once&&this.removeListener(u,v.fn,void 0,!0),x){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,h),!0;case 3:return v.fn.call(v.context,h,d),!0;case 4:return v.fn.call(v.context,h,d,g),!0;case 5:return v.fn.call(v.context,h,d,g,m),!0;case 6:return v.fn.call(v.context,h,d,g,m,A),!0}for(b=1,R=new Array(x-1);b<x;b++)R[b-1]=arguments[b];v.fn.apply(v.context,R)}else{var D=v.length,_;for(b=0;b<D;b++)switch(v[b].once&&this.removeListener(u,v[b].fn,void 0,!0),x){case 1:v[b].fn.call(v[b].context);break;case 2:v[b].fn.call(v[b].context,h);break;case 3:v[b].fn.call(v[b].context,h,d);break;case 4:v[b].fn.call(v[b].context,h,d,g);break;default:if(!R)for(_=1,R=new Array(x-1);_<x;_++)R[_-1]=arguments[_];v[b].fn.apply(v[b].context,R)}}return!0},o.prototype.on=function(u,h,d){return r(this,u,h,d,!1)},o.prototype.once=function(u,h,d){return r(this,u,h,d,!0)},o.prototype.removeListener=function(u,h,d,g){var m=t?t+u:u;if(!this._events[m])return this;if(!h)return a(this,m),this;var A=this._events[m];if(A.fn)A.fn===h&&(!g||A.once)&&(!d||A.context===d)&&a(this,m);else{for(var C=0,v=[],x=A.length;C<x;C++)(A[C].fn!==h||g&&!A[C].once||d&&A[C].context!==d)&&v.push(A[C]);v.length?this._events[m]=v.length===1?v[0]:v:a(this,m)}return this},o.prototype.removeAllListeners=function(u){var h;return u?(h=t?t+u:u,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(Tn)),Tn.exports}var of=af(),Sn=Xc(of);const Ss="1.7.3",Qi={};function lf(){return typeof __HLS_WORKER_BUNDLE__=="function"}function uf(){const n=Qi[Ss];if(n)return n.clientCount++,n;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return Qi[Ss]=s,s}function cf(n){const e=Qi[n];if(e)return e.clientCount++,e;const t=new self.URL(n,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Qi[n]=s,s}function hf(n){const e=Qi[n||Ss];if(e&&e.clientCount--===1){const{worker:i,objectURL:s}=e;delete Qi[n||Ss],s&&self.URL.revokeObjectURL(s),i.terminate()}}function df(n,e,t,i){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const v=new Error(`invalid ADTS sampling index:${a}`);n.emit(E.ERROR,E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,u=s[a];let h=a;(o===5||o===29)&&(h-=3);let d;const g=(h&14)>>1,m=(h&1)<<7|l<<3;let A=0;if(o===1&&a>=6){A=5;const v=a-3;d=[A<<3|g,m|(v&14)>>1,(v&1)<<7|8,0]}else d=[o<<3|g,m];const C="mp4a.40."+(A||o);return Ge.log(`manifest codec:${i}, parsed codec:${C}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a} esds config:[${d.join(",")}])`),{config:d,samplerate:u,channelCount:l,codec:C,parsedCodec:C,manifestCodec:i}}function Ll(n,e){return n[e]===255&&(n[e+1]&246)===240}function Rl(n,e){return n[e+1]&1?7:9}function xn(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function ff(n,e){return e+5<n.length}function fr(n,e){return e+1<n.length&&Ll(n,e)}function gf(n,e){return ff(n,e)&&Ll(n,e)&&xn(n,e)<=n.length-e}function pf(n,e){if(fr(n,e)){const t=Rl(n,e);if(e+t>=n.length)return!1;const i=xn(n,e);if(i<=t)return!1;const s=e+i;return s===n.length||fr(n,s)}return!1}function Dl(n,e,t,i,s){if(!n.samplerate){const r=df(e,t,i,s);if(!r)return;je(n,r)}}function Pl(n){return 1024*9e4/n}function mf(n,e){const t=Rl(n,e);if(e+t<=n.length){const i=xn(n,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function _l(n,e,t,i,s){const r=Pl(n.samplerate),a=i+s*r,o=mf(e,t);let l;if(o){const{frameLength:d,headerLength:g}=o,m=g+d,A=Math.max(0,t+m-e.length);A?(l=new Uint8Array(m-g),l.set(e.subarray(t+g,e.length),0)):l=e.subarray(t+g,t+m);const C={unit:l,pts:a};return A||n.samples.push(C),{sample:C,length:m,missing:A}}const u=e.length-t;return l=new Uint8Array(u),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:u,missing:-1}}let Et=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function ni(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class bn{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=Bt(this.cachedData,e),this.cachedData=null);let i=fs(e,0),s=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?Zr(i):void 0,u=e.length;for((this.basePTS===null||this.frameIndex===0&&se(l))&&(this.basePTS=Af(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Et.audioId3,duration:Number.POSITIVE_INFINITY});s<u;){if(this.canParse(e,s)){const h=this.appendFrame(a,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,r=s):s=u}else ph(e,s)?(i=fs(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Et.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===u&&r!==u){const h=e.slice(r);this.cachedData?this.cachedData=Bt(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:ni(),id3Track:o,textTrack:ni()}}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:ni(),id3Track:this._id3Track,textTrack:ni()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Af=(n,e,t)=>{if(se(n))return n*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},If=[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],Cf=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],yf=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],vf=[0,1,1,4];function kl(n,e,t,i,s){if(t+24>e.length)return;const r=wl(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function wl(n,e){const t=n[e+1]>>3&3,i=n[e+1]>>1&3,s=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-i:i===3?3:4,u=If[l*14+s-1]*1e3,d=Cf[(t===3?0:t===2?1:2)*3+r],g=o===3?1:2,m=yf[t][i],A=vf[i],C=m*8*A,v=Math.floor(m*u/d+a)*A,x=ms();return x&&x<=87&&i===2&&u>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:d,channelCount:g,frameLength:v,samplesPerFrame:C}}}function Ln(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function Ml(n,e){return e+1<n.length&&Ln(n,e)}function Ef(n,e){return Ln(n,e)&&4<=n.length-e}function Ol(n,e){if(e+1<n.length&&Ln(n,e)){const i=wl(n,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=e+s;return r===n.length||Ml(n,r)}return!1}class Fl{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new hn(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Si.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)i.set(e.subarray(r,r+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)e.set(i.subarray(s,s+16),r);return e}decryptAvcSample(e,t,i,s,r){const a=go(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const r=e[t].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}}class Tf extends bn{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=fs(e,0);let s=i?.length||0;if(Ol(e,s))return!1;for(let r=e.length;s<r;s++)if(pf(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return gf(e,t)}appendFrame(e,t,i){Dl(e,this.observer,t,i,e.manifestCodec);const s=_l(e,t,i,this.basePTS,this.frameIndex);if(s?.missing===0)return s}demuxSampleAes(e,t,i){const s=this.demux(e,i),r=this.sampleAes=new Fl(this.observer,this.config,t);return new Promise(a=>{r.decryptAacSamples(s.audioTrack.samples,0,()=>{a(s)})})}}const Nl=(n,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=n[e];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,s[0]=(a[0]&r[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class Sf extends bn{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=Bl(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=fs(e,0);if(!t)return!1;const i=t.length;if(e[i]===11&&e[i+1]===119&&Zr(t)!==void 0){if(Nl(e,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Bl(n,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const d=e[t+6]>>5;let g=0;d===2?g+=2:(d&1&&d!==1&&(g+=2),d&4&&(g+=2));const m=(e[t+6]<<8|e[t+7])>>12-g&1,C=[2,1,2,3,3,4,4,5][d]+m,v=e[t+5]>>3,x=e[t+5]&7,R=new Uint8Array([r<<6|v<<1|x>>2,(x&3)<<6|d<<3|m<<2|l>>4,l<<4&224]),b=1536/o*9e4,D=i+s*b,_=e.subarray(t,t+h);return n.config=R,n.channelCount=C,n.samplerate=o,n.samples.push({unit:_,pts:D}),h}class xf extends bn{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=fs(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Zr(t)!==void 0&&Nl(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Ol(e,i))return Ge.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Ef(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return kl(e,t,i,this.basePTS,this.frameIndex)}}const bf=/\/emsg[-/]ID3/i;class Lf{constructor(e,t,i,s=Ge){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=ni("video",1),a=this.audioTrack=ni("audio",1),o=this.txtTrack=ni("text",1);if(this.id3Track=ni("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=this.initData=oo(e);if(l.video){const{id:u,timescale:h,codec:d,supplemental:g}=l.video;r.id=u,r.timescale=o.timescale=h,r.codec=d,r.supplemental=g}if(l.audio){const{id:u,timescale:h,codec:d}=l.audio;a.id=u,a.timescale=h,a.codec=d}o.id=to.text,r.sampleDuration=0,r.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Ph(e,"moof")}demux(e,t,i){this.timeOffset=t;let s=e;const r=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Bt(this.remainderData,e));const u=$h(s);this.remainderData=u.remainder,r.samples=u.valid||new Uint8Array}else r.samples=s;const o=this.extractID3Track(r,t),l=this.parseFragment(r,a,t,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){const i=this.timeOffset,s=this.videoTrack,r=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const a=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,r,i,t);return{videoTrack:s,audioTrack:ni(),id3Track:a,textTrack:ni(),initData:this.initData,sampleData:o}}parseFragment(e,t,i,s){const r=this.initData;if(r&&s){const{samples:a,sampleData:o}=Uh(i,e,r,this.logger,s.iframe);return t.samples=a,o}t.samples=Gh(i,e)}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=xe(e.samples,["emsg"]);s&&s.forEach(r=>{const a=Hh(r);if(bf.test(a.schemeIdUri)){const o=Ul(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const u=a.payload;i.samples.push({data:u,len:u.byteLength,dts:o,pts:o,type:Et.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||Et.misbklv;if(a.schemeIdUri.startsWith(o)){const l=Ul(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:Et.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function Ul(n,e){return se(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}const Rf=1,Df=2,xs=-1;class $l{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;if(s===0)return[];const r=e.naluState||0,a=r===xs?0:r,o=[];let l=0,u=0,h=-1,d=0;for(r===xs&&(h=0,d=this.getNALuType(t,0),u=1);u<s;){const g=t.indexOf(Rf,u);if(g===-1)break;u=g+1;let m=g;for(;m>0&&t[m-1]===0;)m--;if(!(g-m+(m===0?a:0)<Df)){if(h>=0)o.push({data:t.subarray(h,m),type:d});else{const C=this.getLastNalUnit(e.samples);C&&(m>0?C.data=Bt(C.data,t.subarray(0,m)):a>0&&(C.data=C.data.subarray(0,C.data.byteLength-a)),C.state=0)}if(u<s)h=u,d=this.getNALuType(t,u);else{l=xs,h=-1;break}}}if(l!==xs){let g=s;for(;g>0&&t[g-1]===0;)g--;l=s-g+(g===0?a:0)}if(h>=0)o.push({data:t.subarray(h),type:d,state:l});else if(o.length===0&&l!==xs){const g=this.getLastNalUnit(e.samples);g&&(g.data=Bt(g.data,t),g.state=l)}return e.naluState=l,o}}class bs{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(r===0)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&Ge.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class Pf extends $l{parsePES(e,t,i,s,r){const a=r.iframe,o=this.parseNALu(e,i.data,s);let l=this.VideoSample,u,h=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach(d=>{var g,m;switch(d.type){case 1:{if(a)break;let x=!1;u=!0;const R=d.data;if(h&&R.length>4){const b=this.readSliceType(R);(b===2||b===4||b===7||b===9)&&(x=!0)}if(x){var A;(A=l)!=null&&A.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=x;break}case 5:u=!0,(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;u=!0,ps(d.data,1,i.pts,t.samples);break}case 7:{var C,v;u=!0,h=!0;const x=d.data,R=this.readSPS(x);if(!e.sps||e.width!==R.width||e.height!==R.height||((C=e.pixelRatio)==null?void 0:C[0])!==R.pixelRatio[0]||((v=e.pixelRatio)==null?void 0:v[1])!==R.pixelRatio[1]){e.width=R.width,e.height=R.height,e.pixelRatio=R.pixelRatio,e.sps=[x];const b=x.subarray(1,4);let D="avc1.";for(let _=0;_<3;_++){let M=b[_].toString(16);M.length<2&&(M="0"+M),D+=M}e.codec=D}break}case 8:u=!0,e.pps=[d.data];break;case 9:u=!0,e.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:u=!0;break;default:u=!1;break}l&&u&&l.units.push(d)}),s&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new bs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,r;for(let a=0;a<e;a++)s!==0&&(r=t.readEG(),s=(i+r+256)%256),i=s===0?i:s}readSPS(e){const t=new bs(e);let i=0,s=0,r=0,a=0,o,l,u;const h=t.readUByte.bind(t),d=t.readBits.bind(t),g=t.readUEG.bind(t),m=t.readBoolean.bind(t),A=t.skipBits.bind(t),C=t.skipEG.bind(t),v=t.skipUEG.bind(t),x=this.skipScalingList.bind(this);h();const R=h();if(d(5),A(3),h(),v(),R===100||R===110||R===122||R===244||R===44||R===83||R===86||R===118||R===128){const $=g();if($===3&&A(1),v(),v(),A(1),m())for(l=$!==3?8:12,u=0;u<l;u++)m()&&(u<6?x(16,t):x(64,t))}v();const b=g();if(b===0)g();else if(b===1)for(A(1),C(),C(),o=g(),u=0;u<o;u++)C();v(),A(1);const D=g(),_=g(),M=d(1);M===0&&A(1),A(1),m()&&(i=g(),s=g(),r=g(),a=g());let p=[1,1];if(m()&&m())switch(h()){case 1:p=[1,1];break;case 2:p=[12,11];break;case 3:p=[10,11];break;case 4:p=[16,11];break;case 5:p=[40,33];break;case 6:p=[24,11];break;case 7:p=[20,11];break;case 8:p=[32,11];break;case 9:p=[80,33];break;case 10:p=[18,11];break;case 11:p=[15,11];break;case 12:p=[64,33];break;case 13:p=[160,99];break;case 14:p=[4,3];break;case 15:p=[3,2];break;case 16:p=[2,1];break;case 255:{p=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((D+1)*16-i*2-s*2),height:(2-M)*(_+1)*16-(M?2:4)*(r+a),pixelRatio:p}}}class _f extends $l{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let a=this.VideoSample,o,l=!1;i.data=null;const u=h=>(a=this.VideoSample=this.createVideoSample(h,i.pts,i.dts),a);r.forEach((h,d)=>{var g,m;if(this.startsNewAccessUnit(a,e,h,d)){this.pushAccessUnit(a,e);const C=h.type>=16&&h.type<=23;a=u(C),l=!1}switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=u(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var A;(A=a)!=null&&A.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=u(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=u(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,ps(h.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=je(e.params,this.readVPS(h.data)),this.initVPS=h.data),e.vps=[h.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],h.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const C=this.readSPS(h.data);e.width=C.width,e.height=C.height,e.pixelRatio=C.pixelRatio,e.codec=C.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const v in C.params)e.params[v]=C.params[v]}this.pushParameterSet(e.sps,h.data,e.vps),a||(a=u(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const C=this.readPPS(h.data);for(const v in C)e.params[v]=C[v]}this.pushParameterSet(e.pps,h.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(m=a)!=null&&m.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=u(!1));break;default:o=!1;break}a&&o&&a.units.push(h)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,i,s){if(!e)return!1;if(!t.audFound&&s===0)return!0;if(!e.frame)return!1;const{type:r,data:a}=i;return r>=32&&r<=35||r===39||r>=41&&r<=44||r>=48&&r<=55?!0:r<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new bs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new bs(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(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),h=t.readUByte(),d=t.readUByte(),g=t.readUByte(),m=t.readUByte(),A=t.readUByte(),C=t.readUByte(),v=t.readUByte(),x=t.readUByte(),R=[],b=[];for(let pe=0;pe<i;pe++)R.push(t.readBoolean()),b.push(t.readBoolean());if(i>0)for(let pe=i;pe<8;pe++)t.readBits(2);for(let pe=0;pe<i;pe++)R[pe]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),b[pe]&&t.readUByte();t.readUEG();const D=t.readUEG();D==3&&t.skipBits(1);const _=t.readUEG(),M=t.readUEG(),p=t.readBoolean();let $=0,N=0,O=0,W=0;p&&($+=t.readUEG(),N+=t.readUEG(),O+=t.readUEG(),W+=t.readUEG());const q=t.readUEG(),z=t.readUEG(),oe=t.readUEG(),re=t.readBoolean();for(let pe=re?0:i;pe<=i;pe++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let we=0;we<4;we++)for(let Re=0;Re<(we===3?2:6);Re++)if(!t.readBoolean())t.readUEG();else{const it=Math.min(64,1<<4+(we<<1));we>1&&t.readEG();for(let At=0;At<it;At++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const Q=t.readUEG();let ee=0;for(let pe=0;pe<Q;pe++){let we=!1;if(pe!==0&&(we=t.readBoolean()),we){pe===Q&&t.readUEG(),t.readBoolean(),t.readUEG();let Re=0;for(let nt=0;nt<=ee;nt++){const it=t.readBoolean();let At=!1;it||(At=t.readBoolean()),(it||At)&&Re++}ee=Re}else{const Re=t.readUEG(),nt=t.readUEG();ee=Re+nt;for(let it=0;it<Re;it++)t.readUEG(),t.readBoolean();for(let it=0;it<nt;it++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const pe=t.readUEG();for(let we=0;we<pe;we++){for(let Re=0;Re<oe+4;Re++)t.readBits(1);t.readBits(1)}}let te=0,ne=1,Ee=1,Ie=!0,_e=1,ye=0;t.readBoolean(),t.readBoolean();let Oe=!1;if(t.readBoolean()){if(t.readBoolean()){const at=t.readUByte(),Nt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],rt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];at>0&&at<16?(ne=Nt[at-1],Ee=rt[at-1]):at===255&&(ne=t.readBits(16),Ee=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Oe=t.readBoolean(),Oe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(_e=t.readBits(32),ye=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const rt=t.readBoolean(),ue=t.readBoolean();let Ze=!1;(rt||ue)&&(Ze=t.readBoolean(),Ze&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ze&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let xt=0;xt<=i;xt++){Ie=t.readBoolean();const ft=Ie||t.readBoolean();let li=!1;ft?t.readEG():li=t.readBoolean();const Gt=li?1:t.readUEG()+1;if(rt)for(let Dt=0;Dt<Gt;Dt++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ue)for(let Dt=0;Dt<Gt;Dt++)t.readUEG(),t.readUEG(),Ze&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),te=t.readUEG())}let Fe=_,Ye=M;if(p){let pe=1,we=1;D===1?pe=we=2:D==2&&(pe=2),Fe=_-pe*N-pe*$,Ye=M-we*W-we*O}const Ct=s?["A","B","C"][s]:"",yt=o<<24|l<<16|u<<8|h;let We=0;for(let pe=0;pe<32;pe++)We=(We|(yt>>pe&1)<<31-pe)>>>0;let St=We.toString(16);return a===1&&St==="2"&&(St="6"),{codecString:`hvc1.${Ct}${a}.${St}.${r?"H":"L"}${x}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,l,u,h],general_constraint_indicator_flags:[d,g,m,A,C,v],general_level_idc:x,bit_depth:q+8,bit_depth_luma_minus8:q,bit_depth_chroma_minus8:z,min_spatial_segmentation_idc:te,chroma_format_idc:D,frame_rate:{fixed:Ie,fps:ye/_e}},width:Fe,height:Ye,pixelRatio:[ne,Ee]}}readPPS(e){const t=new bs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),r=t.readBoolean();let a=1;return r&&s?a=0:r?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return Yt(e).substring(3)===Yt(t).substring(3)}}const ct=188;class mi{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=mi.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){const t=e.length;let i=Math.min(ct*5,t-ct)+1,s=0;for(;s<i;){let r=!1,a=-1,o=0;for(let l=s;l<t;l+=ct)if(e[l]===71&&(t-l===ct||e[l+ct]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+ct*99,e.length-ct)+1)),r||(r=gr(e,l)===0),r&&o>1&&(a===0&&o>2||l+ct>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:to[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=mi.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Mf(this.logger):null,this._audioTrack=mi.createTrack("audio",s),this._id3Track=mi.createTrack("id3"),this._txtTrack=mi.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,r?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,s=!1,r=!1){s||(this.sampleAes=null);let a;const o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,h=this._id3Track,d=this._txtTrack,g=i.iframe;let m=o.pid,A=o.pesData,C=u.pid,v=h.pid,x=this._klvPid,R=u.pesData,b=h.pesData,D=null,_=null,M=this.pmtParsed,p=this._pmtId,$=e.length;if(this.remainderData&&(e=Bt(this.remainderData,e),$=e.length,this.remainderData=null),$<ct&&!r)return this.remainderData=e,{audioTrack:u,videoTrack:o,id3Track:h,textTrack:d};const N=Math.max(0,mi.syncOffset(e));$-=($-N)%ct,$<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,$,e.buffer.byteLength-$));let O=0;for(let q=N;q<$;q+=ct)if(e[q]===71){const z=!!(e[q+1]&64),oe=gr(e,q),re=(e[q+3]&48)>>4;let J;if(re>1){if(J=q+5+e[q+4],J===q+ct)continue}else J=q+4;switch(oe){case m:z&&(A&&!(l!=null&&l.isCorrupted)&&(a=Oi(A,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,a,!1,i)),A={data:[],size:0},l?.reset(m)),l?.handlePacket(e.subarray(q)),A&&(A.data.push(e.subarray(J,q+ct)),A.size+=q+ct-J);break;case C:if(g)break;if(z){if(R&&(a=Oi(R,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,a,i);break;case"mp3":this.parseMPEGPES(u,a);break;case"ac3":this.parseAC3PES(u,a);break}R={data:[],size:0}}R&&(R.data.push(e.subarray(J,q+ct)),R.size+=q+ct-J);break;case v:if(g)break;z&&(b&&(a=Oi(b,this.logger))&&this.parseID3PES(h,a),b={data:[],size:0}),b&&(b.data.push(e.subarray(J,q+ct)),b.size+=q+ct-J);break;case x:if(g)break;z&&(D&&(a=Oi(D,this.logger))&&this.parseKlvPES(h,a),D={data:[],size:0}),D&&(D.data.push(e.subarray(J,q+ct)),D.size+=q+ct-J);break;case 0:z&&(J+=e[J]+1),p=this._pmtId=kf(e,J);break;case p:{z&&(J+=e[J]+1);const Z=wf(e,J,this.typeSupported,s,this.observer,this.logger,this.config,i);m=Z.videoPid,m>0&&(o.pid=m,o.segmentCodec=Z.segmentVideoCodec),C=Z.audioPid,C>0&&(u.pid=C,u.segmentCodec=Z.segmentAudioCodec),v=Z.id3Pid,v>0&&(h.pid=v),x=Z.klvPid,x>0&&(this._klvPid=x),_!==null&&!M&&(this.logger.warn(`MPEG-TS PMT found at ${q} after unknown PID '${_}'. Backtracking to sync byte @${N} to parse all TS packets.`),_=null,q=N-188),M=this.pmtParsed=!0;break}case 17:case 8191:break;default:_=oe;break}}else O++;O>0&&Rn(this.observer,new Error(`Found ${O} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=A,u.pesData=R,h.pesData=b;const W={audioTrack:u,videoTrack:o,id3Track:h,textTrack:d};return r&&this.extractRemainingSamples(W,i),W}flush(e,t){const{remainderData:i}=this;this.remainderData=null;let s;return i?s=this.demux(i,0,t,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,t),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(e,t){const{audioTrack:i,videoTrack:s,id3Track:r,textTrack:a}=e,o=s.pesData,l=i.pesData,u=r.pesData,h=this.videoIntegrityChecker;let d;if(o&&!(h!=null&&h.isCorrupted)&&(d=Oi(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,a,d,!0,t),s.pesData=null)):s.pesData=o,l&&(d=Oi(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d,t);break;case"mp3":this.parseMPEGPES(i,d);break;case"ac3":this.parseAC3PES(i,d);break}i.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(d=Oi(u,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=u}demuxSampleAes(e,t,i,s){const r=this.demux(e,i,s,!0,!this.config.progressive),a=this.sampleAes=new Fl(this.observer,this.config,t);return this.decrypt(r,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Pf:e==="hevc"&&(this.videoParser=new _f))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&s.segmentCodec==="aac"?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,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let s=0;const r=this.aacOverFlow;let a=t.data;if(r){this.aacOverFlow=null;const g=r.missing,m=r.sample.unit.byteLength;if(g===-1)a=Bt(r.sample.unit,a);else{const A=m-g;r.sample.unit.set(a.subarray(0,g),A),e.samples.push(r.sample),s=r.missing}}let o,l;for(o=s,l=a.length;o<l-1&&!fr(a,o);o++);if(o!==s){let g;const m=o<l-1;if(m?g=`AAC PES did not start with ADTS header,offset:${o}`:g="No ADTS header found in AAC PES",Rn(this.observer,new Error(g),i,m,this.logger),!m)return}Dl(e,this.observer,a,o,this.audioCodec);let u;if(t.pts!==void 0)u=t.pts;else if(r){const g=Pl(e.samplerate);u=r.sample.pts+g}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,d;for(;o<l;)if(d=_l(e,a,o,u,h),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(h++;o<l-1&&!fr(a,o);o++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Ml(i,a)){const l=kl(e,i,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=i.length;let a=0,o=0,l;for(;o<r&&(l=Bl(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=je({},t,{type:this._videoTrack?Et.emsg:Et.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i;const s=(i=t.pts)!=null?i:t.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const r=t.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<r.length;){var o;if(a+16>r.length)break;const l=a;if(a+=16,a>=r.length)break;const u=r[a];a+=1;let h=0;if(u&128){const A=u&127;if(A===0||A>4||a+A>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let C=0;C<A;C++)h=h<<8|r[a+C];a+=A}else h=u;if(a+h>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=a+h,g=r.subarray(l,d),m={data:g,len:g.byteLength,pts:s,dts:(o=t.dts)!=null?o:s,type:Et.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(m),a=d}}}function gr(n,e){return((n[e+1]&31)<<8)+n[e+2]}function kf(n,e){return(n[e+10]&31)<<8|n[e+11]}function wf(n,e,t,i,s,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(n[e+1]&15)<<8|n[e+2],h=e+3+u-4,d=(n[e+10]&15)<<8|n[e+11];for(e+=12+d;e<h;){const g=gr(n,e),m=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!i){Dn("ADTS AAC",r);break}case 15:l.audioPid===-1&&(l.audioPid=g);break;case 21:l.id3Pid===-1&&(l.id3Pid=g);break;case 219:if(!i){Dn("H.264",r);break}case 27:l.videoPid===-1&&(l.videoPid=g);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=g,l.segmentAudioCodec="mp3");break;case 193:if(!i){Dn("AC-3",r);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=g,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(m>0){let A=e+5,C=m;for(;C>2;){switch(n[A]){case 106:l.audioPid===-1&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=g,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=g,r.log(`KLV metadata PID found: ${g}`));break}const x=n[A+1]+2;A+=x,C-=x}}break;case 194:case 135:return Rn(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:l.videoPid===-1&&(l.videoPid=g,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=m+5}return l}function Rn(n,e,t,i,s){s.warn(`parsing error: ${e.message}`),n.emit(E.ERROR,E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:t,error:e,reason:e.message})}function Dn(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Oi(n,e){let t=0,i,s,r,a,o;const l=n.data;if(!n||n.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Bt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>n.size-6)return null;const h=i[7];h&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,h&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=i[8];let d=r+9;if(n.size<=d)return null;n.size-=d;const g=new Uint8Array(n.size);for(let m=0,A=l.length;m<A;m++){i=l[m];let C=i.byteLength;if(d)if(d>C){d-=C;continue}else i=i.subarray(d),C-=d,d=0;g.set(i,t),t+=C}return s&&(s-=r+3),{data:g,pts:a,dts:o,len:s}}return null}class Mf{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=gr(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}const i=(e[3]&48)>>4;if(i===0)return;const s=e[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=s;const a=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0||r<0)return;const u=a?r+1&15:r;if(s!==u){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${u} Last-CC=${r}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class Of{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}var pr;const Ff={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Pn=new Uint8Array([0,0,0,0,0,0,0,0]),Nf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Bf=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Uf=new Uint8Array([0,0,0,0,0,0,0,0]),Ls=new Uint8Array([0,0,0,0,0,0,0,1]),Gl=new Uint8Array([105,115,111,109]),$f=new Uint8Array([97,118,99,49]),Gf=new Uint8Array([0,0,0,1]);class le{static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[s].byteLength;const a=new Uint8Array(i);for(lt(a,0,i),lt(a,4,e),s=0,i=8;s<r;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return le.box(Te.hdlr,Ff[e])}static mdat(e){return le.box(Te.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Jt+1)),s=Math.floor(t%(Jt+1));return le.box(Te.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return le.box(Te.mdia,le.mdhd(e.timescale||0,e.duration||0),le.hdlr(e.type),le.minf(e))}static mfhd(e){return le.box(Te.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?le.box(Te.minf,le.box(Te.smhd,Uf),le.DINF,le.stbl(e)):le.box(Te.minf,le.box(Te.vmhd,Bf),le.DINF,le.stbl(e))}static moof(e,t,i){return le.box(Te.moof,le.mfhd(e),le.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=le.trak(e[t]);return le.box.apply(null,[Te.moov,le.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(le.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=le.trex(e[t]);return le.box.apply(null,[Te.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Jt+1)),s=Math.floor(t%(Jt+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,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return le.box(Te.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 le.box(Te.sdtp,i)}static stbl(e){return le.box(Te.stbl,le.stsd(e),le.box(Te.stts,Pn),le.box(Te.stsc,Pn),le.box(Te.stsz,Nf),le.box(Te.stco,Pn))}static avc1(e){let t=[],i=[],s,r,a;for(s=0;s<e.sps.length;s++)r=e.sps[s],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(s=0;s<e.pps.length;s++)r=e.pps[s],a=r.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=le.box(Te.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return le.box(Te.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,le.box(Te.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),le.box(Te.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return le.box(Te.mp4a,le.audioStsd(e),le.box(Te.esds,le.esds(e)))}static mp3(e){return le.box(Te[".mp3"],le.audioStsd(e))}static ac3(e){return le.box(Te["ac-3"],le.audioStsd(e),le.box(Te.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return le.box(Te.stsd,Ls,le.mp4a(e));if(t==="ac3"&&e.config)return le.box(Te.stsd,Ls,le.ac3(e));if(t==="mp3"&&e.codec==="mp3")return le.box(Te.stsd,Ls,le.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return le.box(Te.stsd,Ls,le.avc1(e));if(t==="hevc"&&e.vps)return le.box(Te.stsd,Ls,le.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,r=e.height||0,a=Math.floor(i/(Jt+1)),o=Math.floor(i%(Jt+1));return le.box(Te.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=le.sdtp(e),s=e.id,r=Math.floor(t/(Jt+1)),a=Math.floor(t%(Jt+1));return le.box(Te.traf,le.box(Te.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),le.box(Te.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),le.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,le.box(Te.trak,le.tkhd(e),le.mdia(e))}static trex(e){const t=e.id;return le.box(Te.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,r=12+16*s,a=new Uint8Array(r);let o,l,u,h,d,g;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],u=l.duration,h=l.size,d=l.flags,g=l.cts,a.set([u>>>24&255,u>>>16&255,u>>>8&255,u&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,g>>>24&255,g>>>16&255,g>>>8&255,g&255],12+16*o);return le.box(Te.trun,a)}static initSegment(e){const t=le.moov(e);return Bt(le.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let a=r.length;for(let A=0;A<i.length;A+=1){a+=3;for(let C=0;C<i[A].length;C+=1)a+=2+i[A][C].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=i.length-1;for(let A=0;A<i.length;A+=1){o.set(new Uint8Array([32+A|(A===l?128:0),0,i[A].length]),a),a+=3;for(let C=0;C<i[A].length;C+=1)o.set(new Uint8Array([i[A][C].length>>8,i[A][C].length&255]),a),a+=2,o.set(i[A][C],a),a+=i[A][C].length}const u=le.box(Te.hvcC,o),h=e.width,d=e.height,g=e.pixelRatio[0],m=e.pixelRatio[1];return le.box(Te.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,h>>8&255,h&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,le.box(Te.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),le.box(Te.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,g&255,m>>24,m>>16&255,m>>8&255,m&255])))}}pr=le,le.FTYP=pr.box(Te.ftyp,Gl,Gf,Gl,$f),le.DINF=pr.box(Te.dinf,pr.box(Te.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const Hl=9e4;function _n(n,e,t=1,i=!1){const s=n*e*t;return i?Math.round(s):s}function Hf(n,e,t=1,i=!1){return _n(n,e,1/t,i)}function Rs(n,e=!1){return _n(n,1e3,1/Hl,e)}function Vf(n,e=1){return _n(n,Hl,1/e)}function Vl(n){const{baseTime:e,timescale:t,trackId:i}=n;return`${e/t} (${e}/${t}) trackId: ${i}`}const Kf=10*1e3,Yf=1024,Wf=1152,jf=1536,kn=8589934592;function Kl(n,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1,paddingValue:0}}}class mr extends wt{constructor(e,t,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Vl(t)} > ${e&&Vl(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=Ot(o,i),l=o-r),l>0?r:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,a,o,l,u){let h,d,g,m,A,C,v=r,x=r;const b=!u.iframe&&e.pid>-1,D=t.pid>-1,_=t.samples.length,M=e.samples.length>0,p=o&&_>0||_>1;if((!b||M)&&(!D||p)||this.ISGenerated||o){if(this.ISGenerated){var N,O,W,q;const J=this.videoTrackConfig;(J&&(t.width!==J.width||t.height!==J.height||((N=t.pixelRatio)==null?void 0:N[0])!==((O=J.pixelRatio)==null?void 0:O[0])||((W=t.pixelRatio)==null?void 0:W[1])!==((q=J.pixelRatio)==null?void 0:q[1]))||!J&&p||this.nextAudioTs===null&&M)&&this.resetInitSegment()}this.ISGenerated||(g=this.generateIS(e,t,r,a));const z=this.isVideoContiguous;let oe=-1,re;if(p&&(oe=qf(t.samples),!z&&this.config.forceKeyFrameOnDiscontinuity))if(C=!0,oe>0){this.warn(`Dropped ${oe} out of ${_} video samples due to a missing keyframe`);const J=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(oe),t.dropped+=oe,x+=(t.samples[0].pts-J)/t.inputTimeScale,re=x}else oe===-1&&(this.warn(`No keyframe found out of ${_} video samples`),C=!1);if(this.ISGenerated){if(M&&p&&r){const J=this.getVideoStartPts(t.samples),Q=(Ot(e.samples[0].pts,J)-J)/t.inputTimeScale;v+=Math.max(0,Q),x+=Math.max(0,-Q)}if(M){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),g=this.generateIS(e,t,r,a)),d=this.remuxAudio(e,v,this.isAudioContiguous,a,D||p||l===ge.AUDIO?x:void 0,u),p){const J=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),g=this.generateIS(e,t,r,a)),h=this.remuxVideo(t,x,z,J,u)}}else p&&(h=this.remuxVideo(t,x,z,0,u));h&&(h.firstKeyFrame=oe,h.independent=oe!==-1,h.firstKeyFramePTS=re)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(A=Yl(i,r,this._initPTS,this._initDTS)),s.samples.length&&(m=Wl(s,r,this._initPTS))),{audio:d,video:h,initSegment:g,independent:C,text:m,id3:A}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let a=Ot(e,r);if(a<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${s}`);a<r;)a+=kn;return a-r}generateIS(e,t,i,s){const r=e.samples,a=t.samples,o=this.typeSupported,l={},u=this._initPTS,h=!u||s;let d="audio/mp4",g,m,A,C=-1;if(h&&(g=m=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):le.initSegment([e]),metadata:{channelCount:e.channelCount}},h){C=e.id,A=e.inputTimeScale;const v=this.computeInitPts(r[0].pts,A,i,"audio");(!u||A!==u.timescale||i===0&&v<u.baseTime)&&(g=m=v)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:le.initSegment([t]),metadata:{width:t.width,height:t.height}},h){C=t.id,A=t.inputTimeScale;const v=this.getVideoStartPts(a),x=Ot(a[0].dts,v),R=this.computeInitPts(x,A,i,"video"),b=this.computeInitPts(v,A,i,"video");(!u||A!==u.timescale||se(g)||i===0&&b<u.baseTime)&&(m=Math.min(m,R),g=Math.min(g,R))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&se(g)?(u&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${g/A} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${g/A} (${g}/${A}) trackId: ${C}`),this._initPTS={baseTime:g,timescale:A,trackId:C},this._initDTS={baseTime:m,timescale:A,trackId:C}):g=A=void 0,{tracks:l,initPTS:g,timescale:A,trackId:C}}remuxVideo(e,t,i,s,r){const a=e.inputTimeScale,o=e.samples,l=[],u=o.length,h=this._initPTS,d=h.baseTime*a/h.timescale;let g=this.nextVideoTs,m=8,A=this.videoSampleDuration,C,v,x=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,b=!1;if(!i||g===null){const te=d+t*a,ne=o[0].pts-Ot(o[0].dts,o[0].pts);ms()&&g!==null&&Math.abs(te-ne-(g+d))<15e3?i=!0:g=te-ne-d}const D=g+d;for(let te=0;te<u;te++){const ne=o[te];ne.pts=Ot(ne.pts,D),ne.dts=Ot(ne.dts,D),ne.dts<o[te>0?te-1:te].dts&&(b=!0)}b&&o.sort(function(te,ne){const Ee=te.dts-ne.dts,Ie=te.pts-ne.pts;return Ee||Ie}),C=o[0].dts,v=o[o.length-1].dts;const _=v-C,M=_?Math.round(_/(u-1)):A||e.inputTimeScale/30;if(i){const te=C-D,ne=te>M,Ee=te<-1;if((ne||Ee)&&(ne?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Rs(te,!0)} ms (${te}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Rs(-te,!0)} ms (${te}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Ee||D>=o[0].pts||ms())){C=D;const Ie=o[0].pts-te;if(ne)o[0].dts=C,o[0].pts=Ie;else{let _e=!0;for(let ye=0;ye<o.length&&!(o[ye].dts>Ie&&_e);ye++){const Oe=o[ye].pts;if(o[ye].dts-=te,o[ye].pts-=te,ye<o.length-1){const Le=o[ye+1].pts,Fe=o[ye].pts,Ye=Le<=Fe,Ct=Le<=Oe;_e=Ye==Ct}}}this.log(`Video: Initial PTS/DTS adjusted: ${Rs(Ie,!0)}/${Rs(C,!0)}, delta: ${Rs(te,!0)} ms`)}}C=Math.max(0,C);let p=0,$=0,N=C;for(let te=0;te<u;te++){const ne=o[te],Ee=ne.units,Ie=Ee.length;let _e=0;for(let ye=0;ye<Ie;ye++)_e+=Ee[ye].data.length;$+=_e,p+=Ie,ne.length=_e,ne.dts<N?(ne.dts=N,N+=M/4|0||1):N=ne.dts,x=Math.min(ne.pts,x),R=Math.max(ne.pts,R)}v=o[u-1].dts;const O=$+4*p+8;let W;try{W=new Uint8Array(O)}catch(te){this.observer.emit(E.ERROR,E.ERROR,{type:me.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:te,bytes:O,reason:`fail allocating video mdat ${O}`});return}lt(W,0,O),lt(W,4,Te.mdat);let q=!1,z=Number.POSITIVE_INFINITY,oe=Number.POSITIVE_INFINITY,re=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY;for(let te=0;te<u;te++){const ne=o[te],Ee=ne.units;let Ie=0;for(let Oe=0,Le=Ee.length;Oe<Le;Oe++){const Fe=Ee[Oe],Ye=Fe.data,Ct=Fe.data.byteLength;lt(W,m,Ct),m+=4,W.set(Ye,m),m+=Ct,Ie+=4+Ct}let _e;if(te<u-1)A=o[te+1].dts-ne.dts,_e=o[te+1].pts-ne.pts;else{const Oe=this.config,Le=te>0?ne.dts-o[te-1].dts:M;if(_e=te>0?ne.pts-o[te-1].pts:M,Oe.stretchShortVideoTrack&&this.nextAudioTs!==null){const Fe=Math.floor(Oe.maxBufferHole*a),Ye=(s?x+s*a:this.nextAudioTs+d)-ne.pts;Ye>Fe?(A=Ye-Le,A<0?A=Le:q=!0,this.log(`It is approximately ${Ye/90} ms to the next segment; using duration ${A/90} ms for the last video frame.`)):A=Le}else A=Le}let ye=Math.round(ne.pts-ne.dts);if(z=Math.min(z,A),re=Math.max(re,A),oe=Math.min(oe,_e),J=Math.max(J,_e),!i&&te===0&&ye>A){const Oe=Math.round(ye/M)*M;Oe-ye===1&&(this.log(`pad first CTS ${ye} -> ${Oe} of sn: ${r.sn}`),ye=Oe)}l.push(Kl(ne.key,A,Ie,ye))}if(l.length){const te=ms();if(te){if(te<70){const ne=l[0].flags;ne.dependsOn=2,ne.isNonSync=0}}else if(qh()&&J-oe<re-z&&M/re<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let ne=C;for(let Ee=0,Ie=l.length;Ee<Ie;Ee++){const _e=ne+l[Ee].duration,ye=ne+l[Ee].cts;if(Ee<Ie-1){const Oe=_e+l[Ee+1].cts;l[Ee].duration=Oe-ye}else l[Ee].duration=Ee?l[Ee-1].duration:M;l[Ee].cts=0,ne=_e}}}A=q||!A?M:A;const Z=v+A;this.nextVideoTs=g=Z-d,this.videoSampleDuration=A,this.isVideoContiguous=!0,r.iframe&&(l.length===1?(l[0].duration=A=r.duration*a,this.nextVideoTs=g=C+A-d):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));const he={data1:le.moof(r.sn,C,je(e,{samples:l})),data2:W,startPTS:(x-d)/a,endPTS:(R+A-d)/a,startDTS:(C-d)/a,endDTS:g/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,he}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Wf;case"ac3":return jf;default:return Yf}}remuxAudio(e,t,i,s,r,a){const o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,u=o/l,h=this.getSamplesPerFrame(e),d=h*u,g=this._initPTS,m=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,A=[],C=r!==void 0;let v=e.samples,x=m?0:8,R=this.nextAudioTs||-1;const b=g.baseTime*o/g.timescale,D=b+t*o;if(this.isAudioContiguous=i=i||v.length&&R>0&&(s&&Math.abs(D-(R+b))<9e3||Math.abs(Ot(v[0].pts,D)-(R+b))<20*d),v.forEach(function(Z){Z.pts=Ot(Z.pts,D)}),!i||R<0){const Z=v.length;if(v=v.filter(Q=>Q.pts>=0),Z!==v.length&&this.warn(`Removed ${v.length-Z} of ${Z} samples (initPTS ${b} / ${o})`),!v.length)return;r===0?R=0:s&&!C?R=Math.max(0,D-b):R=v[0].pts-b}if(e.segmentCodec==="aac"){const Z=this.config.maxAudioFramesDrift;for(let Q=0,ee=R+b;Q<v.length;Q++){const he=v[Q],te=he.pts,ne=te-ee,Ee=Math.abs(1e3*ne/o);if(ne<=-Z*d&&C)Q===0&&(this.warn(`Audio frame @ ${(te/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*ne/o)} ms.`),this.nextAudioTs=R=te-b,ee=te);else if(ne>=Z*d&&Ee<Kf&&C){let Ie=Math.round(ne/d);for(ee=te-Ie*d;ee<0&&Ie&&d;)Ie--,ee+=d;Q===0&&(this.nextAudioTs=R=ee-b),this.warn(`Injecting ${Ie} audio frames @ ${((ee-b)/o).toFixed(3)}s due to ${Math.round(1e3*ne/o)} ms gap.`);for(let _e=0;_e<Ie;_e++){let ye=Of.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ye||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ye=he.unit.subarray()),v.splice(Q,0,{unit:ye,pts:ee}),ee+=d,Q++}}he.pts=ee,ee+=d}}let _=null,M=null,p,$=0,N=v.length;for(;N--;)$+=v[N].unit.byteLength;for(let Z=0,Q=v.length;Z<Q;Z++){const ee=v[Z],he=ee.unit;let te=ee.pts;if(M!==null){const Ee=A[Z-1];Ee.duration=Math.round((te-M)/u)}else if(i&&e.segmentCodec==="aac"&&(te=R+b),_=te,$>0){$+=x;try{p=new Uint8Array($)}catch(Ee){this.observer.emit(E.ERROR,E.ERROR,{type:me.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Ee,bytes:$,reason:`fail allocating audio mdat ${$}`});return}m||(lt(p,0,$),lt(p,4,Te.mdat))}else return;p&&p.set(he,x);const ne=he.byteLength;x+=ne,A.push(Kl(!0,h,ne,0)),M=te}const O=A.length;if(!O)return;const W=A[A.length-1];R=M-b,this.nextAudioTs=R+u*W.duration;const q=m?new Uint8Array(0):le.moof(e.sequenceNumber++,_/u,je({},e,{samples:A}));e.samples=[];const z=(_-b)/o,oe=this.nextAudioTs/o,J={data1:q,data2:p,startPTS:z,endPTS:oe,startDTS:z,endDTS:oe,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,J}}function Ot(n,e){let t;if(e===null)return n;for(e<n?t=-kn:t=kn;Math.abs(n-e)>4294967296;)n+=t;return n}function qf(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Yl(n,e,t,i){const s=n.samples.length;if(!s)return;const r=n.inputTimeScale;for(let o=0;o<s;o++){const l=n.samples[o];l.pts=Ot(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=Ot(l.dts-i.baseTime*r/i.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function Wl(n,e,t){const i=n.samples.length;if(!i)return;const s=n.inputTimeScale;for(let a=0;a<i;a++){const o=n.samples[a];o.pts=Ot(o.pts-t.baseTime*s/t.timescale,e*s)/s}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class zf extends wt{constructor(e,t,i,s){super("passthrough-remuxer",s),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:o}=this.initData=i||oo(e);if(t)Mh(e,t);else{const u=a||o;u!=null&&u.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`)}a&&(s=jl(a,ze.AUDIO,this)),o&&(r=jl(o,ze.VIDEO,this));const l={};a&&o?l.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:s,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,s,r,a,o,l,u,h,d){var g,m;let{initPTS:A,lastEndTime:C}=this;const v={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};se(C)||(C=this.lastEndTime=r||0);const x=t.samples;if(!x.length)return v;const R=this.pendingInitSegment;R&&(this.pendingInitSegment=void 0,this.generateInitSegment(R,this.decryptdata,h));const b={initPTS:void 0,timescale:void 0,trackId:void 0};let D=this.initData;if((g=D)!=null&&g.length||(this.generateInitSegment(x),D=this.initData),!((m=D)!=null&&m.length))return this.warn("Failed to generate initSegment."),v;if(u.iframe&&D.audio&&D.video){var _;const pe=(_=this.initTracks)==null||(_=_.audiovideo)==null?void 0:_.initSegment,we=pe?Rh(pe):null;if(we){var M;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(we,this.decryptdata),(M=this.initData)!=null&&M.length&&(D=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(b.tracks=this.initTracks,v.initSegment=b,this.emitInitSegment=!1);const p=u.iframe,$=d&&(!p||d.includeSampleDetails)?d.tracks:Bh(x,D,u,this,p),N=D.audio?$[D.audio.id]:null,O=D.video?$[D.video.id]:null,W=!!D.audio,q=!!D.video;let z="";W&&(z+="audio"),q&&(z+="video");const oe=Ar(O,1/0),re=Ar(N,1/0),J=Ar(O,0,!0),Z=Ar(N,0,!0);let Q=r,ee=0;O&&N&&D.audio&&(re>J||oe>Z)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${oe}-${J} a: ${re}-${Z}}`,O,N);const he=!!N&&(!O||!A&&re<oe||!!A&&A.trackId===D.audio.id),te=he?N:O;if(!te)return this.log(`No media samples found in ${l} ${u.level} ${u.part===-1?"":`part: ${u.part} of`} sn: ${u.sn} at playlist time: ${r}`),v;let ne=x,Ee,Ie;if(O&&O.sampleCount>=1&&D.video&&u.iframe){const{trun:pe,start:we}=O,Re=pe.length===1,nt=pe.length?Re?pe[0].samples:pe[0].samples.concat(...pe.slice(1).map(it=>it.samples)):[];if(nt.length){const it=pe[0];let At=it;for(let xt=pe.length;xt--;)if(pe[xt].samples.length){At=pe[xt];break}const at=At.lastSampleDurationOffset,{defaultSampleDurationOffset:Nt}=it,rt=Math.abs(u.duration-(J-oe))>.05,ue=nt.length<O.sampleCount;if(!(rt||ue||this.videoOnlyRemux||!Re))ee=J-oe;else{const xt=ue?At.sampleOffset+At.samples.reduce((Dt,Di)=>Dt+Di.size,0):void 0,ft=rt?u.duration:J-oe,li=Zf(nt,ft*D.video.timescale,at,Nt),Gt=Dh(x,D.video.id,nt.length,xt,li);Gt?(ne=Gt,Ie=Xf(we,nt)):this.warn(`IFrame remux skipped (sn ${u.sn}); using native sample duration`),ee=Gt&&li?ft:J-oe}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${pe.length})`),ee=J-oe}else ee=he?Z-re:J-oe;if(this.videoOnlyRemux&&ne===x)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${u.sn})`),v;const _e=te.timescale,ye=te.start-r*_e,Oe=he?D.audio.id:D.video.id;if(Q=te.start/_e,(a||!A)&&(Qf(A,Q,r,ee)||_e!==A.timescale)){let pe=!1;const we=he?"audio":"video";if(A){const Re=r!==0?Q/r:1+Q/1;pe=Q>=0&&Math.abs(1-Re)<.001,this.log(`${we} timestamps in track ${Oe} at playlist time: ${a?"":"~"}${r} maps to ${Q} with initPTS: ${A.baseTime/A.timescale} (${ye/_e-A.baseTime/A.timescale}s diff) (${z}) drift estimate: ${Re} ${pe?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}pe||(this.log(`Found initPTS in ${we} track ${Oe} at playlist time: ${r} offset: ${Q-r} (${ye}/${_e})`),A=null,b.initPTS=ye,b.timescale=_e,b.trackId=Oe)}A?(b.initPTS=A.baseTime,b.timescale=A.timescale,b.trackId=A.trackId):((!b.timescale||b.trackId===void 0||b.initPTS===void 0)&&(this.warn("Could not set initPTS"),b.initPTS=Q,b.timescale=1,b.trackId=-1),this.initPTS=A={baseTime:b.initPTS,timescale:b.timescale,trackId:b.trackId});const Le=Q-A.baseTime/A.timescale,Fe=Le+ee,Ye=q&&te?.ptsMin!==void 0?te.ptsMin/te.timescale-A.baseTime/A.timescale:Le,Ct=Ie!==void 0&&O?Ie/O.timescale-A.baseTime/A.timescale:q&&te!=null&&te.ptsMax?te.ptsMax/te.timescale-A.baseTime/A.timescale:Fe;ee>0?this.lastEndTime=Fe:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const yt=(D.audio?D.audio.encrypted:!1)||(D.video?D.video.encrypted:!1),We={data1:ne,data2:Ee,startPTS:Ye,startDTS:Le,endPTS:Ct,endDTS:Fe,type:z,hasAudio:W,hasVideo:q,nb:1,dropped:0,encrypted:yt};v.audio=W&&!q?We:void 0,v.video=q?We:void 0;const St=this.isVideoContiguous,$t=O?.sampleCount;if($t){const pe=O.keyFrameIndex,we=pe!==-1;We.nb=$t,We.dropped=pe===0||St?0:we?pe:$t,We.independent=we,We.firstKeyFrame=pe,we&&O.keyFrameStart&&(We.firstKeyFramePTS=(O.keyFrameStart-A.baseTime)/A.timescale),St||(v.independent=we),this.isVideoContiguous||(this.isVideoContiguous=we),We.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${pe}/${$t} dropped: ${We.dropped} start: ${We.firstKeyFramePTS||"NA"}`)}return v.initSegment=b,v.id3=Yl(i,r,A,A),s.samples.length&&(v.text=Wl(s,r,A)),v}}function Ar(n,e,t=!1){return n?.start!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function Xf(n,e){let t=n,i=n;for(let s=0;s<e.length;s++){const{cts:r,duration:a}=e[s];i=Math.max(i,t+(r||0)+a),t+=a}return i}function Zf(n,e,t,i){if(t!==void 0){const r=n[n.length-1];let a=e;for(let o=0;o<n.length-1;o++)a-=n[o].duration;return a<=0&&(a=r.duration),r.duration=a,{durationOffset:t,value:a}}if(i===void 0)return;const s=Math.round(e/n.length);for(let r=0;r<n.length;r++)n[r].duration=s;return{durationOffset:i,value:s}}function Qf(n,e,t,i){if(n===null)return!0;const s=Math.max(i,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>=s}function jl(n,e,t){const i=n.codec;return i&&i.length>4?i:e===ze.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Js(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):i==="mjpg"?i:(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let xi;try{xi=self.performance.now.bind(self.performance)}catch{xi=Date.now}const Ir=[{demux:Lf,remux:zf},{demux:mi,remux:mr},{demux:Tf,remux:mr},{demux:xf,remux:mr}];Ir.splice(2,0,{demux:Sf,remux:mr});class ql{constructor(e,t,i,s,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){if(!this.observer)return Cr(i);const r=i.transmuxing;r.executeStart=xi();const a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:u,discontinuity:h,trackSwitch:d,accurateTimeOffset:g,timeOffset:m,initSegmentChange:A}=s||o,{audioCodec:C,videoCodec:v,defaultInitPts:x,duration:R,initSegmentData:b}=l,D=Jf(a,t);if(D&&Xi(D.method)){const $=this.getDecrypter(),N=pn(D.method);return this.asyncResult=!0,this.decryptionPromise=$.decrypt(a,D.key.buffer,D.iv.buffer,N,i.decryptRange).then(O=>{const W=this.push(O,null,i);return this.decryptionPromise=null,W}),this.decryptionPromise}const _=this.needsProbing(h,d);if(_){const $=i.iframe&&b&&mi.probe(b,this.logger)?b:a,N=this.configureTransmuxer($);if(N)return this.logger.warn(`[transmuxer] ${N.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:N,reason:N.message}),r.executeEnd=xi(),Cr(i)}(h||d||A||_)&&this.resetInitSegment(b,C,v,R,t,i),(h||A||_)&&this.resetInitialTimestamp(x),u||this.resetContiguity();const M=this.transmux(a,D,m,g,i);this.asyncResult=Ds(M);const p=this.currentTransmuxState;return p.contiguous=!0,p.discontinuity=!1,p.trackSwitch=!1,r.executeEnd=xi(),M}flush(e){const t=e.transmuxing;t.executeStart=xi();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(i){const d=i.flush();d&&a.push(this.push(d.buffer,null,e))}const{demuxer:l,remuxer:u}=this;if(!l||!u){t.executeEnd=xi();const d=[Cr(e)];return this.asyncResult?Promise.resolve(d):d}const h=l.flush(o,e);return Ds(h)?(this.asyncResult=!0,h.then(d=>(this.flushRemux(a,d,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:u}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);const h=this.remuxer.remux(s,r,a,o,u,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=xi()}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,a){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,i,s,r,a),l.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,s,r){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,r):a=this.transmuxUnencrypted(e,i,s,r),a}transmuxUnencrypted(e,t,i,s){const{demuxer:r,remuxer:a}=this;if(!r||!a)return Cr(s);const o=r.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:u,id3Track:h,textTrack:d}=o;return{remuxResult:a.remux(l,u,h,d,t,i,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id,r,a.initData,a.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;if(!i)return;let r;try{for(let d=0,g=Ir.length;d<g;d++){var a;if((a=Ir[d].demux)!=null&&a.probe(e,this.logger)){r=Ir[d];break}}}catch(d){return d}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,u=r.demux,h=r.remux;(!o||!(o instanceof u))&&(this.logger.log(`Using ${u.name}`),this.demuxer=new u(i,t,s,this.logger),this.probe=u.probe),(!l||!(l instanceof h))&&(this.logger.log(`Using ${h.name}`),this.remuxer=new h(i,t,s,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new hn(this.config)),e}}function Jf(n,e){let t=null;return n.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Cr=n=>({remuxResult:{},chunkMeta:n});function Ds(n){return"then"in n&&n.then instanceof Function}class eg{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 tg{constructor(e,t,i,s,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=a}}let zl=0;class Xl{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=zl++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const u=l.data,h=this.hls;if(!(!h||!(u!=null&&u.event)||u.instanceNo!==this.instanceNo))switch(u.event){case"init":{var d;const g=(d=this.workerContext)==null?void 0:d.objectURL;g&&self.URL.revokeObjectURL(g);break}case"transmuxComplete":{this.handleTransmuxComplete(u.data);break}case"flush":{this.onFlush(u.data);break}case"workerLog":{h.logger[u.data.logType]&&h.logger[u.data.logType](u.data.message);break}default:{u.data=u.data||{},u.data.frag=this.frag,u.data.part=this.part,u.data.id=this.id,h.trigger(u.event,u.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const u=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(l,u)=>{u=u||{},u.frag=this.frag||void 0,l===E.ERROR&&(u=u,u.parent=this.id,u.part=this.part,this.error=u.error),this.hls.trigger(l,u)};this.observer=new Sn,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);const o=yo(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||lf()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=cf(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=uf());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Xe(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new ql(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new ql(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=zl++;const t=this.hls.config,i=yo(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Xe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),hf(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,a,o,l,u,h){var d,g;u.transmuxing.start=self.performance.now();const{instanceNo:m,transmuxer:A}=this,C=a?a.start:r.start,v=r.decryptdata,x=this.frag,R=x?r.cc!==x.cc:!0,b=x?u.level!==x.level:!0,D=x?u.sn-x.sn:-1,_=this.part?u.part-this.part.index:-1,M=D===0&&u.id>1&&u.id===x?.stats.chunkCount,p=!b&&(D===1||D===0&&(_===1||M&&_<=0)),$=self.performance.now();(b||D||r.stats.parsing.start===0)&&(r.stats.parsing.start=$),a&&(_||!p)&&(a.stats.parsing.start=$);const N=!(x&&((d=r.initSegment)==null?void 0:d.url)===((g=x.initSegment)==null?void 0:g.url)),O=new tg(R,p,l,b,C,N);if(!p||R||N){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${u.sn}${u.part>-1?" part: "+u.part:""} ${this.id} playlist: ${u.level} id: ${u.id}
|
|
17
|
-
discontinuity: ${R}
|
|
18
|
-
trackSwitch: ${b}
|
|
19
|
-
contiguous: ${p}
|
|
20
|
-
accurateTimeOffset: ${l}
|
|
21
|
-
timeOffset: ${C}
|
|
22
|
-
initSegmentChange: ${N}`);const W=new eg(i,s,t,o,h);this.configureTransmuxer(W)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:m,cmd:"demux",data:e,decryptdata:v,chunkMeta:u,state:O},e instanceof ArrayBuffer?[e]:[]);else if(A){const W=A.push(e,v,u,O);Ds(W)?W.then(q=>{this.handleTransmuxComplete(q)}).catch(q=>{this.transmuxerError(q,u,"transmuxer-interface push error")}):this.handleTransmuxComplete(W)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);Ds(s)?s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Zl=100;class ig extends En{constructor(e,t,i){super(e,t,i,"audio-stream-controller",ge.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:i,id:s,initPTS:r,timescale:a,trackId:o,timestampOffsets:l}=t;if(s===ge.MAIN){const u=i.cc,h=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${u} found from main: ${r/a} (${r}/${a}) trackId: ${o}`),this.mainAnchor=i,this.state===Y.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==u)&&this.syncWithAnchor(i,d?.frag)}else!this.hls.hasEnoughToStart&&h&&h.cc!==u?(h.abortRequests(),this.syncWithAnchor(i,h)):this.state===Y.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;const r=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Oo(a,r,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===Y.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Y.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Zl),i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Y.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case Y.IDLE:this.doTickIdle();break;case Y.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Y.WAITING_INIT_PTS}break}case Y.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Y.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Y.FRAG_LOADING;const o=s.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Y.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[r]))return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=Y.WAITING_TRACK,this.startFragRequested=!1;return}const u=this.getBufferOutput();this.bufferFlushed&&u&&(this.bufferFlushed=!1,this.afterBufferFlushed(u,ze.AUDIO));const h=this.getFwdBufferInfo();if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=Y.ENDED;return}const d=h.len,g=t.maxBufferLength,m=l.fragments,A=m[0].start,C=this.getLoadPosition(),v=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?C:h.end;if(this.switchingTrack&&s){const b=C;l.PTSKnown&&b<A&&b>=this.timelineOffset&&(h.end>A||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${b} -> ${A} + 0.05`),s.currentTime=A+.05)}if(d>=g&&!this.switchingTrack&&v<m[m.length-1].start)return;let x=this.getNextFragment(v,l);if(x&&this.isLoopLoading(x,v)&&(x=this.getNextFragmentLoopLoading(x,l,h,ge.MAIN,g)),!x){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,g,x))return;let R=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&R&&st(x)&&!x.endList&&(!l.live||!this.loadingParts&&v<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(R)===et.OK&&(this.mainFragLoading=R=null),R&&st(R))){if(x.start>R.end){const D=this.fragmentTracker.getFragAtPos(v,ge.MAIN);D&&D.end>R.end&&(R=D,this.mainFragLoading={frag:D,targetBufferTime:null})}if(x.start>R.end)return}this.loadFragment(x,o,v)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Cs(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Y.STOPPED&&(this.setInterval(Zl),this.state=Y.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:a,groupId:o,track:l}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const u=this.mainDetails;if(!u||r.endCC>u.endCC||u.expired){this.cachedTrackLoadedData=t,this.state!==Y.STOPPED&&(this.state=Y.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=s[a];let d=0;if(r.live||(i=h.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var g;d=this.alignPlaylists(r,h.details,(g=this.levelLastLoaded)==null?void 0:g.details)}r.alignedSliding||(cr(u,r,this),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(u,d),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===Y.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=Y.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const u=l[o];if(!u){this.warn("Audio track is undefined on fragment load progress");return}const h=u.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const d=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2";let g=this.transmuxer;g||(g=this.transmuxer=new Xl(this.hls,ge.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const m=this.initPTS[i.cc],A=(t=i.initSegment)==null?void 0:t.data;if(m!==void 0){const v=s?s.index:-1,x=v!==-1,R=new dn(i.level,i.sn,i.stats.chunkCount,r.byteLength,v,x,i.duration);g.push(r,A,d,"",i,s,h.totalduration,!1,R,m)}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 ${o}`);const{cache:C}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new xl,complete:!1};C.push(new Uint8Array(r)),this.state!==Y.STOPPED&&(this.state=Y.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ge.MAIN&&st(t.frag)&&(this.mainFragLoading=t,this.state===Y.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==ge.AUDIO){!this.audioOnly&&i.type===ge.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(st(i)){const r=this.switchingTrack;r&&(this.bufferedTrack=r)}this.fragBufferedComplete(i,s),this.media&&this.tick()}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,ge.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const i=this.fragPlaying,s=e?.level;return(!i||i.level!==s)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=Y.ERROR;return}switch(t.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.AUDIO,t);break;case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Y.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ke.AUDIO_TRACK&&(this.state=Y.IDLE);break;case U.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ze.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ze.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Y.ENDED&&(this.state=Y.IDLE);const i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,t),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:h}=o,{details:d}=h,{audio:g,text:m,id3:A,initSegment:C}=r;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l),C!=null&&C.tracks&&this.resetTransmuxer();return}if(this.state=Y.PARSING,g&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:v}=this,x=v.nextAudioTrackBufferFlushForwardOffset,R=Math.max(this.getLoadPosition()+x,l.start);super.flushMainBuffer(R,Number.POSITIVE_INFINITY,ge.AUDIO)}if(C!=null&&C.tracks){const v=l.initSegment||l;if(this.unhandledEncryptionError(C,l))return;this._bufferInitSegment(h,C.tracks,v,a),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:C.tracks})}if(g){const{startPTS:v,endPTS:x,startDTS:R,endDTS:b}=g;u&&(u.elementaryStreams[ze.AUDIO]={startPTS:v,endPTS:x,startDTS:R,endDTS:b}),l.setElementaryStreamInfo(ze.AUDIO,v,x,R,b),this.bufferFragmentData(g,l,u,a)}if(A!=null&&(t=A.samples)!=null&&t.length){const v=je({id:i,frag:l,details:d},A);s.trigger(E.FRAG_PARSING_METADATA,v)}if(m){const v=je({id:i,frag:l,details:d},m);s.trigger(E.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,s){if(this.state!==Y.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=ge.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a?.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===et.NOT_LOADED||s===et.PARTIAL){var r;if((r=t.details)!=null&&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=Y.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&cr(a,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;wi({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:a,channels:o},e,Mi)||(sr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,Ae({},e))}get nextAudioTrack(){return this.nextTrackId}}class wn extends wt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t?.renditionReports;if(s){let r=-1;for(let a=0;a<s.length;a++){const o=s[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(u){this.warn(`Could not construct new URL for Rendition Report: ${u}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=s[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const u=i&&bo(i);return new Lo(o,l>=0?l:void 0,u)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,a=s.fragments,o=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(o-r.loading.first)):0;s.advancedDateTime=Date.now()-l;const u=this.hls.config.timelineOffset;if(u!==s.appliedTimelineOffset){const d=Math.max(u||0,0);s.appliedTimelineOffset=d,a.forEach(g=>{g?.setStart(g.playlistOffset+d)})}if(s.live||i!=null&&i.live){var h;const d="levelInfo"in t?t.levelInfo:t.track;s.reloaded(i);const g=(h=a[a.length-1])==null?void 0:h.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const _=new Error(`${g} playlist ${d.id} hit max allowed unchanged reloads.`);this.warn(_);const{networkDetails:M,context:p}=t;this.hls.trigger(E.ERROR,{type:me.NETWORK_ERROR,details:U.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:_,reason:_.message,level:t.level,parent:g,context:p,networkDetails:M,stats:r});return}if(i){zd(i,s,this);const _=s.playlistParsingError;if(_){this.warn(_);const M=this.hls;if(!M.config.ignorePlaylistParsingErrors){const{networkDetails:p}=t;M.trigger(E.ERROR,{type:me.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:_,reason:_.message,level:t.level,parent:g,networkDetails:p,stats:r});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=r.loading.start);const m=this.hls.mainForwardBufferInfo,A=m?m.end-m.len:0,C=(s.edge-A)*1e3,v=ml(s,C);s.requestScheduled+v<o?s.requestScheduled=o:s.requestScheduled<=o&&(s.requestScheduled+=v);const x=t.deliveryDirectives;if(this.log(`live playlist ${e} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${x?` | requested ${x.msn} - ${x.part}`:""})`}`),!this.canLoad||!s.live)return;let R,b,D;if(s.canBlockReload&&s.advanced){const _=this.hls.config.lowLatencyMode,M=s.lastPartSn,p=s.endSN,$=s.lastPartIndex,N=$!==-1,O=M===p;N?O?(b=p+1,D=_?0:$):(b=M,D=_?$+1:s.maxPartIndex):b=p+1;const W=s.age,q=W+s.ageHeader;let z=Math.min(q-s.partTarget,s.targetduration*1.5);if(z>0){if(q>s.targetduration*3)this.log(`Playlist last advanced ${W.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,D=void 0;else if(i!=null&&i.tuneInGoal&&q-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${z} with playlist age: ${s.age}`),z=0;else{const oe=Math.floor(z/s.targetduration);if(b+=oe,D!==void 0){const re=Math.round(z%s.targetduration/s.partTarget);D+=re}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${W.toFixed(2)}s goal: ${z} skip sn ${oe} to part ${D}`)}s.tuneInGoal=z}if(R=this.getDeliveryDirectives(s,t.deliveryDirectives,b,D),_||!O){s.requestScheduled=o,this.loadingPlaylist(d,R);return}}else(s.canBlockReload||s.canSkipUntil)&&(R=this.getDeliveryDirectives(s,t.deliveryDirectives,b,D));R&&b!==void 0&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(v-l*2,v/2)),this.scheduleLoading(d,R,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=s.requestScheduled;if(r>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}const o=Math.max(a-r,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let r=bo(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=ir.No),new Lo(i,s,r)}checkRetry(e){const t=e.details,i=Ks(e),s=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(r===gt.RetryRequest||!s.resolved&&r===gt.SendAlternateToPenaltyBox);if(l){var u;if(a>=o.maxNumRetry)return!1;if(i&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;const d=ds((h=e.response)==null?void 0:h.code);if(this.clearTimer(),d)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const g=Yr(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${g}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),g)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),ds(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function Ql(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Ps(n[t].attrs,e[t].attrs))return!1;return!0}function Ps(n,e,t){const i=n["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>n[s]!==e[s])}class sg extends wn{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(o=>s?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(g=>ys(g.groupId,i));if(o.length)this.selectDefaultTrack&&!o.some(g=>g.default)&&(this.selectDefaultTrack=!1),o.forEach((g,m)=>{g.id=m});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const g=ii(l,o,Mi);if(g>-1)r=o[g];else{const m=ii(l,this.tracks);r=this.tracks[m]}}let u=this.findTrackId(r);u===-1&&r&&(u=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,h);const d=this.trackId;if(u!==-1&&d===-1)this.setAudioTrack(u);else if(o.length&&d===-1){var a;const g=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(g.message),this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:g})}}}onError(e,t){t.fatal||!t.context||t.context.type===ke.AUDIO_TRACK&&t.context.id===this.trackId&&ys(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&wi(e,s,Mi))return s;const r=ii(e,this.tracksInGroup,Mi);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Id(e,t.levels,i,a,Mi);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=ii(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e,t=!0){const i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,r=i[e],a=r.details&&!r.details.live;if(e===this.trackId&&r===s&&a||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,Ae(Ae({},r),{},{flushImmediate:t})),a))return;const o=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||wi(e,s,Mi)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let u=0;u<t.length;u++){const h=t[u];if(wi({name:i,lang:s,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,Mi))return u}for(let u=0;u<t.length;u++){const h=t[u];if(Ps(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(let u=0;u<t.length;u++){const h=t[u];if(Ps(e.attrs,h.attrs,["LANGUAGE"]))return u}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&sr(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),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}}class rg{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;i==="async-blocker"||i==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):i==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;const a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
23
|
-
${this.list("video")}
|
|
24
|
-
${this.list("audio")}
|
|
25
|
-
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}}const Jl=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,eu="HlsJsTrackRemovedError",ng=.25,ag=.001;class og extends Error{constructor(e){super(e),this.name=eu}}class lg extends wt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:r}=this;i&&this.log("Media source opened"),!(!s||!r)&&(Ve(r,"sourceopen",this._onMediaSourceOpen),Ve(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:s,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const i=this.media.error,{appendError:s,appendErrors:r}=this;let a=!1;!s&&i&&(a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${iu(a,i)}`);this.warn(o),this.hls.trigger(E.ERROR,je({fatal:a},s,{type:me.MEDIA_ERROR,details:U.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{const{media:i}=this;if(i){var s,r;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(r=i.error)==null?void 0:r.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=uh(Ei(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===t?je(i,s.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(i[a]=je({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=Ei(this.appendSource);if(s){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),r)this._objectUrl=i.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,tu(i),ug(i,o),i.load()}catch{i.src=o}else i.src=o}Ke(i,"emptied",this._onMediaEmptied),Ke(i,"error",this._onMediaError),this.appendSource&&Ke(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),Ke(e,"sourceopen",this._onMediaSourceOpen),Ke(e,"sourceended",this._onMediaSourceEnded),Ke(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ke(e,"startstreaming",this._onStartStreaming),Ke(e,"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,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
26
|
-
required tracks: ${Xe(i,(l,u)=>l==="initSegment"?void 0:u)};
|
|
27
|
-
transfer tracks: ${Xe(s,(l,u)=>l==="initSegment"?void 0:u)}}`),!ja(s,i)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,u=this.details,h=Math.max(l,u?.fragments[0].start||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{const u=l,h=s[u];if(h){const d=h.buffer;if(d){const g=this.fragmentTracker,m=h.id;if(g.hasFragments(m)||g.hasParts(m)){const v=ve.getBuffered(d);g.detectEvictedFragments(u,v,m,null,null,!0)}const A=Mn(u),C=[u,d];this.sourceBuffers[A]=C,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(u),this.trackSourceBuffer(u,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let u=l.length;u--;)o&&l[u].abort(),r.removeSourceBuffer(l[u]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Ve(r,"sourceopen",this._onMediaSourceOpen),Ve(r,"sourceended",this._onMediaSourceEnded),Ve(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ve(r,"startstreaming",this._onStartStreaming),Ve(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(Ve(s,"emptied",this._onMediaEmptied),Ve(s,"error",this._onMediaError),Ve(s,"seeking",this._onStartStreaming),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&tu(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Mn(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new rg(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!s[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var u,h;const d=t[l],{id:g,codec:m,levelCodec:A,container:C,metadata:v,supplemental:x}=d;let R=s[l];const b=(u=this.transferData)==null||(u=u.tracks)==null?void 0:u[l],D=b!=null&&b.buffer?b:R,_=D?.pendingCodec||D?.codec,M=D?.levelCodec;R||(R=s[l]={buffer:void 0,listeners:[],codec:m,supplemental:x,container:C,levelCodec:A,metadata:v,id:g});const p=er(_,M),$=p?.replace(Jl,"$1");let N=er(m,A);const O=(h=N)==null?void 0:h.replace(Jl,"$1");N&&p&&$!==O&&(l.slice(0,5)==="audio"&&(N=Js(N,this.appendSource)),this.log(`switching codec ${_} to ${N}`),N!==(R.pendingCodec||R.codec)&&(R.pendingCodec=N),R.container=C,this.appendChangeType(l,C,N))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,ge.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>s||ve.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,ge.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:a,frag:o,part:l,chunkMeta:u,offset:h}=t,d=u.buffering[r],g=st(o)&&!l&&!o.gap&&!u.partial&&!u.iframe;let m=null,A=!1;const{sn:C,cc:v}=o,x=self.performance.now();d.start=x;const R=o.stats.buffering,b=l?l.stats.buffering:null;R.start===0&&(R.start=x),b?.start===0&&(b.start=x);const D=i.audio;let _=!1;r==="audio"&&D?.container==="audio/mpeg"&&(_=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const M=i.video,p=M?.buffer;if(p&&C!=="initSegment"&&h!==void 0){const O=D?.buffer,W=l||o;if(r==="audio"&&a!=="main"&&!(M.ending||M.ended)&&O&&ve.getBuffered(O).length){const z=W.start+W.duration*.05,oe=ve.getBuffered(p),re=this.currentOp("video");!oe.length&&!re?this.blockAudio(W):!ve.isBuffered(p,z)&&this.lastVideoAppendEnd<z&&this.blockAudio(W)}else if(r==="video"){const q=W.end,z=this.lastVideoAppendEnd-q;this.lastVideoAppendEnd=q,z<0||z>W.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const $=(l||o).start,N={label:`append-${r}`,execute:()=>{var O;d.executeStart=self.performance.now();const W=(O=this.tracks[r])==null?void 0:O.buffer;W&&(g&&(m=ve.timeRangesToArray(ve.getBuffered(W)),A=ru(On(m,o),o)),_?this.updateTimestampOffset(W,$,.1,r,C,v):h!==void 0&&se(h)&&this.updateTimestampOffset(W,h,1e-6,r,C,v)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const O=self.performance.now();d.executeEnd=d.end=O,R.first===0&&(R.first=O),b?.first===0&&(b.first=O);const W={};if(this.sourceBuffers.forEach(([q,z])=>{q&&(W[q]=ve.getBuffered(z))}),g){const q=this.getFragmentAppendProgress(o),z=W[r];if(z&&m){const oe=ve.timeRangesToArray(z),re=On(oe,o);q.progressed||(q.progressed=re-On(m,o)>ag);const J=A&&ru(re,o);q.fullyBuffered[r]=(q.fullyBuffered[r]===void 0||q.fullyBuffered[r])&&J}}this.hls.trigger(E.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:u,parent:a,timeRanges:W})},onError:O=>{var W;this.clearBufferAppendTimeoutId(this.tracks[r]);const q=O.code===DOMException.QUOTA_EXCEEDED_ERR||O.name=="QuotaExceededError"||"quota"in O;if(q&&!this._quotaEvictionPending[r]){const J=this.getBackBufferEvictionTarget(r,s.byteLength,o.type);if(J>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${C} - evicting back buffer to ${J.toFixed(3)}s and retrying`);const Z=this.getFlushOp(r,0,J),Q=this.getClearEvictionPendingOp(r);this.insertNext([Z,N,Q],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${C} - no back buffer available to evict`)}g&&(this.getFragmentAppendProgress(o).errored=!0);const z={type:me.MEDIA_ERROR,parent:a,details:U.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:u,error:O,err:O,fatal:!1},oe=(W=this.media)==null?void 0:W.error;if(O.name===eu&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))z.errorAction=vs(!0);else{var re;q&&(z.details=U.BUFFER_FULL_ERROR);const J=++this.appendErrors[r],Z=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${J}/${Z+1} times to append segment in "${r}" sourceBuffer with error: ${O.message}`),J>=Z&&(z.fatal=!q);const Q=(re=this.mediaSource)==null?void 0:re.readyState;(Q==="ended"||Q==="closed"||oe)&&(this.warn(`MediaSource readyState "${Q}" during SourceBuffer${iu(z.fatal,oe)}`),z.details=U.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=z,this.hls.trigger(E.ERROR,z),q&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${r}" append sn: ${C}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${v} offset: ${h} bytes: ${s.byteLength}`),this.append(N,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var s;const r=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${r?hr(ve.getBuffered(r)):"(detached)"}`),this.hls.trigger(E.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s),this.hls.trigger(E.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;(!i||i==="audio")&&this.unblockAudio(),i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,r),a)})}onFragParsed(e,t){const{frag:i,part:s,chunkMeta:r}=t,a=[],o=s?s.elementaryStreams:i.elementaryStreams;o[ze.AUDIOVIDEO]?a.push("audiovideo"):(o[ze.AUDIO]&&a.push("audio"),o[ze.VIDEO]&&a.push("video"));const l=()=>{const u=self.performance.now();i.stats.buffering.end=u,s&&(s.stats.buffering.end=u);const h=s?s.stats:i.stats;this.checkAppendProgress(i,s,r,a),this.hls&&(this.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:s,stats:h,id:i.type,chunkMeta:r}),!s&&i.gap&&h.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${h.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(l,a).catch(u=>{this.warn(`Fragment buffered callback ${u.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,s;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const{backBufferLength:a,frontBufferFlushThreshold:o}=r;this.trimBuffers(o,a,t.frag,t.previousFrag);const l=t.frag.elementaryStreams,{appendErrors:u}=this,h=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach(d=>{l[d]&&(u[d]=0,d===h&&(this.appendError=void 0),d==="audio"||d==="video"?(u.audiovideo=0,h==="audiovideo"&&(this.appendError=void 0)):(u.audio=0,u.video=0,h!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(a?.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===U.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;se(s)&&s!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){const{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,t):0}getFragmentAppendProgress(e){var t;const i=su(e);let s=this.fragmentAppendProgress[i];return((t=s)==null?void 0:t.stats)!==e.stats&&(s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(e,t,i,s){if(t||!st(e)||e.gap||i.iframe||i.partial)return;const r=su(e),a=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const o=e.stats.buffering;if(o.start&&!o.first)return;const l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;const u=s.length>0&&s.every(m=>l?.fullyBuffered[m]===!0);if(l!=null&&l.progressed||u){delete this.appendsWithoutProgress[r];return}if(!l&&s.length===0)return;const h=(this.appendsWithoutProgress[r]||0)+1,d=this.hls;h>=d.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=h,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${h} time${h>1?"s":""} without buffered range growth`),d.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:h,error:new Error(`Fragment append did not increase buffered coverage (${h})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,s){const{hls:r,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;const l=r.config,u=o.currentTime,h=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let d=-1/0;if(se(t)&&t>=0){const g=Math.max(t,h);d=Math.floor(u/h)*h-g}if(i){const g=this.getLoopBackBufferFlushEnd(i,s??null);g>0&&(d=Math.max(d,g))}if(d>0&&this.flushBackBuffer(u,h,d),se(e)&&e>0){const g=Math.max(l.maxBufferLength,e),m=Math.max(g,h),A=Math.floor(u/h)*h+m;this.flushFrontBuffer(u,h,A)}}getLoopBackBufferFlushEnd(e,t){var i;const{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;const{video:r,audiovideo:a}=e.elementaryStreams;if(r!=null&&r.partial||a!=null&&a.partial)return 0;const o=this.getEarliestElementaryStreamStart(e)-ng;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){const{audio:t,video:i,audiovideo:s}=e.elementaryStreams;let r=e.start;return s?r=Math.min(r,s.startDTS):(t&&(r=Math.min(r,t.startDTS)),i&&(r=Math.min(r,i.startDTS))),r}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const u=ve.getBuffered(r);if(u.length>0&&i>u.start(0)){var a,o,l;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:i});const h=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(h!=null&&h.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const a=ve.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),u=a.end(o-1);if(i>l||e>=l&&e<=u)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const u=Math.max(0,t.fragmentStart),h=Math.max(u,s);return{duration:1/0,start:u,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return se(r)?{duration:r}:null;const a=this.media.duration,o=se(i.duration)?i.duration:0;return s>o&&s>a||!se(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!s||!this.media||s.readyState!=="open"||(s.duration!==e&&(se(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Xe(i)}`),this.tracksReady){var s;const r=(s=this.transferData)==null?void 0:s.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.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 a=r,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),u=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${u})${this.currentOp(a)?" Queued":""} ${Xe(o)}`);try{const h=i.addSourceBuffer(u),d=Mn(a),g=[a,h];t[d]=g,o.buffer=h}catch(h){var s;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:u,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&As(i,"video")&&(s=ed(s,i));const r=er(s,e.levelCodec);return r?t.slice(0,5)==="audio"?Js(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",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&(this.log(`${r} buffer removed ${hr(o)}`),this.hls.trigger(E.BUFFER_FLUSHED,{type:r,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);if(!s)return;if(s.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;const s=(i=this.mediaSource)==null?void 0:i.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${r.message}`,t),this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const a=this.currentOp(e);a&&a.onError(r)}updateTimestampOffset(e,t,i,s,r,a){const o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,a=this.tracks[e],o=a?.buffer;if(!s||!r||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const l=se(s.duration)?s.duration:1/0,u=se(r.duration)?r.duration:1/0,h=Math.max(0,t);if(h>=u){var d;(d=this.currentOp(e))==null||d.onComplete(),this.shiftAndExecuteNext(e);return}const g=Math.min(i,l,u);if(g>h&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${h},${g}] from the ${e} SourceBuffer`),o.remove(h,g);else throw new Error(`Cannot remove ${g<=h?`invalid range (${h} >= ${g}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){const i=this.tracks[t],s=i?.buffer;if(!s)throw new og(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){const r=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,r),r)}s.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const s=this.currentOp(e);s&&s.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Xo;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(this.media===null)return i;const s=ve.bufferInfo(e,this.media.currentTime,0);return s.len?(i=Math.max(s.len*1e3,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(r).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const a=i.bind(this,e);s.listeners.push({event:t,listener:a}),Ke(r,t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{Ve(i,s.event,s.listener)}),t.listeners.length=0)}}function tu(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function ug(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function Mn(n){return n==="audio"?1:0}function iu(n,e){return`${n?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function su(n){return`${n.type}_${n.sn}_${n.level}`}function On(n,e){const{start:t,end:i}=e;let s=0;for(let r=0;r<n.length;r++){const a=n[r];if(a.start>=i)break;const o=Math.max(t,a.start),l=Math.min(i,a.end);l>o&&(s+=l-o)}return s}function ru(n,e){return e.duration-n<=.05}class Fn{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:e}=this;e&&(e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){const i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(se(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const e=this.hls.levels;if(e.length>1){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,r)=>this.isLevelAllowed(s)&&r<=e);return this.observer||(this.clientRect=null),Fn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(t=>{var i;const s=(i=t[0])==null?void 0:i.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){r=o;break}}return r}}var Lt=class Fa{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Fa?i:new Fa(i))),this.value=e,this.params=t}};const cg="Dict";function hg(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function dg(n,e,t,i){return new Error(`failed to ${n} "${hg(e)}" as ${t}`,{cause:i})}const nu="Bare Item",fg="Boolean",gg="Byte Sequence",pg="Decimal",mg="Integer";function Ag(n){return n<-999999999999999||999999999999999<n}const Ig="String",Cg=/[\x00-\x1f\x7f]+/;var au=class{constructor(n){this.description=n}};const yg="Token",vg="Key";function ai(n,e,t){return dg("serialize",n,e,t)}function Eg(n){if(typeof n!="boolean")throw ai(n,fg);return n?"?1":"?0"}function Tg(n){if(ArrayBuffer.isView(n)===!1)throw ai(n,gg);return`:${ch(n)}:`}function ou(n){if(Ag(n))throw ai(n,mg);return n.toString()}function Sg(n){return`@${ou(n.getTime()/1e3)}`}function xg(n){const e=za(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ai(n,pg);const t=e.toString();return t.includes(".")?t:`${t}.0`}function bg(n){if(Cg.test(n))throw ai(n,Ig);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Lg(n){return n.description||n.toString().slice(7,-1)}function lu(n){const e=Lg(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ai(e,yg);return e}function Nn(n){switch(typeof n){case"number":if(!se(n))throw ai(n,nu);return Number.isInteger(n)?ou(n):xg(n);case"string":return bg(n);case"symbol":return lu(n);case"boolean":return Eg(n);case"object":if(n instanceof Date)return Sg(n);if(n instanceof Uint8Array)return Tg(n);if(n instanceof au)return lu(n);default:throw ai(n,nu)}}function Bn(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw ai(n,vg);return n}function Un(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${Bn(e)}`:`;${Bn(e)}=${Nn(t)}`).join("")}function uu(n){return n instanceof Lt?`${Nn(n.value)}${Un(n.params)}`:Nn(n)}function Rg(n){return`(${n.value.map(uu).join(" ")})${Un(n.params)}`}function Dg(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw ai(n,cg);const t=n instanceof Map?n.entries():Object.entries(n),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,r])=>{r instanceof Lt||(r=new Lt(r));let a=Bn(s);return r.value===!0?a+=Un(r.params):(a+="=",Array.isArray(r.value)?a+=Rg(r):a+=uu(r)),a}).join(`,${i}`)}function cu(n,e){return Dg(n,e)}const Pg=["url"],_g=["version","eventTargets","sid","transmissionMode"],kg=["customData","headers"],hu=n=>n instanceof Lt?new Lt(Math.round(n.value),n.params):Math.round(n),$n=n=>Array.isArray(n)?n.map(hu):hu(n),Gn=(n,e)=>Array.isArray(n)?n.map(t=>Gn(t,e)):n instanceof Lt&&typeof n.value=="string"?new Lt(Gn(n.value,e),n.params):(e.baseUrl&&(n=gh(n,fh(e.baseUrl))),e.version===1?encodeURIComponent(n):n),du=n=>n instanceof Lt?new Lt(Math.round(n.value/100)*100,n.params):Math.round(n/100)*100,yr=n=>Array.isArray(n)?n.map(du):du(n),wg={br:$n,d:$n,bl:yr,dl:yr,mtp:yr,nor:(n,e)=>{let t=n;return e.version>=2&&(n instanceof Lt&&typeof n.value=="string"?t=new Lt([n]):typeof n=="string"&&(t=[n])),Gn(t,e)},rtp:yr,tb:$n},_s=2,fu="bc",Mg="ps",gu="pr",Og="e",pu="t",Fg="c",mu="b",Hn="rr",Au="ce",vr={BITRATE_CHANGE:fu,ERROR:Og,RESPONSE_RECEIVED:Hn,CUSTOM_EVENT:Au},Iu=new Map([[Mg,"sta"],[gu,"pr"],[Fg,"cid"],[mu,"bg"],[fu,"br"]]),Vn="event",Kn="request",Cu=["cen","e","h","ts"],yu=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Ng=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Yn(n){return Ng.test(n)}const Bg=new Set(yu);function vu(n){return Bg.has(n)||Yn(n)}const Eu=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ug=new Set(Eu);function Tu(n){return Ug.has(n)}const $g=new Set(Cu);function Gg(n){return vu(n)||Tu(n)||$g.has(n)}const Hg=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Er=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Vg=new Set(Er);function Kg(n){return Vg.has(n)||Yn(n)}const Yg=new Set(["ot","sf","st","e","sta"]);function Wg(n){return Yg.has(n)}function jg(n){return typeof n=="number"?se(n):n!=null&&n!==""&&n!==!1}const qg={[Vn]:Gg,[Kn]:vu};function Su(n,e){if(Array.isArray(n)){let t;return e&&(t=n.find(i=>{var s;return((s=i.params)==null?void 0:s.ot)===e})),t||(t=n[0]),Su(t)}return n instanceof Lt?n.value:n}function zg(n){const e={};for(const[i,s]of Object.entries(n)){if(s==null){e[i]=s;continue}if(i==="nor"){const r=(Array.isArray(s)?s:[s])[0];if(r instanceof Lt){var t;e.nor=r.value,(t=r.params)!=null&&t.r&&(e.nrr=r.params.r)}else e.nor=r}else Hg.has(i)?e[i]=Su(s,n.ot):e[i]=s}return e}function xu(n,e={}){const t={};if(n==null||typeof n!="object")return t;const i=e.version||n.v||_s,s=e.reportingMode||Kn,r=i===1?zg(n):n,a=i===1?Kg:qg[s];let o=Object.keys(r).filter(a);r.e&&r.e!==Hn&&(o=o.filter(m=>!Tu(m)));const l=e.filter;typeof l=="function"&&(o=o.filter(l));const u=s===Vn;if(u){const m=r.e;!o.includes("e")&&m!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&r.cen!=null&&m===Au&&o.push("cen");const A=m?Iu.get(m):void 0;A&&r[A]!=null&&!o.includes(A)&&o.push(A)}if(o.length===0)return t;i>1&&!o.includes("v")&&o.push("v");const h={version:i,reportingMode:s,baseUrl:e.baseUrl};o.sort();for(const m of o){var d,g;let A=r[m];const C=(d=(g=e.formatters)==null?void 0:g[m])!=null?d:wg[m];if(typeof C=="function"&&(A=C(A,h)),m==="v"){if(i===1)continue;A=i}if(m==="pr"&&A===1&&!(u&&r.e===gu))continue;u&&m==="ts"&&!se(A)&&(A=Date.now());const v=u&&A===!1&&m==="bg"&&r.e===mu;!jg(A)&&!v||(Wg(m)&&typeof A=="string"&&(A=new au(A)),t[m]=A)}return t}const Ai="CMCD-Object",Rt="CMCD-Request",Ji="CMCD-Session",Wt="CMCD-Status",Xg={REQUEST:Rt},Zg={ab:Ai,br:Ai,d:Ai,lab:Ai,lb:Ai,ot:Ai,tab:Ai,tb:Ai,tpb:Ai,bl:Rt,cs:Rt,dfa:Rt,dl:Rt,ltc:Rt,mtp:Rt,nor:Rt,nrr:Rt,pb:Rt,sn:Rt,sta:Rt,su:Rt,tbl:Rt,cid:Ji,msd:Ji,sf:Ji,sid:Ji,st:Ji,v:Ji,bg:Wt,bs:Wt,bsa:Wt,bsd:Wt,bsda:Wt,cdn:Wt,ec:Wt,nr:Wt,pr:Wt,pt:Wt,rtp:Wt};function Qg(n){return Object.keys(n).reduce((e,t)=>{var i;return(i=n[t])==null||i.forEach(s=>e[s]=t),e},{})}function Jg(n,e){const t={};if(!n)return t;const i=Object.keys(n),s=e?Qg(e):{};for(const a of i){var r;const o=Zg[a]||s[a]||Xg.REQUEST,l=(r=t[o])!=null?r:t[o]={};l[a]=n[a]}return t}function ep(n,e){const t={},i=Jg(n,e);for(const[s,r]of Object.entries(i)){const a=cu(r,{whitespace:!1});a&&(t[s]=a)}return t}const bu="CMCD";function Lu(n){return cu(n,{whitespace:!1})}function tp(n,e={}){return n?Lu(xu(n,e)):""}const ip=30,Wn=[...Er,...yu,...Eu,...Cu].filter((n,e,t)=>t.indexOf(n)===e),sp="application/cmcd",rp=1,mt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},jt={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},jn="query",Ru="headers";function Du(n,e,t){var i;const s=new Set((i=e.enabledKeys)!=null?i:[]);return{version:e.version||_s,reportingMode:n,filter:r=>s.has(r),baseUrl:t}}function np(n,e){if(n===e)return!0;if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++){const i=n[t],s=e[t];if(i===s)continue;if(typeof i=="number"||typeof s=="number"||i.value!==s.value)return!1;const r=i.params,a=s.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&r&&a&&r[o]!==a[l])return!1}return!0}const ap=Object.is,op=n=>n,Pu=Array.from(Iu,([n,e])=>e==="br"?{event:n,field:e,equal:(t,i)=>t===void 0||i===void 0?t===i:np(t,i),snapshot:t=>t.slice()}:{event:n,field:e,equal:ap,snapshot:op}),lp=new Map(Pu.map(n=>[n.event,n]));function up(n){const{url:e}=n,t=Vs(n,Pg);return fetch(e,t)}function cp(n){const{version:e=_s,eventTargets:t=[],sid:i=Xa(),transmissionMode:s=jn}=n,r=Vs(n,_g);return Ae(Ae({},r),{},{version:e,transmissionMode:s,sid:i,eventTargets:t.reduce((a,o)=>{var l,u,h;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||_s,enabledKeys:((u=o.enabledKeys)==null?void 0:u.slice())||[],url:o.url,events:o.events.slice(),interval:(h=o.interval)!=null?h:ip,batchSize:o.batchSize||1}),a},[])})}var hp=class{constructor(n,e=up){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=cp(n),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const i of this.config.eventTargets)this.eventTargets.set(i,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((n,e)=>{if(this.disarmInterval(n),e.interval===0||!e.events.includes(pu))return;const t=()=>{this.recordTargetEvent(n,e,pu),this.processEventTargets()};n.intervalId=setInterval(t,e.interval*1e3),t()})}stop(n=!1){n&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(n){n.sid&&n.sid!==this.data.sid&&this.resetSession(),n.msd&&!isNaN(n.msd)&&(this.msd=n.msd),this.data=Ae(Ae(Ae({},this.data),n),{},{msd:void 0});for(const e of Pu)e.field in n&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(n,e={}){const t=lp.get(n);if(t){const i=t.field,s=e[i];s!==void 0&&je(this.data,{[i]:s});const r=this.data[i];if(r===void 0||t.equal(r,this.lastEmitted[i]))return;je(this.lastEmitted,{[i]:t.snapshot(r)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,n,e)}),this.processEventTargets()}recordTargetEvent(n,e,t,i={}){var s;if(!e.events.includes(t))return;const r=Ae(Ae(Ae({},this.data),i),{},{e:t,ts:(s=i.ts)!=null?s:Date.now(),sn:n.sn++});!isNaN(this.msd)&&!n.msdSent&&(r.msd=this.msd,n.msdSent=!0),n.queue.push(r)}recordResponseReceived(n,e={}){var t,i,s;const{request:r}=n,a=(t=e.url)!=null?t:r?.url;if(!a)return;const o=new URL(a);o.searchParams.delete(bu);const l={url:o.toString(),rc:n.status},u=n.resourceTiming;u&&(u.startTime!=null&&(l.ts=Math.round(this.timeOrigin+u.startTime),u.responseStart!=null&&(l.ttfb=Math.round(u.responseStart-u.startTime))),u.duration!=null&&(l.ttlb=Math.round(u.duration)));const h=(i=(s=r.customData)==null?void 0:s.cmcd)!=null?i:{};this.recordEvent(Hn,Ae(Ae(Ae({},h),l),e))}applyRequestReport(n){var e;return(e=this.createRequestReport(n))!=null?e:n}isRequestReportingEnabled(){var n;return!!((n=this.config.enabledKeys)!=null&&n.length)}createRequestReport(n,e){var t;const{customData:i={},headers:s={}}=n,r=Vs(n,kg),a=Ae(Ae({},r),{},{headers:Ae({},s),customData:Ae(Ae({},i),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;const o=new URL(a.url),l=Ae(Ae(Ae({},this.data),e),{},{sn:this.requestTarget.sn++}),u=Du(Kn,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);const h=a.customData.cmcd=xu(l,u);switch(this.config.transmissionMode){case jn:const d=Lu(h);d&&(o.searchParams.set(bu,d),a.url=o.toString());break;case Ru:je(a.headers,ep(h,u.customHeaderMap));break}return a}processEventTargets(n=!1){let e=!1;this.eventTargets.forEach((t,i)=>{const{queue:s}=t;if(!s.length||s.length<i.batchSize&&!n)return;const r=n?s.length:i.batchSize,a=s.splice(0,r);this.sendEventReport(i,a).catch(()=>{t.queue.unshift(...a)}),e||(e=s.length>0)}),e&&this.processEventTargets()}async sendEventReport(n,e){const t=Du(Vn,n),{status:i}=await this.requester({url:n.url,method:"POST",headers:{"Content-Type":sp},body:e.map(s=>tp(s,t)).join(`
|
|
28
|
-
`)+`
|
|
29
|
-
`});if(i===410)this.disposeEventTarget(n);else if(i===429||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(n){clearInterval(n.intervalId),n.intervalId=void 0}disposeEventTarget(n){const e=this.eventTargets.get(n);e&&(this.disarmInterval(e),this.eventTargets.delete(n))}resetSession(){this.eventTargets.forEach(n=>n.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const dp={HLS:"h"},qn={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function fp(n,e){return new Lt(n,e)}new Set(Er),new Set(Wn);const gp=["includeKeys"];function _u(n){return Object.keys(n).every(Yn)}class pp{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(jt.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(jt.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(jt.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(jt.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(jt.SEEKING)},this.onSeeked=()=>{var s;this.initialized&&(s=this.media)!=null&&s.paused&&this.setPlayerState(jt.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=s=>{try{this.apply(s,{ot:mt.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const{frag:o,part:l}=s,u=this.hls.levels[o.level],h=this.getObjectType(o,u),d={d:(l||o).duration*1e3,ot:h};if(h===mt.VIDEO||h===mt.AUDIO||h===mt.MUXED||h==null&&(o.type==="main"||o.type==="audio")){var r;const m=u.bitrate/1e3;d.br=[m];const{cmcd:A}=this.config,C=(r=A?.rtpSafetyFactor)!=null?r:5;if(d.rtp=Math.round(m*C/100)*100,h===mt.MUXED||h==null&&o.type==="main"){const R=this.getTopBandwidth()/1e3;se(R)&&(d.tb=[R]);const b=this.getLowestBandwidth()/1e3;se(b)&&(d.lb=[b])}const v=this.getBufferLength(o);if(se(v)){var a;d.bl=[v];const R=((a=this.media)==null?void 0:a.playbackRate)||1;d.dl=Math.round(v/R/100)*100}this.playheadLevel&&(d.pb=[this.playheadLevel.bitrate/1e3]);const x=this.hls.maxAutoLevel;if(x>=0){const R=this.hls.levels[x];R&&(d.tpb=[R.bitrate/1e3])}}const g=l?this.getNextPart(l):this.getNextFrag(o);g!=null&&g.url&&g.url!==o.url&&(g.byteRange.length>0?d.nor=[fp(g.url,{r:`${g.byteRange[0]}-${g.byteRange[1]}`})]:d.nor=[g.url]),this.apply(s,d)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(s,r,a)=>{var o;const{cmcd:l}=this.config,u=l==null||(o=l.eventTargets)==null?void 0:o.some(h=>{var d;return(d=h.events)==null?void 0:d.includes(vr.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!u))try{this.reporter.recordResponseReceived({request:{url:s},status:r.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(h){this.hls.logger.warn("Could not record fragment response CMCD data.",h)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:i}=this.config;if(i==null)return;const s=i.version||rp;if(this.reporter=new hp({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:i.useHeaders===!0?Ru:jn,enabledKeys:(e=i.includeKeys)!=null?e:[...s>=_s?Wn:Er],eventTargets:((t=i.eventTargets)!=null?t:[]).map(r=>{let{includeKeys:a}=r,o=Vs(r,gp);return Ae(Ae({},o),{},{enabledKeys:a??Wn})})},i.loader),this.reporter.update({sf:dp.HLS,sta:this.playerState}),i.reporterCallback){const r=this.reporter,a={updateCustomData:o=>{_u(o)&&r.update(o)},recordCustomEvent:(o,l={})=>{_u(l)&&r.recordEvent(vr.CUSTOM_EVENT,Ae({cen:o},l))}};i.reporterCallback(a)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(E.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(E.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(E.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(E.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const i=this.media=t.media;this.setPlayerState(this.media.autoplay?jt.STARTING:jt.PRELOADING),Ke(i,"waiting",this.onWaiting),Ke(i,"play",this.onPlay),Ke(i,"playing",this.onPlaying),Ke(i,"pause",this.onPause),Ke(i,"seeking",this.onSeeking),Ke(i,"seeked",this.onSeeked),Ke(i,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(Ve(e,"waiting",this.onWaiting),Ve(e,"play",this.onPlay),Ve(e,"playing",this.onPlaying),Ve(e,"pause",this.onPause),Ve(e,"seeking",this.onSeeking),Ve(e,"seeked",this.onSeeked),Ve(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(jt.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(jt.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(jt.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(vr.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;const s={br:[t.bitrate/1e3]},r=(i=t.details)==null?void 0:i.fragments[0];r&&(s.ot=this.getObjectType(r,t)),this.reporter.recordEvent(vr.BITRATE_CHANGE,s)}onLevelSwitched(e,t){const i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?qn.LOW_LATENCY:qn.LIVE:qn.VOD}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(i=this.media)==null?void 0:i.playbackRate,st:this.getStreamType()});const s=t.ot===mt.INIT||t.ot===mt.VIDEO||t.ot===mt.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=s;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===i&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e,t){const{type:i}=e;if(i==="subtitle")return mt.TIMED_TEXT;if(e.sn==="initSegment")return mt.INIT;if(i==="audio")return mt.AUDIO;if(i==="main"){if(e.hasStreams){const s=e.elementaryStreams;if(s.audiovideo)return mt.MUXED;if(s.video)return mt.VIDEO;if(s.audio)return mt.AUDIO}if(t){const{audioCodec:s,videoCodec:r}=t;if(!this.hls.audioTracks.length){if(s&&r)return mt.MUXED;if(s)return mt.AUDIO}if(r)return mt.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),se(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;const i=e||t;return i?i.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const i=this.getEventBufferLength();se(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);const{onSuccess:u}=l;this.loader.load(a,o,Ae(Ae({},l),{},{onSuccess:(h,d,g,m)=>{u(h,d,g,m),i(a.url,h,d)}}))}}}}const mp=3e5;class Ap extends wt{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if(i?.action===gt.SendAlternateToPenaltyBox&&i.flags&dt.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:u}=t.context;o&&s?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&s&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==a,!i.resolved&&(t.details!==U.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${Xe(r)} penalized: ${Xe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>mp&&delete i[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,yl(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(t===ke.AUDIO_TRACK&&s[r].hasAudioGroup(e)||t===ke.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(e))return s[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const u=this.getLevelsForPathway(o).map(h=>{const d=new tt(h.attrs);d["PATHWAY-ID"]=a;const g=d.AUDIO&&`${d.AUDIO}_clone_${a}`,m=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;g&&(i[d.AUDIO]=g,d.AUDIO=g),m&&(s[d.SUBTITLES]=m,d.SUBTITLES=m);const A=wu(h.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),C=new Cs({attrs:d,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:A,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let v=1;v<h.audioGroups.length;v++)C.addGroupId("audio",`${h.audioGroups[v]}_clone_${a}`);if(h.subtitleGroups)for(let v=1;v<h.subtitleGroups.length;v++)C.addGroupId("text",`${h.subtitleGroups[v]}_clone_${a}`);return C});t.push(...u),ku(this.audioTracks,i,l,a),ku(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Ti(s,"_HLS_pathway",this.pathwayId),Ti(s,"_HLS_throughput",""+h)}const r={type:ke.STEERING_MANIFEST,responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},u={onSuccess:(h,d,g,m)=>{this.log(`Loaded steering manifest: "${s}"`);const A=h.data;if(A?.VERSION!==1){this.log(`Steering VERSION ${A.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=A.TTL;const{"RELOAD-URI":C,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":x}=A;if(C)try{this.uri=new self.URL(C,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${C}`);return}this.scheduleRefresh(this.uri||g.url),v&&this.clonePathways(v);const R={steeringManifest:A,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,R),x&&this.updatePathwayPriority(x)},onError:(h,d,g,m)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${d.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let A=this.timeToLoad*1e3;if(h.code===429){const C=this.loader;if(typeof C?.getResponseHeader=="function"){const v=C.getResponseHeader("Retry-After");v&&(A=parseFloat(v)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,A)},onTimeout:(h,d,g)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ku(n,e,t,i){n&&Object.keys(e).forEach(s=>{const r=n.filter(a=>a.groupId===s).map(a=>{const o=je({},a);return o.details=void 0,o.attrs=new tt(o.attrs),o.url=o.attrs.URI=wu(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});n.push(...r)})}function wu(n,e,t,i){if(e){const{[t]:o}=i;if(o){const l=o[e];if(l)return l}}const{HOST:s,PARAMS:r}=i,a=new self.URL(n);return s&&(a.hostname=s),r&&Object.keys(r).sort().forEach(o=>{o&&Ti(a,o,r[o])}),a.href}class Ip{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Sn,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();const e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class qt extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class es extends wt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=es.CDMCleanupPromise?[es.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:i,initData:s}=t,r=`"${t.type}" event: init data type: "${i}"`;if(this.log(r),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Es(this.config));const o=a.map(An).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o;const l=ur(a),u=this.activeLevelKeys();if(l===Je.FAIRPLAY&&i==="sinf")try{const A=Yt(new Uint8Array(s)),C=Qr(JSON.parse(A).sinf),v=uo(C);if(!v)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(v.subarray(8,24))}catch(A){this.warn(`${r} Failed to parse sinf: ${A}`);return}else if(l===Je.PLAYREADY)o=In(new Uint8Array(s));else if(l===Je.WIDEVINE){const A=po(s).filter(C=>C.systemId===el.WIDEVINE);if(A.length){var h;const C=A[0];o=(h=C.kids)!=null&&h.length?C.kids[0]:null}}let d;if(o){const A=ut(o);for(let C=0;C<u.length;C++){const v=u[C];if(v.keyId&&(or(o,v.keyId)||v.uri.replace(/-/g,"").indexOf(A)!==-1)){v.pssh||(v.scheme=i,v.pssh=new Uint8Array(s),v.keyId=o,gi.setKeyIdForUri(v.uri,o)),d=this.getSessionForKey(v,"encrypted-event-key-match");break}}}if(!d){if(u.length){var g,m;return(g=u[0]).scheme||(g.scheme=i),(m=u[0]).pssh||(m.pssh=new Uint8Array(s)),this.getSessionForKey(u[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${ut(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=u=>{const h=u.shift();this.getMediaKeysPromise(h,s,r).then(d=>a({keySystem:h,mediaKeys:d})).catch(d=>{u.length?l(u):d instanceof qt?o(d):o(new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return tl===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;const r=Ud(e,t,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Xe(r)}`),o=this.requestMediaKeySystemAccess(e,r);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(u=>{this.log(`Failed to obtain access to key-system "${e}": ${u}`)}),o.then(u=>{this.throwIfDestroyed(),this.log(`Access for key-system "${u.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=l.mediaKeys=u.createMediaKeys().then(g=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then(m=>m?this.setMediaKeysServerCertificate(g,e,m):g)));return d.catch(g=>{this.error(`Failed to create media-keys for "${e}"}: ${g}`)}),d})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,s){const{mediaKeySessions:r}=this,a=` key-session "${e}" keyId: ${ut(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let u=0;u<r.length;u++){const h=r[u];if(!h.initialized&&h.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),h}this.log(`Creating${a}`);const o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return r.push(l),l}resetMediaKeys(){var e;const t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ut(t.keyId||[])}
|
|
30
|
-
} (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>An(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{const i=An(t);if(!i)throw new Error(`Unable to find format for key-system "${t}"`);return i})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Es(this.config),i=e.map(ur).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const a=t[s];if(e.cc<=a.cc&&(!st(e)||!st(a)||e.sn<a.sn)||!i&&s==r-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);const l=ur(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const s=Es(this.config);if(s.length)return this.getKeySystemAccess(s)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const s=zn(e,t[i]);if(s)return s}}loadKey(e){const t=e.decryptdata,i=this.getKeyStatus(t);if(i==="internal-error"){const o=Mu(i,t);return o.data.frag=e,this.error(`${o.message} (${ut(t.keyId||[])})`),Promise.reject(o)}const s=e.type,r=this.activeKeys,a=r[s];a&&!t.matches(a.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(a),delete r[s]),r[s]||(r[s]=e);for(let o=this.mediaKeySessions.length;o--;){const l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[ut(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){const s=this.getSessionForKey(e,t);return s.catch(r=>this.handleError(r,i)),s.then(r=>e)}getSessionForKey(e,t){const i=this.findContextForKey(e);if(i!==void 0)return Promise.resolve(i);const s=e.uri,r=this.sessionSetupByUri[s];let a;r===void 0?a=this.resolveSessionForKey(e,t):a=r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[s]=a;const o=()=>{this.sessionSetupByUri[s]===a&&delete this.sessionSetupByUri[s]};return a.then(o,o),a}findContextForKey(e){const{mediaKeySessions:t}=this;for(let i=t.length;i--;){const s=t[i];if(zn(e,s))return s}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let r=this.mediaKeySessions.length;r--;){const a=this.mediaKeySessions[r];if(zn(e,a))return a;const o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,e,t))).then(r=>{this.throwIfDestroyed();const a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(r,e,a,o,t)})})}getUsableKeyPromise(e,t,i){const s=e.keyRequests[t.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${vp(t)} format: "${t.keyFormat}" URI: ${t.uri})`),s.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof qt){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${ut(i.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ur(e.keyFormat),i=t?[t]:Es(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=Es(this.config)),e.length===0)throw new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Xe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(i=>i.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}filterInitData(e,t,i,s,r){var a;const o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const u=o.call(this.hls,i,s,je({},e,{decryptdata:t,reason:r}),r);if(!u)throw new Error("Invalid response from configured generateRequest filter");t.scheme=u.initDataType?u.initDataType:"cenc";const h=u.initData?u.initData:null;return t.pssh=h?new Uint8Array(h):null,u}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(e,t,i,s,r){const a=this.getUsableKeyPromise(e,t,r);if(a)return a;const o=this.filterInitData(e,t,i,s,r);if(o&&(s=o.initData?o.initData:null,i=o.initDataType),s===null)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));const l=t.uri,u=new Ip;e.keyRequests[l]=u;const h=g=>{const m=e.mediaKeysSession;if(!m){const v=new Error("invalid state");u.errored=v;return}const{messageType:A,message:C}=g;u.status=A,this.log(`"${A}" message event for session "${m.sessionId}" message size: ${C.byteLength}`),A==="license-request"||A==="license-renewal"?this.renewLicense(e,t,C).catch(v=>{u.errored=v,u.hasListeners||this.handleError(v),this.removeSession(e)}):A==="license-release"?e.keySystem===Je.FAIRPLAY&&this.updateKeySession(e,t,mn("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${A}"`)};return u.onmessage=h,Ke(e.mediaKeysSession,"message",h),this.generateRequest(e,t,i,s,r,!1)}generateRequest(e,t,i,s,r,a){if(a){const m=this.filterInitData(e,t,i,s,r);m&&(s=m.initData?m.initData:s,i=m.initDataType)}const o=t.uri,l=e.keyRequests[o],u=ut(t.keyId||[]),h=m=>{let A;m.startsWith("usable")?l.resolve():m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?A=Mu(m,t):m==="expired"?A=new Error(`key expired (keyId: ${u})`):m==="released"?A=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${u})`),A&&(l.errored=A,l.hasListeners||this.handleError(A))},d=m=>{if(!e.mediaKeysSession){const _=new Error("invalid state");l.errored=_;return}const C=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(C).some(_=>C[_]!=="status-pending"))return;const x=this.activeLevelKeys();for(let _=0;_<x.length;_++){const M=ut(x[_].keyId||[]);if(C[M]==="expired"){var R;this.log(`Expired key ${Xe(C)} in key-session "${(R=e.mediaKeysSession)==null?void 0:R.sessionId}"`),this.renewKeySession(t,e).catch(p=>this.handleError(p));break}}let b=C[u];if(b)h(b);else{var D;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(D=e.keyStatusTimeouts)[u]||(D[u]=self.setTimeout(()=>{var M;if(!e.mediaKeysSession)return;const p=this.getKeyStatus(t);if(p&&p!=="status-pending"){var $;return this.log(`No status for keyId ${u} in key-session "${($=e.mediaKeysSession)==null?void 0:$.sessionId}". Using session key-status ${p} from other session.`),h(p)}this.log(`key status for ${u} in key-session "${(M=e.mediaKeysSession)==null?void 0:M.sessionId}" timed out after 1000ms`),b="internal-error",h(b)},1e3)),this.log(`No status for keyId ${u} (${Xe(C)}).`)}};l.onkeystatuseschange=d,Ke(e.mediaKeysSession,"keystatuseschange",d);const g=l.useable;return this.log(`Generating key-session request for "${r}" keyId: ${u} URI: ${o} (init data type: ${i} length: ${s.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,s).then(()=>{var m;l.status="generated",this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${u} URI: ${o}`)}).catch(m=>{throw this.log(`mediaKeysSession.generateRequest failed: ${m}`),new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:t,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>g).catch(m=>{var A;this.log(`mediaKeysSession.generateRequest failed: ${m}`);const C=(A=m.data)==null?void 0:A.details;return(C===U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||C===U.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(v=>e.keyStatuses[v]==="usable")?(this.handleError(m),e):this.removeSession(e).then(()=>{throw m})}).then(()=>e)}getKeyStatuses(e){const t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const l=r;r=s,s=l}const a="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===Je.PLAYREADY&&a.length===16){const l=ut(a);t[l]=s,Qo(a)}const o=ut(a);this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${i}"`),t[o]=s}),t}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),r=yp(e,t);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={type:ke.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},u=t.certLoadPolicy.default,h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(g,m,A,C)=>{a(g.data)},onError:(g,m,A,C)=>{o(new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:A,response:Ae({url:l.url,data:void 0},g)},`"${e}" certificate request failed (${r}). Status: ${g.code} (${g.text})`))},onTimeout:(g,m,A)=>{o(new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:A,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(g,m,A)=>{o(new Error("aborted"))}};s.load(l,h,d)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(a=>{r(new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(r=>{throw new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){const i=Yt(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 h;for(let d=0,g=r.length;d<g;d++){var a,o;h=r[d];const m=(a=h.querySelector("name"))==null?void 0:a.textContent,A=(o=h.querySelector("value"))==null?void 0:o.textContent;m&&A&&e.setRequestHeader(m,A)}}const l=s.querySelector("Challenge"),u=l?.textContent;if(!u)throw new Error("Cannot find <Challenge> in key message");return mn(atob(u))}setupLicenseXHR(e,t,i,s,r){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,Ae(Ae({},i),{},{decryptdata:s}),r))).catch(o=>{if(!i.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,Ae(Ae({},i),{},{decryptdata:s}),r)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,i){return new Promise((s,r)=>{const a=Cp(e.keySystem,this.config);if(!a)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const o=e.keyRequests[t.uri];if(!o)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);const l=this.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(u.readyState===4)if(u.status===200){o.requestErrors=[];let h=u.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const d=this.config.licenseResponseCallback;if(d)try{h=d.call(this.hls,u,a,Ae(Ae({},e),{},{decryptdata:t}))}catch(g){this.error(g)}s(h)}else{const h=l.errorRetry,d=h?h.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>d||u.status>=400&&u.status<500)r(new qt({type:me.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:a,data:void 0,code:u.status,text:u.statusText}},`License Request XHR failed (${a}). Status: ${u.status} (${u.statusText})`));else{const g=d-o.requestErrors.length;this.warn(`Retrying license request, ${g} attempts left`),this.requestLicense(e,t,i).then(s,r)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,this.setupLicenseXHR(u,a,e,t,i).then(({xhr:h,licenseChallenge:d})=>{e.keySystem==Je.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(h,d)),h.send(d)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Ke(i,"encrypted",this.onMediaEncrypted),Ke(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ve(e,"encrypted",this.onMediaEncrypted),Ve(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,gi.clearKeyUriToKeyIdMap();const r=s.length;es.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,r)=>(s.indexOf(r.keyFormat)===-1&&s.push(r.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{const l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:s}=e;s&&Object.keys(s).forEach(o=>self.clearTimeout(s[o]));const{drmSystemOptions:r}=this.config;return(Gd(r)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}es.CDMCleanupPromise=void 0;function Cp(n,e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?.[n];if(s)return s.licenseUrl;if(n===Je.WIDEVINE&&i)return i}function yp(n,e){const{drmSystems:t}=e,i=t?.[n];if(i)return i.serverCertificateUrl}function vp(n){if(n.keyFormat===pt.FAIRPLAY)return n.uri;if(n.keyId===null)throw new Error("keyId is null");return ut(n.keyId)}function zn(n,e){const t=n.keyId,i=e.mediaKeysSession;if(t&&i){const s=e.mediaKeysSession.keyStatuses;if(s.size)return s.has(t)?s.get(t):e.keyStatuses[ut(t)]}}function Mu(n,e){const t=n==="output-restricted",i=t?U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:U.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new qt({type:me.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}class Ep{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const r=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,u=this.hls;if(u.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let h=u.currentLevel;u.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=h)&&(h=h-1,u.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:u.currentLevel}),u.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var Xn=(function(){if(lr!=null&&lr.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const u=l.toLowerCase();return~o.indexOf(u)?u:!1}function i(o){return t(n,o)}function s(o){return t(e,o)}function r(o,...l){let u=1;for(;u<arguments.length;u++){const h=arguments[u];for(const d in h)o[d]=h[d]}return o}function a(o,l,u){const h=this,d={enumerable:!0};h.hasBeenReset=!1;let g="",m=!1,A=o,C=l,v=u,x=null,R="",b=!0,D="auto",_="start",M=50,p="middle",$=50,N="middle";Object.defineProperty(h,"id",r({},d,{get:function(){return g},set:function(O){g=""+O}})),Object.defineProperty(h,"pauseOnExit",r({},d,{get:function(){return m},set:function(O){m=!!O}})),Object.defineProperty(h,"startTime",r({},d,{get:function(){return A},set:function(O){if(typeof O!="number")throw new TypeError("Start time must be set to a number.");A=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},d,{get:function(){return C},set:function(O){if(typeof O!="number")throw new TypeError("End time must be set to a number.");C=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},d,{get:function(){return v},set:function(O){v=""+O,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},d,{get:function(){return x},set:function(O){x=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},d,{get:function(){return R},set:function(O){const W=i(O);if(W===!1)throw new SyntaxError("An invalid or illegal string was specified.");R=W,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},d,{get:function(){return b},set:function(O){b=!!O,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},d,{get:function(){return D},set:function(O){if(typeof O!="number"&&O!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");D=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},d,{get:function(){return _},set:function(O){const W=s(O);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");_=W,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},d,{get:function(){return M},set:function(O){if(O<0||O>100)throw new Error("Position must be between 0 and 100.");M=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},d,{get:function(){return p},set:function(O){const W=s(O);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");p=W,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},d,{get:function(){return $},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");$=O,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},d,{get:function(){return N},set:function(O){const W=s(O);if(!W)throw new SyntaxError("An invalid or illegal string was specified.");N=W,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Tp{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ou(n){function e(i,s,r,a){return(i|0)*3600+(s|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Sp{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 Fu(n,e,t,i){const s=i?n.split(i):[n];for(const r in s){if(typeof s[r]!="string")continue;const a=s[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Zn=new Xn(0,0,""),Tr=Zn.align==="middle"?"middle":"center";function xp(n,e,t){const i=n;function s(){const o=Ou(n);if(o===null)throw new Error("Malformed timestamp: "+i);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const u=new Sp;Fu(o,function(g,m){let A;switch(g){case"region":for(let C=t.length-1;C>=0;C--)if(t[C].id===m){u.set(g,t[C].region);break}break;case"vertical":u.alt(g,m,["rl","lr"]);break;case"line":A=m.split(","),u.integer(g,A[0]),u.percent(g,A[0])&&u.set("snapToLines",!1),u.alt(g,A[0],["auto"]),A.length===2&&u.alt("lineAlign",A[1],["start",Tr,"end"]);break;case"position":A=m.split(","),u.percent(g,A[0]),A.length===2&&u.alt("positionAlign",A[1],["start",Tr,"end","line-left","line-right","auto"]);break;case"size":u.percent(g,m);break;case"align":u.alt(g,m,["start",Tr,"end","left","right"]);break}},/:/,/\s/),l.region=u.get("region",null),l.vertical=u.get("vertical","");let h=u.get("line","auto");h==="auto"&&Zn.line===-1&&(h=-1),l.line=h,l.lineAlign=u.get("lineAlign","start"),l.snapToLines=u.get("snapToLines",!0),l.size=u.get("size",100),l.align=u.get("align",Tr);let d=u.get("position","auto");d==="auto"&&Zn.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);n=n.slice(3),a(),e.endTime=s(),a(),r(n,e)}function Nu(n){return n.replace(/<br(?: \/)?>/gi,`
|
|
31
|
-
`)}class bp{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Tp,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,a=0;for(r=Nu(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
32
|
-
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
33
|
-
`&&++a,t.buffer=r.slice(a),o}function s(r){Fu(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=i();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=i(),t.state){case"HEADER":/:/.test(r)?s(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Xn(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{xp(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
34
|
-
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
35
|
-
|
|
36
|
-
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}function ks(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const Lp=/\r\n|\n\r|\n|\r/g,Bu="Missing initPTS for VTT ",Rp=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(!se(t)||!se(i)||!se(s)||!se(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=3600*1e3*r,t};function Qn(n,e,t){return ks(n.toString())+ks(e.toString())+ks(t)}function Dp(n,e,t,i,s,r,a){const o=new bp,l=Mt(new Uint8Array(n)).trim().replace(Lp,`
|
|
37
|
-
`).split(`
|
|
38
|
-
`),u=[],h=e?Vf(e.baseTime,e.timescale):0;let d="00:00.000",g=0,m=0,A=!1,C,v=!0;o.oncue=function(x){const R=t[i];let b=t.ccOffset;const D=(g-h)/9e4;if(A){if(R!=null&&R.new&&(b=t.ccOffset=R.start),D){if(!e){C=new Error(Bu+"MPEGTS");return}b=D-t.presentationOffset}}else if(e)b=-e.baseTime/e.timescale;else{C=new Error(Bu+"without X-TIMESTAMP-MAP");return}const _=x.endTime-x.startTime,M=Ot((x.startTime+b-m)*9e4,s*9e4)/9e4;x.startTime=Math.max(M,0),x.endTime=Math.max(M+_,0);const p=x.text.trim();x.text=decodeURIComponent(encodeURIComponent(p)),x.id?i&&(x.id=`hlsjscc${i}_${x.id}`):x.id=Qn(x.startTime,x.endTime,p),x.endTime>0&&u.push(x)},o.onparsingerror=function(x){C=x},o.onflush=function(){if(C){a(C);return}r(u)},l.forEach(x=>{if(v)if(x.startsWith("X-TIMESTAMP-MAP=")){v=!1,A=!0,x.slice(16).split(",").forEach(R=>{R.startsWith("LOCAL:")?d=R.slice(6):R.startsWith("MPEGTS:")&&(g=parseInt(R.slice(7)))});try{m=Rp(d)/1e3}catch(R){C=R}return}else x===""&&(v=!1);o.parse(x+`
|
|
39
|
-
`)}),o.flush()}const Jn="stpp.ttml.im1t",Uu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,$u=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Pp={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gu(n,e,t,i){const s=xe(new Uint8Array(n),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=s.map(o=>Mt(o)),a=Hf(e.baseTime,1,e.timescale);try{r.forEach(o=>t(_p(o,a)))}catch(o){i(o)}}function _p(n,e){const s=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(r).reduce((d,g)=>(d[g]=s.getAttribute(`ttp:${g}`)||r[g],d),{});!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o=s.getAttribute("xml:space")!=="preserve",l=Hu(ea(s,"styling","style")),u=Hu(ea(s,"layout","region")),h=ea(s,"body","[begin]");return[].map.call(h,d=>{const g=Vu(d,o);if(!g||!d.hasAttribute("begin"))return null;const m=ia(d.getAttribute("begin"),a),A=ia(d.getAttribute("dur"),a);let C=ia(d.getAttribute("end"),a);if(m===null)throw Ku(d);if(C===null){if(A===null)throw Ku(d);C=m+A}const v=new Xn(m-e,C-e,g);v.id=Qn(v.startTime,v.endTime,v.text);const x=u[d.getAttribute("region")],R=l[d.getAttribute("style")],b=kp(x,R,l),{textAlign:D}=b;if(D){const _=Pp[D];_&&(v.lineAlign=_),v.align=D}return je(v,b),v}).filter(d=>d!==null)}function ea(n,e,t){const i=n.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Hu(n){return n.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Vu(n,e){return[].slice.call(n.childNodes).reduce((t,i,s)=>{var r;return i.nodeName==="br"&&s?t+`
|
|
40
|
-
`:(r=i.childNodes)!=null&&r.length?Vu(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function kp(n,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),r.reduce((o,l)=>{const u=ta(e,i,l)||ta(n,i,l)||ta(s,i,l);return u&&(o[l]=u),o},{})}function ta(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Ku(n){return new Error(`Could not parse ttml timestamp ${n}`)}function ia(n,e){if(!n)return null;let t=Ou(n);return t===null&&(Uu.test(n)?t=wp(n,e):$u.test(n)&&(t=Mp(n,e))),t}function wp(n,e){const t=Uu.exec(n),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Mp(n,e){const t=$u.exec(n),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i/1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}function sa(n,e,t,i="",s="disabled"){const r=n.ownerDocument.createElement("track");return r.kind=e,r.label=t,i&&(r.srclang=i),r.src="data:,WEBVTT",r.track.mode=s,n.appendChild(r),r}function Op(n){return n.forced&&Xh()?"forced":n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function ra(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Ge.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,n.addCue(s)}catch(s){Ge.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(n.mode=t)}function na(n,e,t,i){const s=n.mode;if(s==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=Np(n.cues,e,t);for(let a=0;a<r.length;a++)(!i||i(r[a]))&&n.removeCue(r[a])}s==="disabled"&&(n.mode=s)}function Fp(n,e){if(e<=n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let i=0,s=t,r;for(;i<=s;)if(r=Math.floor((s+i)/2),e<n[r].startTime)s=r-1;else if(e>n[r].startTime&&i<t)i=r+1;else return r;return n[i].startTime-e<e-n[s].startTime?i:s}function Np(n,e,t){const i=[],s=Fp(n,e);if(s>-1)for(let r=s,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}class Bp extends wn{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,i=!1;if(this.currentTrack){var s;const o=(s=this.currentTrack.trackNode)==null?void 0:s.track.mode;o==="showing"?(t=this.trackId,i=!0):o==="hidden"&&(t=this.trackId)}if(!i)for(let o=0;o<this.tracksInGroup.length;o++){var r;const l=(r=this.tracksInGroup[o].trackNode)==null?void 0:r.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(i=>{i.trackNode||(i.trackNode=sa(this.media,Op(i),i.name,i.lang))});const t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const i=t.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!s&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(r=>{const a=r.trackNode;a&&(a.track.mode="hidden",a.remove(),r.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i;const a=[];if(this.tracks.forEach(h=>{(h.textCodec===Jn?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(h.groupId)>-1?(h.id=a.length,a.push(h)):h.trackNode&&(h.trackNode.remove(),h.trackNode=void 0))}),a.length===this.tracksInGroup.length){let h=!1;for(let d=0;d<a.length;d++)if(a[d]!==this.tracksInGroup[d]){h=!0;break}if(!h)return}a.length&&this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=ii(o,a);if(h>-1)r=a[h];else{const d=ii(o,this.tracks);r=this.tracks[d]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,u),this.setSubtitleTrack(l),this.createTracksInGroup()}}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||wi(r,e)))return s}if(e){for(let s=0;s<t.length;s++){const r=t[s];if(Ps(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(Ps(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ke.SUBTITLE_TRACK&&t.context.id===this.trackId&&ys(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&wi(e,i))return i;const s=ii(e,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),r}else{if(i)return null;{const r=ii(e,t);if(r>-1)return t[r]}}}}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),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",s=t.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(e,t=!1){const i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!se(e)){this.warn(`Invalid subtitle track id: ${e}`);return}const s=this.currentTrack,r=i[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r){s&&this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!r.details&&!r.details.live;if(r===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:u,type:h,url:d}=r;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:u,type:h,url:d});const g=this.switchParams(r.url,s?.details,r.details);this.loadPlaylist(g)}}const Sr=2,Up=100;class $p extends Ko{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Up),this.mediaSource=t.mediaSource;const i=this.media=t.media;Ke(i,"playing",this.onMediaPlaying),Ke(i,"waiting",this.onMediaWaiting),Ke(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Ve(i,"playing",this.onMediaPlaying),Ve(i,"waiting",this.onMediaWaiting),Ve(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,s;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,u=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||l){l&&this.stallResolved(e);return}if(h){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!ve.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}const d=ve.bufferInfo(a,e,0),g=this.fragmentTracker;g&&this.hls&&ju(d,e,g,this.hls);const m=d.nextStart||0;if(o&&g&&this.hls){const M=Yu(this.hls.inFlightFragments,e),p=d.len>Sr,$=!m||M||m-e>Sr&&!g.getPartialFragment(e);if(p||$)return;this.moved=!1}const A=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(d.len>0)&&!m)return;const p=Math.max(m,d.start||0)-e,N=!!(A!=null&&A.live)?A.targetduration*2:Sr,O=ws(e,g);if(p>0&&(p<=N||O)){a.paused||this._trySkipBufferHole(O);return}}const C=r.detectStallWithCurrentTimeMs,v=self.performance.now(),x=this.waiting;let R=this.stalled;if(R===null)if(x>0&&v-x<C)R=this.stalled=x;else{this.stalled=v;return}const b=v-R;if(!o&&(b>=C||x&&this.moved)&&this.hls){var D;if(((D=this.mediaSource)==null?void 0:D.readyState)==="ended"&&!(A!=null&&A.live)&&Math.abs(e-(A?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return;if(a.currentTime!==e){const M=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${M} > ${e}`);return}}const _=ve.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(_,b,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const r=ve.bufferedInfo(ve.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=ve.timeRangesToArray(s),o=ve.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=ve.bufferedInfo(a,e,0).bufferedIndex,u=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-u<1&&e-u<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${h} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=1e-6;let g=ws(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const m=ve.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:g,buffer:m.len,bufferInfo:m})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;const u=(r=this.hls)==null?void 0:r.latestLevelDetails,h=ws(i,a);if((h||u!=null&&u.live&&i<u.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const d=e.buffered,g=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||g))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const r=i.getFragAtPos(t,ge.MAIN),a=i.getFragAtPos(s,ge.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Xe(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:i,hls:s}=this,r=s?.config;if(!i||!t||!r)return 0;const a=i.currentTime,o=ve.bufferInfo(i,a,0);ju(o,a,t,s);const l=a<o.start?o.start:o.nextStart;if(l){const h=o.len<=r.maxBufferHole,d=o.len>0&&o.len<1&&i.readyState<3,g=l-a;if(g>0&&(h||d)){if(g>r.maxBufferHole){let x=!1;if(a===0){const R=t.getAppendedFrag(0,ge.MAIN);R&&l<R.end&&(x=!0)}if(!x&&e){var u;if(!((u=s.loadLevelObj)!=null&&u.details)||Yu(s.inFlightFragments,l))return 0;let b=!1,D=e.end;for(;D<l;){const _=ws(D,t),M=_?_.duration:0;if(M>0)D+=M;else{b=!0;break}}if(b)return 0}}const{nudgeMaxRetry:m,skipBufferHolePadding:A}=r,C=++this.skipRetry>m,v=Math.max(l,a)+A;if(C||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${v}`),this.moved=!0,i.currentTime=v),!(e!=null&&e.gap)||C){const x=new Error(C?`Playhead still not moving after seeking over buffer hole from ${a} to ${v} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${v}`),R={type:me.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:C,error:x,reason:x.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?R.part=e:R.frag=e),s.trigger(E.ERROR,R)}return v}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=t?.config;if(!i||!r)return 0;const a=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const o=a+(s+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Yu(n,e){const t=Wu(n.main);if(t&&t.start<=e)return t;const i=Wu(n.audio);return i&&i.start<=e?i:null}function Wu(n){if(!n)return null;switch(n.state){case Y.IDLE:case Y.STOPPED:case Y.ENDED:case Y.ERROR:return null}return n.frag}function ws(n,e){return e.getAppendedFrag(n,ge.MAIN)||e.getPartialFragment(n)}function ju(n,e,t,i){const s=i.latestLevelDetails,r=ws(e,t);if(dr(i.config)&&!n.nextStart&&s&&r&&i.interstitialsManager){const a="type"in r?r:r.fragment,o=Fo(s,a.sn);o?.level===a.level&&Sl(o,i.interstitialsManager.playerQueue,e)&&(n.nextStart=o.start)}}const Gp=.25;function aa(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function oa(n,e,t,i,s){let r=new n(e,t,"");try{r.value=i,s&&(r.type=s)}catch{r=new n(e,t,Xe(s?Ae({type:s},i):i))}return r}const xr=(()=>{const n=aa();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Hp{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return sa(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=aa();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===Et.emsg&&!i||!s)continue;const u=Qa(r[o].data),h=r[o].pts;let d=h+r[o].duration;d>xr&&(d=xr),d-h<=0&&(d=h+Gp);for(let m=0;m<u.length;m++){const A=u[m];if(!Ja(A)){this.updateId3CueEnds(h,l);const C=oa(a,h,d,A,l);C&&this.id3Track.track.addCue(C)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.track.cues;if(s)for(let r=s.length;r--;){const a=s[r];a.type===t&&a.startTime<e&&a.endTime===xr&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let u;s==="audio"?u=h=>h.type===Et.audioId3&&l:s==="video"?u=h=>h.type===Et.emsg&&o:u=h=>h.type===Et.audioId3&&l||h.type===Et.emsg&&o,na(r.track,t,i,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=aa();if(i&&s&&!a){const{fragmentStart:C,fragmentEnd:v}=e;let x=this.assetCue;x?(x.startTime=C,x.endTime=v):o&&(x=this.assetCue=oa(o,C,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),x&&(x.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(x),x.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:u}=e,h=Object.keys(u);let d=this.dateRangeCuesAppended;if(l&&t){var g;if((g=l.track.cues)!=null&&g.length){const C=Object.keys(d).filter(v=>h.indexOf(v)===-1);for(let v=C.length;v--;){var m;const x=C[v],R=(m=d[x])==null?void 0:m.cues;delete d[x],R&&Object.keys(R).forEach(b=>{const D=R[b];if(D){D.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(D)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const A=e.fragments[e.fragments.length-1];if(!(h.length===0||!se(A?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let C=0;C<h.length;C++){const v=h[C],x=u[v],R=x.startTime,b=d[v],D=b?.cues||{};let _=b?.durationKnown||!1,M=xr;const{duration:p,endDate:$}=x;if($&&p!==null)M=R+p,_=!0;else if(x.endOnNext&&!_){const O=h.reduce((W,q)=>{if(q!==x.id){const z=u[q];if(z.class===x.class&&z.startDate>x.startDate&&(!W||x.startDate<W.startDate))return z}return W},null);O&&(M=O.startTime,_=!0)}const N=Object.keys(x.attr);for(let O=0;O<N.length;O++){const W=N[O];if(!Od(W))continue;const q=D[W];if(q)_&&!(b!=null&&b.durationKnown)?q.endTime=M:Math.abs(q.startTime-R)>.01&&(q.startTime=R,q.endTime=M);else if(o){let z=x.attr[W];Fd(W)&&(z=eo(z));const re=oa(o,R,M,{key:W,data:z},Et.dateRange);re&&(re.id=v,this.id3Track.track.addCue(re),D[W]=re,a&&(W==="X-ASSET-LIST"||W==="X-ASSET-URL")&&re.addEventListener("enter",this.onEventCueEnter))}}d[v]={cues:D,dateRange:x,durationKnown:_}}}}}function qu(){return self.SourceBuffer||self.WebKitSourceBuffer}function zu(){if(!Ei())return!1;const e=qu();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Vp(){if(!zu())return!1;const n=Ei();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Is(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Is(e,"audio"))))}function Kp(){var n;const e=qu();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}var oi={DISABLED:0,SWITCHING:1,SWITCHED:2};const Yp=100;class Xu extends En{constructor(e,t,i){super(e,t,i,"stream-controller",ge.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=oi.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,r=s?s.currentTime:null;if(r===null||!se(r)||(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(s,r,ge.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(Yp),this.level=-1,!this.startFragRequested){let r=s.startLevel;r===-1&&(s.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=s.firstAutoLevel),s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=Y.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Y.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Y.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=Y.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Y.IDLE;break}break}case Y.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Y.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const a=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const C={type:this.targetBufferType()};this.hls.trigger(E.BUFFER_EOS,C),this.state=Y.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const u=a.details;if(!u||this.state===Y.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=Y.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const g=this.backtrackFragment?this.backtrackFragment.start:o.end;let m=this.getNextFragment(g,u);if(this.couldBacktrack&&!this.fragPrevious&&m&&st(m)&&this.fragmentTracker.getState(m)!==et.OK){var A;const v=((A=this.backtrackFragment)!=null?A:m).sn-u.startSN,x=u.fragments[v-1];x&&m.cc===x.cc&&(m=x,this.fragmentTracker.removeFragment(x))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(m&&this.isLoopLoading(m,g)){if(!m.gap){const v=this.audioOnly&&!this.altAudio?ze.AUDIO:ze.VIDEO,x=(v===ze.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;x&&this.afterBufferFlushed(x,v)}m=this.getNextFragmentLoopLoading(m,u,o,ge.MAIN,d)}m&&(this.exceedsMaxBuffer(o,d,m)||this.loadFragment(m,a,g))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===et.NOT_LOADED||s===et.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==oi.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===oi.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const i=this.fragPlaying;if(i){const s=i.level;this.hls.trigger(E.FRAG_CHANGED,{frag:i,previousFrag:e}),e?.level!==s&&this.hls.trigger(E.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===oi.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Ke(i,"playing",this.onMediaPlaying),Ke(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(Ve(i,"playing",this.onMediaPlaying),Ve(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=oi.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!Kp(),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!==Y.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=Y.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const u=t.levelInfo,h=this.fragCurrent;h&&(this.state===Y.FRAG_LOADING||this.state===Y.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=u.details)!=null&&i.live){var g;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,(g=this.levelLastLoaded)==null?void 0:g.details)}if(u.details=o,this.levelLastLoaded=u,r||this.setStartPosition(o,d),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===Y.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Y.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((m,A)=>{if(A>=o.startCC)return!0;delete this.initPTS[A]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.playhead,a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(s!==null&&i.duration>s&&(r<s||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var u;const d=ve.bufferInfo(i,s,0);if(!((u=d.buffered)!=null&&u.length)){i.currentTime=s;return}if(d.start<=r){i.currentTime=s;return}const{nextStart:m}=ve.bufferedInfo(d.buffered,r,0);m&&(i.currentTime=m)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const u=o.videoCodec,h=l.PTSKnown||!l.live,d=(t=i.initSegment)==null?void 0:t.data,g=this._getAudioCodec(o),m=this.transmuxer=this.transmuxer||new Xl(this.hls,ge.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),A=s?s.index:-1,C=A!==-1,{decryptRange:v,byteRange:x}=nr(i,s,this.iframesOnly),R=new dn(i.level,i.sn,i.stats.chunkCount,x?x.end-x.start:r.byteLength,A,C,i.duration,this.iframesOnly,v),b=this.initPTS[i.cc];m.push(r,d,g,u,i,s,l.totalduration,h,R,b)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==oi.DISABLED;if(sr(t.url,i))this.altAudio=oi.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=oi.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),i.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=sr(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?oi.SWITCHED:oi.DISABLED,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,s=l,o==="video"){const u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&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===ge.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Y.PARSED&&(this.state=Y.IDLE);return}let l=!1;if(st(i)&&(l=!!i.gap&&!i.tagList.some(u=>u[0]==="GAP")),this.fragBufferedComplete(i,s),l){var a;i.stats.retry++;const u=(a=this.levels)==null?void 0:a[i.level];u&&u.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&ve.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=Y.ERROR;return}switch(t.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ge.MAIN,t);break;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Y.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ke.LEVEL&&(this.state=Y.IDLE);break;case U.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Y.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ze.AUDIO||!this.altAudio){const i=(t===ze.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),a=ve.getBuffered(e),o=a.length?a.start(0):0,l=o-i,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<u||this.loadingParts&&l<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=Y.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:u}=a,{video:h,text:d,id3:g,initSegment:m}=s,{details:A}=u,C=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Y.PARSING,m){const v=m.tracks;if(v){const D=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(u,v,D,r),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:D,id:t,tracks:v})}const x=m.initPTS,R=m.timescale,b=this.initPTS[o.cc];if(se(x)&&(!b||b.baseTime!==x||b.timescale!==R)){const D=m.trackId;this.initPTS[o.cc]={baseTime:x,timescale:R,trackId:D};const _=this.initPTS.slice(0);i.trigger(E.INIT_PTS_FOUND,{timestampOffsets:_,frag:o,id:t,initPTS:x,timescale:R,trackId:D})}}if(h&&A){C&&h.type==="audiovideo"&&this.logMuxedErr(o);const v=A.fragments[o.sn-1-A.startSN],x=o.sn===A.startSN,R=!v||o.cc>v.cc;if(s.independent!==!1){const{startPTS:b,endPTS:D,startDTS:_,endDTS:M}=h;if(l)l.elementaryStreams[h.type]={startPTS:b,endPTS:D,startDTS:_,endDTS:M};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!R&&(this.couldBacktrack=!0),h.dropped&&h.independent){const p=this.getMainFwdBufferInfo(),$=(p?p.end:this.getLoadPosition())+this.config.maxBufferHole,N=h.firstKeyFramePTS?h.firstKeyFramePTS:b;if(!x&&$<N-this.config.maxBufferHole&&!R){this.backtrack(o);return}else R&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,D,o.start,M,!0)}else x&&b-(A.appliedTimelineOffset||0)>Sr&&(o.gap=!0);o.setElementaryStreamInfo(h.type,b,D,_,M),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,x||R)}else if(x||R)o.gap=!0;else{this.backtrack(o);return}}if(C){const{startPTS:v,endPTS:x,startDTS:R,endDTS:b}=C;l&&(l.elementaryStreams[ze.AUDIO]={startPTS:v,endPTS:x,startDTS:R,endDTS:b}),o.setElementaryStreamInfo(ze.AUDIO,v,x,R,b),this.bufferFragmentData(C,o,l,r)}if(A&&g!=null&&g.samples.length){const v={id:t,frag:o,details:A,samples:g.samples};i.trigger(E.FRAG_PARSING_METADATA,v)}if(A&&d){const v={id:t,frag:o,details:A,samples:d.samples};i.trigger(E.FRAG_PARSING_USERDATA,v)}}logMuxedErr(e){this.warn(`${st(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==Y.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:a,audiovideo:o}=t;if(r){const u=e.audioCodec;let h=er(r.codec,u);if(h==="mp4a"&&(h="mp4a.40.5"),this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&!zh()&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&Zh()&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),u&&u!==h&&this.log(`Swapping manifest audio codec "${u}" for "${h}"`),r.levelCodec=h,r.id=ge.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${u||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=ge.MAIN;const u=a.codec;if(u?.length===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;l.forEach(u=>{const d=t[u].initSegment;d!=null&&d.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:u,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,ge.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Y.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return se(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(se(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?qi(null,i.fragments,t):null);if(s){const r=s.programDateTime;if(r!==null){const a=r+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Zu extends Xu{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:i}=t,s=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=e,this.state){case Y.STOPPED:case Y.ENDED:case Y.ERROR:this.state=Y.IDLE}this.state===Y.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,t]):this.nextOp=[s,t],this.hls.off(E.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;i&&r&&this.seekTo(s)&&(this.currentOp=[s,t],this.nextOp=void 0,this.flushPipeline(s,!0))}seekTo(e){const t=this.media;if(t){var i;const s=(i=this.getLevelDetails())==null?void 0:i.edge,r=s!==void 0?s:t.duration;if(e>=r&&(e=r-.01),ve.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,ge.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;const s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){const r=i.shift();if(r.data)this.cachedSize-=r.data.byteLength,r.data=void 0;else{this.cached=i.filter(a=>!!a.data),this.cachedSize=i.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:i,payload:s}=e;this.cacheFragmentData&&!i&&s!=null&&s.byteLength&&!t.data&&st(t)&&this.cacheSet(t,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if((s===et.NOT_LOADED||s===et.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;const i=e.decryptdata;return i?.keyFormat!=="identity"||!!i.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const i=e.stats=new Vr;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=Y.FRAG_LOADING;const s={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(E.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=Y.STOPPED,i!=null&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?hr(ve.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(e,t){if(t){const i=this.media;if(i){const s=ve.bufferInfo(i,e,0),r=s.len?s.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,ge.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(E.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(E.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){const s=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||s||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,ge.MAIN);return!!(t!=null&&t.endList)}}class Wp extends Zu{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const i=(t=this._img)==null?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Y.STOPPED:case Y.ENDED:case Y.ERROR:this.state=Y.IDLE}if(this.state===Y.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Y.IDLE){const i=this.getBufferedAt(e);i&&(this.fragCurrent=i,this.updateImage(i,null))}}else{const i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){const s=e.data;s||this.fragmentTracker.removeFragment(e);const r=this._img;if(r&&s){const a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,r.onload=()=>{if(!this.hls)return;const h=this.hls.levels[e.level];h!=null&&h.fragmentError&&(h.fragmentError=0,e.stats.retry=0);const d=self.performance.now(),g=t?t.stats:e.stats;g.buffering.end=e.stats.buffering.end=d,this.hls.trigger(E.FRAG_BUFFERED,{frag:e,part:t,stats:g,id:e.type,chunkMeta:i})},r.onerror=()=>{this.handleError("Image decode error",e,t,i)};const l=r.src;l&&self.URL.revokeObjectURL(l);const u=new Blob([s],{type:"image/jpeg"});r.src=self.URL.createObjectURL(u)}else this.state=Y.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,s){if(!this.hls)return;const r=new Error(e);this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:s,frag:t,part:i,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,i,s){super.bufferFragmentData(e,t,i,s,!0);const r=xe(new Uint8Array(e.data1),["mdat"]);if(r.length===0){this.handleError("Could not find I-Frame mdat",t,i,s);return}const a=t;this.cacheSet(a,r[0]),this.updateImage(a,i,s)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){const i=this.getAppendedFrag(t);if(i&&!cs(i,this.fragPlaying))return this.fragPlaying=i,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const jp=10,qp="Image I-Frame player does not accept HTMLMediaElements",Qu={seekOnAppend:!0};let br,la;class zp extends wt{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,br||(br=Xp(t)),la||(la=Zp(br)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MANIFEST_LOADING,this.clearAsset,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.clearAsset,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;const s=(i=this.hls)==null?void 0:i.pathwayPriority;t.length&&s&&this.iframeInstances.forEach(r=>{r.pathwayPriority=s})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===ge.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;const s=this.hls;s&&s.hasEnoughToStart&&(((i=s.mainForwardBufferInfo)==null?void 0:i.len)||0)>jp&&this.iframeInstances.forEach(r=>{if(!r.loadingEnabled){var a;r.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(br,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const i=(t=this.hls)==null?void 0:t.iframeVariants.filter(s=>s.imageCodec);return this.createInstance(la,i,e,"image-")}createInstance(e,t,i,s){const{hls:r}=this;if(!r)return null;const{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:u,loadLevel:h,bandwidthEstimate:d,sessionId:g}=r,{stats:m,variableList:A}=this;if(!(t!=null&&t.length)||!m||!a)return null;const C=`${s||""}iframe-player-${this.instanceCounter++}`,v=r.levels,x=u||v[h],R=ko(x,o.videoPreference),b=x?.pathwayId||".",D=Ae(Ae({},o),{},{loggerId:C,primarySessionId:g,videoPreference:R,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),_=new e(D,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(M=>!M.url),this.iframeInstances.push(_),_.trigger(E.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:b},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:m,networkDetails:null,url:a,variableList:A}),_}}function Xp(n){return class extends n{constructor(t,i,s,r){t.streamController||(t.streamController=Zu),super(t),this._url=i,this.streamController.setInitPts(s),this.streamController.initDetails=r}loadSource(){}loadMediaAt(t,i=Qu){if(t<0)return;const s=Ae(Ae({},Qu),i);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}}function Zp(n){return class extends n{constructor(t,i,s,r){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=Wp),t.capLevelController=void 0,t.bufferController=void 0,super(t,i,s,r)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(qp)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}const bi=.025;let Lr=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function Qp(n,e,t){return`${n.identifier}-${t+1}-${ks(e)}`}class Jp{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Ju(t,e)?Rr(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,i=Rr(t,e);return t-i<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=se(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 Ju(t,e)?Rr(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<bi))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Lr.Range:Lr.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return em(this)}}function Rr(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<bi)?e.start:e.start+e.duration}function Ju(n,e){return e>n.start-bi&&e<n.start+n.duration+bi}function ec(n,e,t){const i=new self.URL(n,t);return i.protocol!=="data:"&&Ti(i,"_HLS_primary_id",e),i}function ua(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function em(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function ts(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class tm{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const 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,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(E.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=ec(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if((i=this.hls)!=null&&i.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),a=ve.bufferInfo(e,r,.02);return this.getAssetTime(a.end)>=s-.02}reachedPlayout(e){const i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=ve.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ts(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ca=.033;class im extends wt{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=s[i])!=null&&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];t&&t!=="primary"&&(r=r[t]);const a=r.start,o=i[s].event,l=o!=null&&o.cue.pre?o.duration:r.end;if(e===a||e>a&&e<l)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const r=i[s].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let r=0;r<s;r++){const a=i[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===s-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,i=0){const s=e.main.details,{dateRanges:r}=s,a=this.events,o=this.parseDateRanges(r,{url:s.url},t),l=Object.keys(r),u=a?a.filter(h=>l.indexOf(h.identifier)===-1):[];o.length&&o.sort((h,d)=>{const g=h.cue.pre,m=h.cue.post,A=d.cue.pre,C=d.cue.post;if(g&&!A)return-1;if(A&&!g||m&&!C)return 1;if(C&&!m)return-1;if(!g&&!A&&!m&&!C){const v=h.startTime,x=d.startTime;if(v!==x)return v-x}return h.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=o,u.forEach(h=>{this.removeEvent(h)}),this.updateSchedule(e,u,i)}updateSchedule(e,t=[],i=0,s=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const a=this.items,o=this.parseSchedule(r,e,i);(s||t.length||a?.length!==o.length||o.some((u,h)=>Math.abs(u.playout.start-a[h].playout.start)>.005||Math.abs(u.playout.end-a[h].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],l=e[o];if(l.isInterstitial){let u=this.eventMap[o];u?u.setDateRange(l):(u=new Jp(l,t),this.eventMap[o]=u,i===!1&&(u.appendInPlace=i)),s.push(u)}}return s}parseSchedule(e,t,i=0){const s=[],r=t.main.details,a=r.live?1/0:r.edge;let o=0;if(e=e.filter(u=>!u.error&&!(u.cue.once&&u.hasPlayed)),e.length){this.resolveOffsets(e,t);let u=0,h=0;if(e.forEach((d,g)=>{const m=d.cue.pre,A=d.cue.post,C=e[g-1]||null,v=d.appendInPlace,x=A?a:d.startOffset,R=d.duration,b=d.timelineOccupancy===Lr.Range?R:0,D=m&&r.live?i+(d.resumeOffset||0):0,_=D||d.resumptionOffset,M=C?.startTime===x,p=x+d.cumulativeDuration;let $=v?p+R:x+_;if(m||!A&&x<=0){const O=h;h+=b,d.timelineStart=p;const W=o;o+=R,s.push({event:d,start:p,end:$,playout:{start:W,end:o},integrated:{start:O,end:h}})}else if(x<=a){if(!M){const q=x-u;if(q>ca){const z=u,oe=h;h+=q;const re=o;o+=q;const J={previousEvent:e[g-1]||null,nextEvent:d,start:z,end:z+q,playout:{start:re,end:o},integrated:{start:oe,end:h}};s.push(J)}else q>0&&C&&(C.cumulativeDuration+=q,s[s.length-1].end=x)}A&&($=p),d.timelineStart=p;const O=h;h+=b;const W=o;o+=R,s.push({event:d,start:p,end:$,playout:{start:W,end:o},integrated:{start:O,end:h}})}else return;const N=D||d.resumeTime;A||N>a?u=a:!m&&$&&d.appendInPlaceStarted&&N-$>ca?u=$:u=N}),u<a){var l;const d=u,g=h,m=a-u;h+=m;const A=o;o+=m,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:u,end:d+m,playout:{start:A,end:o},integrated:{start:g,end:h}})}this.setDurations(a,o,h)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let r=0,a=-1;e.forEach((o,l)=>{const u=o.cue.pre,h=o.cue.post,d=u?0:h?s:o.startTime;this.updateAssetDurations(o),a===d?o.cumulativeDuration=r:(r=0,a=d),!h&&o.snapOptions.in&&(o.resumeAnchor=qi(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<ca&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const m=se(o.resumeOffset)?o.resumeOffset:o.duration;r+=m})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>bi?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;const u=qi(null,o.fragments,i);if(!u)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(u.start-i)<bi+h||Math.abs(u.end-i)<bi+h?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${u.start}-${u.end} sn: ${u.sn} cc: ${u.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,s||(s=o.duration===null),r||(r=!!o.error);const u=o.error?0:o.duration||0;i+=u}s&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ft(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class sm{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=ec(i,this.hls.sessionId,e.baseUrl)}catch(g){const m=this.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,g,i);this.hls.trigger(E.ERROR,m);return}t&&s.protocol!=="data:"&&Ti(s,"_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),l={type:ke.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},u=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(g,m,A,C)=>{const v=g.data,x=v?.ASSETS;if(!Array.isArray(x)){const R=this.assignAssetListError(e,U.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),A.url,m,C);this.hls.trigger(E.ERROR,R);return}e.assetListResponse=v,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:v,networkDetails:C})},onError:(g,m,A,C)=>{const v=this.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${g.code} ${g.text} (${m.url})`),m.url,C,A);this.hls.trigger(E.ERROR,v)},onTimeout:(g,m,A)=>{const C=this.assignAssetListError(e,U.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${m.url})`),m.url,g,A);this.hls.trigger(E.ERROR,C)}};return o.load(l,h,d),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,r,a){return e.error=i,{type:me.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:r}}}function tc(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function Fi(n,e){return`[${n}] Advancing timeline position to ${e}`}class rm extends wt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const a=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;const m=this.findItemIndex(o);let A=this.schedule.findItemIndexAtTime(i);if(A===-1&&(A=m+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${m} to ${A})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&A>m){const C=this.schedule.findJumpRestrictedIndex(m+1,A);if(C>m){this.setSchedulePosition(C);return}}this.setSchedulePosition(A);return}const u=this.playingAsset;if(!u){if(this.playingLastItem&&this.isInterstitial(o)){const m=o.event.assetList[0];m&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,m))}return}const h=u.timelineStart,d=u.duration||0;if(a&&i<h||i>=h+d){var g;(g=o.event)!=null&&g.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,u)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,s)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],u=r.durations,h=i.map(C=>C.identifier),d=!!(o.length||h.length);(d||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
41
|
-
Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let g=null,m=null;a&&(g=this.updateItem(a,this.timelinePos),this.itemsMatch(a,g)?this.playingItem=g:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const A=this.bufferingItem;if(A&&(m=this.updateItem(A,this.bufferedPos),this.itemsMatch(A,m)?this.bufferingItem=m:A.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(A.event,null))),i.forEach(C=>{C.assetList.forEach(v=>{this.clearAssetPlayer(v.identifier,null)})}),this.playerQueue.forEach(C=>{if(C.interstitial.appendInPlace){const v=C.assetItem.timelineStart,x=C.timelineOffset-v;if(x)try{C.timelineOffset=v}catch(R){Math.abs(x)>bi&&this.warn(`${R} ("${C.assetId}" ${C.timelineOffset}->${v})`)}}}),d||s){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:u,removedIds:h}),this.isInterstitial(a)&&h.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(g,a),A&&m!==g&&this.trimInPlace(m,A),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new sm(e),this.schedule=new im(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ve(e,"play",this.onPlay),Ve(e,"pause",this.onPause),Ve(e,"seeking",this.onSeeking),Ve(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Ke(i,"seeking",this.onSeeking),Ke(i,"timeupdate",this.onTimeupdate),Ke(i,"play",this.onPlay),Ke(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=d=>d&&e.getAssetPlayer(d.identifier),s=(d,g,m,A,C)=>{if(d){let v=d[g].start;const x=d.event;if(x){if(g==="playout"||x.timelineOccupancy!==Lr.Point){const R=i(m);R?.interstitial===x&&(v+=R.assetItem.startOffset+R[C])}}else{const R=A==="bufferedPos"?a():e[A];v+=R-d.start}return v}return 0},r=(d,g)=>{var m;if(d!==0&&g!=="primary"&&(m=e.schedule)!=null&&m.length){var A;const C=e.schedule.findItemIndexAtTime(d),v=(A=e.schedule.items)==null?void 0:A[C];if(v){const x=v[g].start-v.start;return d+x}}return d},a=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var g,m;return(g=e.primaryDetails)!=null&&g.live?e.primaryDetails.edge:((m=e.schedule)==null?void 0:m.durations[d])||0},l=(d,g)=>{var m,A;const C=e.effectivePlayingItem;if(C!=null&&(m=C.event)!=null&&m.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${g}"`);const v=e.effectivePlayingItem,x=e.schedule.findItemIndexAtTime(d,g),R=(A=e.schedule.items)==null?void 0:A[x],b=e.getBufferingPlayer(),D=b?.interstitial,_=D?.appendInPlace,M=v&&e.itemsMatch(v,R);if(v&&(_||M)){const p=i(e.playingAsset),$=p?.media||e.primaryMedia;if($){const N=g==="primary"?$.currentTime:s(v,g,e.playingAsset,"timelinePos","currentTime"),O=d-N,W=(_?N:$.currentTime)+O;if(W>=0&&(!p||_||W<=p.duration)){$.currentTime=W;return}}}if(R){let p=d;if(g!=="primary"){const N=R[g].start,O=d-N;p=R.start+O}const $=!e.isInterstitial(R);if((!e.isInterstitial(v)||v.event.appendInPlace)&&($||R.event.appendInPlace)){const N=e.media||(_?b?.media:null);N&&(N.currentTime=p)}else if(v){const N=e.findItemIndex(v);if(x>N){const W=e.schedule.findJumpRestrictedIndex(N+1,x);if(W>N){e.setSchedulePosition(W);return}}let O=0;if($)e.timelinePos=p,e.checkBuffer();else{const W=R.event.assetList,q=d-(R[g]||R).start;for(let z=W.length;z--;){const oe=W[z];if(oe.duration&&q>=oe.startOffset&&q<oe.startOffset+oe.duration){O=z;break}}}e.setSchedulePosition(x,O)}}},u=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const g=t();return e.isInterstitial(g)?g:null},h={get bufferedEnd(){const d=t(),g=e.bufferingItem;if(g&&g===d){var m;return s(g,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-g.playout.start||((m=e.bufferingAsset)==null?void 0:m.startOffset)||0}return 0},get currentTime(){const d=u(),g=e.effectivePlayingItem;return g&&g===d?s(g,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-g.playout.start:0},set currentTime(d){const g=u(),m=e.effectivePlayingItem;m&&m===g&&l(d+m.playout.start,"playout")},get duration(){const d=u();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const g=(d=u())==null?void 0:d.event.assetList;return g?g.map(m=>e.getAssetPlayer(m.identifier)):[]},get playingIndex(){var d;const g=(d=u())==null?void 0:d.event;return g&&e.effectivePlayingAsset?g.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return u()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return u()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return a()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){l(d,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){l(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){return r(e.seekableStart,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,g=d?.event;if(g&&!g.restrictions.skip){const m=e.findItemIndex(d);if(g.appendInPlace){const A=d.playout.start+d.event.duration;l(A+.001,"playout")}else e.advanceAfterAssetEnded(g,m,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const r=(t=s)==null?void 0:t.currentTime;if(!(r===void 0||!se(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Xe(r)}`),this.detachedData=r}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,u=(i=this.detachedData)==null?void 0:i.mediaSource;let h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else{const A=this.getBufferingPlayer();A?(r=A.transferMedia(),this.detachedData=r,h=`${A}`):u?h="detached MediaSource":h="detached media"}if(!r){if(u)r=this.detachedData,this.log(`using detachedData: MediaSource ${Xe(r)}`);else if(!this.detachedData||a.media===t){const A=this.playerQueue;A.length>1&&A.forEach(C=>{if(o&&C.interstitial.appendInPlace!==l){const v=C.interstitial;this.clearInterstitial(C.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=r&&"mediaSource"in r&&((s=r.mediaSource)==null?void 0:s.readyState)!=="closed";if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!d&&!o){e.attachMedia(t);return}const g=d&&r?Ae({},r):{media:t},m=this.schedule;if(m&&o){const A=e.assetId===m.assetIdAtEnd;g.overrides={duration:m.duration,endOfStream:A||e.appendInPlace===!1}}if(!d&&l){const A=e,C=A.assetItem.timelineStart;if(C){const v=A.hls,x=Math.max(this.timelinePos-C,Number.EPSILON);v.startPosition!==x&&(this.log(`Set ${A} startPosition: ${x}`),v.config.startPosition=x,v.loadingEnabled&&v.startLoad(x))}}e.attachMedia(g)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,r=this.effectivePlayingItem;if(s===-1){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}const a=i.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Fi("checkStart (preroll)",a));const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Fi("checkStart",a));const o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else i.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Fi("checkStart (playing item)",r.start));const a=e.findItemIndex(r);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),r=ua(i,s);if(!i.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!se(e.resumeOffset)&&this.hls){const i=this.getLiveStartPos();if(t){const s=this.getBufferingPlayer(),r=s!=null&&s.interstitial.cue.pre?s.remaining:0;return i+r}return i}}getNextItemIndex(e,t){if(this.schedule){const i=this.livePrerollResumption(e.event,t);if(i!==void 0)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){const s=ua(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const r=this.schedule.items;if(r){const a=r[t],o=a.event?this.getNextItemIndex(a):t+1,l=r.length;if(o>=l){this.setSchedulePosition(-1);return}const u=e.resumeTime;this.timelinePos<u&&(this.log(Fi("advanceAfterAssetEnded",u)),this.timelinePos=u,e.appendInPlace&&!r[o].event&&this.hls.startLoad(u+.01),this.checkBuffer(this.bufferedPos<u)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const r=e.assetList[s];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const a=i.findEventIndex(s),o=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ft(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const d=a.event,g=this.playingAsset,m=g?.identifier,A=m?this.getAssetPlayer(m):null;if(A&&m&&(!this.eventItemsMatch(a,r)||t!==void 0&&m!==d.assetList[t].identifier)){var l;const C=d.findAssetIndex(g);if(this.log(`INTERSTITIAL_ASSET_ENDED ${C+1}/${d.assetList.length} ${ts(g)}`),this.endedAsset=g,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:g,assetListIndex:C,event:d,schedule:s.slice(0),scheduleIndex:e,player:A}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),C);return}this.retreiveMediaSource(m,r),A.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&A.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Ft(a)}`),d.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once&&this.hls)){var u;this.updateSchedule();const C=(u=this.schedule)==null?void 0:u.items;if(r&&C){const v=this.findItemIndex(r),x=this.livePrerollResumption(d);if(x!==void 0){let R=x;const b=this.getNextItemIndex(a);if(!this.isInterstitial(s[b])){var h;const D=(h=this.primaryDetails)==null?void 0:h.fragments;if(d.snapOptions.in&&D){const _=qi(null,D,x);_&&(R=Math.min(Math.max(s[b].start,Rr(R,_)),s[b].end))}}if(this.log(Fi("live join (preroll)",R)),this.timelinePos=R,b!==v&&(b||b===0)){this.advanceSchedule(b,C,void 0,a,o);return}}this.advanceSchedule(v,C,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,i,s,r){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(h=>{const d=h.interstitial,g=a.findEventIndex(d.identifier);(g<e||g>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(i===void 0){i=h.cue.pre?0:a.findAssetIndex(h,this.timelinePos);const A=ua(h,i-1);if(h.isAssetPastPlayoutLimit(A)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,i);return}i=A}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let g=this.preloadAssets(h,i);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ft(o)} ${h.appendInPlace?"append in place":""}`),h.hasPlayed=!1,this.hls.trigger(E.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const m=h.assetList[i];if(!m){this.advanceAfterAssetEnded(h,e,i||0);return}if(g||(g=this.getAssetPlayer(m.identifier)),g===null||g.destroyed){const A=h.assetList.length;this.warn(`asset ${i+1}/${A} player destroyed ${h}`),g=this.createAssetPlayer(h,m,i),g.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(m))return;this.startAssetPlayer(g,i,t,e,l),this.shouldPlay&&tc(g.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&tc(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ft(e)}`);let a=this.timelinePos;if((s=this.detachedData)!=null&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Fi("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ft(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){const s=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;const r=this.endedItem||this.playingItem,a=r!=null&&r.event?this.livePrerollResumption(r.event,i):void 0;if(a!==void 0)return a;const o=this.primaryDetails;if(o){const{fragmentStart:l,edge:u}=o;if(s<l||s>u&&!i){const h=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${l}-${u}]) snapping to liveSync ${h}`),h||l}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var e;const t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||i&&i-t<s?i||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ve.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Fi("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){const i=this.hls,{loadingEnabled:s,bufferingEnabled:r,startPosition:a}=i,o=i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${s} bufferingEnabled: ${r}`),!t&&o||!s||Math.abs(a-e)>.1){const l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){const u=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${u?Ft(u):null}`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else r||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=Ae(Ae({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,r===-1?0:r),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;const u=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${u?Ft(u):null}`),u?.end===1/0){const d=this.playingItem,g=this.isInterstitial(d)&&d.event.appendInPlace;this.hls.startLoad(Math.max(l,u.start),g)}else{const d=this.getBufferingPlayer();d&&d.bufferedInPlaceToEnd(this.primaryMedia,d.currentTime)&&d.hls&&d.hls.trigger(E.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Ae(Ae({},this.altSelection),{},{audio:i});return}const r=Ae(Ae({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Ae(Ae({},this.altSelection),{},{subtitles:i});return}const r=Ae(Ae({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=Po(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Po(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const s=t[i];if(s.cue.post){const r=this.getEventItem(s.identifier);r&&this.eventItemsMatch(r,this.bufferingItem)&&this.bufferedToItem(r,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(e&&s){const r=this.findItemIndex(e,t);return s[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,s=ve.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Ft(e)} (was ${Ft(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const i=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;const s=this.mediaSelection;if(!s)return;const r=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(i=this.schedule)==null||i.updateSchedule(s,[],r,e)}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const s=ve.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var u;const h=this.findItemIndex(r),d=Math.min(h+1,t.length-1),g=t[d];if((l===-1&&r&&e>=r.end||(u=g.event)!=null&&u.appendInPlace&&e+.01>=g.start)&&(l=d),this.isInterstitial(r)){const m=r.event;if(d-o>1&&m.appendInPlace===!1||m.assetList.length===0&&m.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(g);else{const m=this.primaryDetails;this.primaryLive&&m&&e>m.edge-m.targetduration&&g.start<m.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(g)&&this.preloadAssets(g.event,0)}}else i&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{const r=this.getAssetPlayer(s.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ft(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,d)=>{const g=this.getAssetPlayer(h.identifier);g&&(d===u&&g.loadSource(),g.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(u=>u.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.getPrimaryResumption(e,this.findItemIndex(e),!0),r=this.bufferedPos=Math.max(s,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(r,e,!0):this.startLoadingPrimaryAt(r);else{const o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(r,l)}}}}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(s||!r){const a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=s===0&&!e.assetListLoader,a=e.cue.once;if(r){const l=e.timelineStart,u=this.playingItem,h=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let d,g=0;if((!h||h.interstitial.cue.pre)&&this.primaryLive&&(g=this.getLiveStartPos(),h&&(g+=h.remaining)),g&&!(e.cue.pre||e.cue.post)){const A=g-l;A>0&&(d=Math.round(A*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${g?` live-start: ${g} start-offset: ${d} (timeline-start: ${l})`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);const m=this.assetListLoader.loadAssetList(e,d);m&&(e.assetListLoader=m)}else if(!a&&s){for(let u=t;u<s;u++){const h=e.assetList[u],d=this.getAssetPlayerQueueIndex(h.identifier);(d===-1||this.playerQueue[d].destroyed)&&!h.error&&this.createAssetPlayer(e,h,u)}const l=e.assetList[t];if(l){const u=this.getAssetPlayer(l.identifier);return u&&u.loadSource(),u}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const i=this.primaryDetails;if(i&&e>=i.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}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,a){const o={parentIdentifier:e.identifier,identifier:Qp(e,a,t),duration:r,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig,a=s.loadLevelObj||s.levels[s.currentLevel],o=ko(a,r.videoPreference),l=s.audioTracks[s.audioTrack],u=s.subtitleTracks[s.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const D=this.timelinePos-t.timelineStart;if(D>=0){const _=t.duration;_&&D<_&&(h=D)}}const d=t.identifier,g=Ae(Ae({},r),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||r.audioPreference,subtitlePreference:u||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(g.timelineOffset=t.timelineStart));const m=g.cmcd;m!=null&&m.sessionId&&m.contentId&&(g.cmcd=je({},m,{contentId:ks(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const A=new tm(this.HlsPlayerClass,g,e,t);this.playerQueue.push(A),e.assetList[i]=t;let C=!0;const v=D=>{if(D.live){const p=new Error(`Interstitials MUST be VOD assets ${e}`),$={fatal:!0,type:me.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},N=this.findEventIndex(e.identifier);this.handleAssetItemError($,e,N,i,p.message);return}const _=D.edge-D.fragmentStart,M=t.duration;(C||M===null||_>M)&&(C=!1,this.log(`Interstitial asset "${d}" duration change ${M} > ${_}`),t.duration=_,this.updateSchedule())};A.on(E.LEVEL_UPDATED,(D,{details:_})=>v(_)),A.on(E.LEVEL_PTS_UPDATED,(D,{details:_})=>v(_)),A.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const x=(D,_)=>{const M=this.getAssetPlayer(d);if(M&&_.tracks){M.off(E.BUFFER_CODECS,x),M.tracks=_.tracks;const p=this.primaryMedia;this.bufferingAsset===M.assetItem&&p&&!M.media&&this.bufferAssetPlayer(M,p)}};A.on(E.BUFFER_CODECS,x);const R=()=>{const D=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${D}`),!D||!this.schedule)return;const _=this.getEventItem(e.identifier);_&&this.advanceAssetBuffering(_,D.assetItem)};A.on(E.BUFFERED_TO_END,R);const b=D=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const M=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,M,D)};return A.once(E.MEDIA_ENDED,b(i)),A.once(E.PLAYOUT_LIMIT_REACHED,b(1/0)),A.on(E.ERROR,(D,_)=>{if(!this.schedule)return;const M=this.getAssetPlayer(d);if(_.details===U.BUFFER_STALLED_ERROR){if(M!=null&&M.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(_.details===U.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(_,e,this.findEventIndex(e.identifier),i,`Asset player error ${_.error} ${e}`)}),A.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const _=new Error(`Asset player destroyed unexpectedly ${d}`),M={fatal:!0,type:me.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(M,e,this.findEventIndex(e.identifier),i,_.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ts(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:A}),A}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Ft(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:a,assetItem:o,assetId:l}=e,u=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h?.identifier!==l&&(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${u} ${ts(o)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;const{interstitial:s,assetItem:r}=e,a=this.getEventItem(s.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,r);return}const o=this.getBufferingPlayer();if(o===e)return;const l=s.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;const u=o?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!ja(u,e.tracks)){const h=new Error(`Asset ${ts(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),d={fatal:!0,type:me.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},g=s.findAssetIndex(r);this.handleAssetItemError(d,s,this.findEventIndex(s.identifier),g,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||s-a.timelineStart,u=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+u} in ${o} ${e} (media.currentTime: ${s})`),l&&(u/i.playbackRate<.5||o.bufferedInPlaceToEnd(i,o.currentTime))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,s,r){if(e.details===U.BUFFER_STALLED_ERROR)return;const a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&ts(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),u=this.playerQueue[l]||null,h=this.schedule.items,d=je({},e,{fatal:!1,errorAction:vs(!0),asset:a,assetListIndex:s,event:t,schedule:h,scheduleIndex:i,player:u});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const g=this.playingAsset,m=this.bufferingAsset,A=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=A),!t.assetList.some(C=>!C.error))t.error=A;else for(let C=s;C<t.assetList.length;C++)this.resetAssetPlayer(t.assetList[C].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):g?.identifier===o?this.advanceAfterAssetEnded(t,i,s):m?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,m)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,r=this.seekableStart,a=this.hls.startPosition;let o=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ft(i)} startPosition: ${a} seekableStart: ${r} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,r);const u=this.updateItem(i,o);this.itemsMatch(i,u)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(s))return;const l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,s;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;const l=r.timelineStart,u=r.duration;let h=0;o.forEach((A,C)=>{const v=parseFloat(A.DURATION);this.createAsset(r,C,h,l+h,v,A.URI),h+=v}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${u}) ${r}`);const d=this.waitingItem,g=d?.event.identifier===a;this.updateSchedule();const m=(s=this.bufferingItem)==null?void 0:s.event;if(g){const A=this.findEventIndex(a),C=this.getEventItem(a);if(C){if(!this.playingItem&&this.timelinePos>C.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==A){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(C)}this.setSchedulePosition(A)}else if(m?.identifier===a){const A=r.assetList[0];if(A){const C=this.getAssetPlayer(A.identifier);if(m.appendInPlace){const v=this.primaryMedia;C&&v&&this.bufferAssetPlayer(C,v)}else C&&C.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case U.ASSET_LIST_PARSING_ERROR:case U.ASSET_LIST_LOAD_ERROR:case U.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case U.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}const s=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${s?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class nm{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:i}=this,s=this.levelDetails;if(!i||!s||!this.hls)return;this.currentTime=i.currentTime;const r=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=r;if(!o||l===1||!s.live)return;const u=this.targetLatency;if(u===null)return;const h=a-u,d=Math.min(this.maxLatency,u+s.targetduration),g=h<d,m=dr(r)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(g&&h>.05&&this.forwardBufferLength>1&&!m){const A=Math.min(2,Math.max(1,l)),C=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,v=Math.min(A,Math.max(1,C));this.changeMediaPlaybackRate(i,v)}else i.playbackRate!==1&&i.playbackRate!==0&&this.changeMediaPlaybackRate(i,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;const t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||!this.hls)return null;const t=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,u=this.hls.userConfig;let h=l&&s||i;(this._targetLatencyUpdated||u.liveSyncDuration||u.liveSyncDurationCount||h===0)&&(h=a!==void 0?a:o*r);const d=r;return h+Math.min(this.stallCount*t.liveSyncOnStallIncrease,d)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,r=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null||!this.hls)return 0;const t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this),e.on(E.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this),e.off(E.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;const s=this.hls,r=this.media||t.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((a,o)=>a||o.media,null));s&&r&&r.playbackRate>1&&r.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(e,t){var i;t.details===U.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const ic=500;class am extends En{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",ge.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Y.IDLE,this.setInterval(ic),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,part:s,success:r}=t;if(!r)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o;const l=(s||i).start;for(let h=0;h<a.length;h++)if(l>=a[h].start&&l<=a[h].end){o=a[h];break}const u=l+(s||i).duration;if(o?o.end=u:(o={start:l,end:u},a.push(o)),!s||u>=i.end){const h=this.fragmentTracker.fragBuffered(i);s&&h&&(h.range.subs={time:[{startPTS:i.start,endPTS:u}],partial:!0}),st(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,r,ge.SUBTITLE)}}onError(e,t){const i=t.frag;i?.type===ge.SUBTITLE&&(t.details===U.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Y.STOPPED&&(this.state=Y.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Ql(this.levels,t)){this.levels=t.map(i=>new Cs(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new Cs(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ge.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];if(!(s!=null&&s.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Y.STOPPED&&this.setInterval(ic)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const u=this.mainDetails;let h=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;if(!u){this.startFragRequested=!1;return}if(l.details){var d;h=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}a.alignedSliding||(cr(u,a,this),h=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,u&&!this.startFragRequested&&this.setStartPosition(u,h),o===s&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:i,payload:s}=e;!i||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,i)}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e;this.fragContextChanged(t)||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Xi(t.method))}decryptPayload(e,t,i){const s=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),s.key.buffer,s.iv.buffer,pn(s.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(E.FRAG_DECRYPTED,{frag:t,part:i,payload:a,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:i}),i||(this.warn(`${a.name}: ${a.message}`),this.state=Y.IDLE)})}doTick(){if(this.state===Y.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,r=s[i],a=r?.details;if(!a||this.waitForLive(r)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}const{config:o}=this,l=this.playhead,u=ve.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:h,len:d}=u,g=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(d>g||d&&!this.buffering)return;let m=this.getNextFragment(h,a);if(!m)return;if(st(m)){var t;const A=m.sn-a.startSN,C=a.fragments[A-1];m.cc===C?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(C)===et.NOT_LOADED&&(m=C)}this.loadFragment(m,r,h)}}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);(s===et.NOT_LOADED||s===et.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new om(this.tracksBuffered[this.currentTrackId]||[])}}class om{constructor(e){this.buffered=void 0;const t=(i,s,r)=>{if(s=s>>>0,s>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}const lm={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},sc=n=>String.fromCharCode(lm[n]||n),zt=15,Xt=42,um={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},cm={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hm={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},dm={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fm=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class gm{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;Ge.log(`${this.time} [${e}] ${i}`)}}}const Ni=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ha=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class rc{constructor(){this.styles=ha}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=ha}setStyles(e){const t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class pm{constructor(){this.uchar=" ",this.penState=new rc}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class mm{constructor(e){this.chars=[],this.pos=0,this.currPenState=new rc,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Xt;t++)this.chars.push(new pm);this.logger=e}equals(e){const t=this.chars,i=e.chars;for(let s=0;s<Xt;s++){const r=t[s],a=i[s];if(r.uchar!==a.uchar)return!1;const o=r.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Xt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<Xt;t++){const i=e[t];if(i.uchar!==" ")return!1;const s=i.penState.styles;if(s!==ha&&(s.foreground!=="white"||s.underline||s.italics||s.background!=="black"||s.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Xt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xt-1)}moveCursor(e){const t=Math.min(this.pos+e,Xt);if(e>1)for(let i=this.pos+1;i<t;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=sc(e);if(this.pos>=Xt){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Xt;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<Xt;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 da{constructor(e){this.rows=[],this.currRow=zt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<zt;t++)this.rows.push(new mm(e));this.logger=e}reset(){for(let e=0;e<zt;e++)this.rows[e].clear();this.currRow=zt-1}equals(e){let t=!0;for(let i=0;i<zt;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<zt;t++){const i=this.rows[t].chars,s=e.rows[t].chars;for(let r=0;r<Xt;r++){const a=i[r],o=s[r];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<zt;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 = "+Xe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<zt;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let u=0;u<this.nrRollUpRows;u++)this.rows[t-this.nrRollUpRows+u+1].copy(a.rows[r+u])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Xe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let r=0;r<zt;r++){const a=this.rows[r].getTextString();a&&(s=r+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
42
|
-
`)),i}getTextAndFormat(){return this.rows}}class Am{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 da(i),this.nonDisplayedMemory=new da(i),this.lastOutputScreen=new da(i),this.currRollUpRow=this.displayedMemory.rows[zt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[zt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+Xe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class nc{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Cm(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new gm,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,(i=this.channels[e])==null||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new Am(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,r=t[i+1]&127;let a=!1,o=null;if(s===0&&r===0)continue;this.logger.log(3,()=>"["+Ni([t[i],t[i+1]])+"] -> ("+Ni([s,r])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(Im(s,r,l)){Dr(null,null,l),this.logger.log(3,()=>"Repeated command ("+Ni([s,r])+") is dropped");continue}Dr(s,r,this.cmdHistory),a=this.parseCmd(s,r),a||(a=this.parseMidrow(s,r)),a||(a=this.parsePAC(s,r)),a||(a=this.parseBackgroundAttributes(s,r))}else Dr(null,null,l);if(!a&&(o=this.parseChars(s,r),o)){const h=this.currentChannel;h&&h>0?this.getChannel(h).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ni([s,r])+" orig: "+Ni([t[i],t[i+1]]))}}parseCmd(e,t){const i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;const r=e===20||e===21||e===23?1:2,a=this.getChannel(r);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ni([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(s||r))return!1;const a=e<=23?1:2;return t>=64&&t<=95?i=a===1?um[e]:hm[e]:i=a===1?cm[e]:dm[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+sc(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+Ni(s).join(",")),s}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=fm[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Dr(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 Dr(n,e,t){t.a=n,t.b=e}function Im(n,e,t){return t.a===n&&t.b===e}function Cm(){return{a:null,b:null}}class Pr{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class ym{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ac(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Pr(this,"textTrack1"),t=new Pr(this,"textTrack2"),i=new Pr(this,"textTrack3"),s=new Pr(this,"textTrack4");this.cea608Parser1=new nc(1,e,t),this.cea608Parser2=new nc(3,i,s)}addCues(e,t,i,s,r){let a=!1;for(let l=r.length;l--;){const u=r[l],h=vm(u[0],u[1],t,i);if(h>=0&&(u[0]=Math.min(u[0],t),u[1]=Math.max(u[1],i),a=!0,h/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){const l=this.cueCache[e];if(l){const u=this.Cues.newCue(null,t,i,s);u.length&&l.push.apply(l,u)}else{const u=this.captionsTracks[e].track;this.Cues.newCue(u,t,i,s)}}else{var o;const l=this.Cues.newCue(null,t,i,s),u=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:u})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){const{unparsedVttFrags:s}=this;t===ge.MAIN&&(this.initPTS=i),s.length&&(this.unparsedVttFrags=[],s.forEach(r=>{this.initPTS[r.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,r):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,cueCache:s,media:r}=this,{label:a,languageCode:o}=t[e];r&&(s[e]=[],i[e]=sa(r,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){const{captionsTracks:s,cueCache:r}=this;for(const a in s)s[a].remove(),delete r[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ac(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!Ql(this.tracks,i)){const s=i.map(r=>({label:r.name,kind:r.type.toLowerCase(),default:r.default,subtitleTrack:r}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const r=`textTrack${s[1]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ge.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=t.frag,h=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;r&&a&&(u!==o+1||u===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.level<this.tracks.length&&i.type===ge.SUBTITLE){var r;if(s.byteLength||(r=i.initSegment)!=null&&(r=r.data)!=null&&r.byteLength){const a=i.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){const l=this.tracks[i.level],u=this.vttCCs;u[i.cc]||(u[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),l?.textCodec===Jn?this._parseIMSC1(t):this._parseVTTs(t)}}else{const a="part"in t?t.part:null;this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){const{frag:t,payload:i}=e,s="part"in e?e.part:null,r=this.hls;Gu(i,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:s})},a=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:s,error:a})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,r="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[i.cc]&&l===-1){o.push(e);return}const u=this.hls,h=(t=i.initSegment)==null?void 0:t.data,d=h?Bt(h,new Uint8Array(s)).buffer:s;Dp(d,this.initPTS[i.cc],this.vttCCs,i.cc,(r&&!h?r:i).start,g=>{this._appendCues(g,i.level),u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:r})},g=>{const m=g.message.startsWith("Missing initPTS");if(u.logger.log(`${m?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${g}`),m){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);u.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:r,error:g})})}_fallbackToIMSC1(e){const{frag:t,payload:i}=e,s=this.tracks[t.level];s.textCodec||Gu(i,this.initPTS[t.cc],()=>{s.textCodec=Jn,this._parseIMSC1(e)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){var s;const r=(s=this.tracks[t].trackNode)==null?void 0:s.track;if(!r||r.mode==="disabled")return;e.forEach(a=>ra(r,a))}else{const r=this.tracks[t];if(!r)return;const a=r.default?"default":"subtitles"+t;i.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===ge.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===ge.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;r<s.length;r++){const a=s[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[r].pts,o[0]),this.cea608Parser2.addData(s[r].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;const{type:s,timeRanges:r}=t;if(s==="video"&&(i=r[s])!=null&&i.length){const{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var u;const h=(u=a[l])==null?void 0:u.track;if(h){const d=o[l];for(let g=0;g<d.length;g++)ra(h,d[g])}delete o[l]})}}}onBufferFlushing(e,t){const{startOffset:i,endOffset:s,endOffsetSubtitles:r,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<s)){if(!a||a==="video"){const{captionsTracks:l,cueCache:u}=this;Object.keys(l).forEach(h=>na(l[h].track,i,s)),Object.keys(u).forEach(h=>{const d=u[h];for(let g=d.length;g--;){const m=d[g];m.startTime>=i&&m.endTime<=s&&d.splice(g,1)}})}this.config.renderTextTracksNatively&&i===0&&r!==void 0&&this.tracks.forEach(l=>{var u;const h=(u=l.trackNode)==null?void 0:u.track;h&&na(h,i,r)})}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let r=0;r<i;r++){const a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function vm(n,e,t,i){return Math.min(e,i)-Math.max(n,t)}function ac(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Em=/\s/,Tm={newCue(n,e,t,i){const s=[];let r,a,o,l,u;const h=self.VTTCue||self.TextTrackCue;for(let g=0;g<i.rows.length;g++)if(r=i.rows[g],o=!0,l=0,u="",!r.isEmpty()){var d;for(let C=0;C<r.chars.length;C++)Em.test(r.chars[C].uchar)&&o?l++:(u+=r.chars[C].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const m=Nu(u.trim()),A=Qn(e,t,m);n!=null&&(d=n.cues)!=null&&d.getCueById(A)||(a=new h(e,t,m),a.id=A,a.line=g+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return n&&s.length&&(s.sort((g,m)=>g.line==="auto"||m.line==="auto"?0:g.line>8&&m.line>8?m.line-g.line:g.line-m.line),s.forEach(g=>ra(n,g))),s}};class oc{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Vr}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(hs(e,t,!0))this.retry(e);else{var i;Ge.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Yr(e,i.retry),i.retry++,Ge.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function Sm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const xm=/(\d+)-(\d+)\/(\d+)/;class lc extends oc{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||Dm}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;const s=bm(t,this.controller.signal),r=t.responseType==="arraybuffer",a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&se(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(Ds(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=h;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(g-i.loading.start)),!h.ok){const{status:A,statusText:C}=h;throw new Pm(C||"fetch, bad network response",A,h)}i.loading.first=g,i.total=Rm(h.headers)||i.total;const m=(d=this.callbacks)==null?void 0:d.onProgress;return m&&se(e.highWaterMark)?this.loadProgressively(h,i,t,e.highWaterMark,m):r?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var d,g;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const A=h[a];A&&(i.loaded=i.total=A);const C={url:m.url,data:h,code:m.status},v=(d=this.callbacks)==null?void 0:d.onProgress;v&&!se(e.highWaterMark)&&v(i,t,h,m),(g=this.callbacks)==null||g.onSuccess(C,i,t,m)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const d=h&&h.code||0,g=h?h.message:null,m=e.loadPolicy.errorRetry,A=i.retry,C={url:t.url,data:void 0,code:d};if(hs(m,A,!1,C))this.retry(m);else{var v;Ge.error(`${d} while loading ${t.url}`),(v=this.callbacks)==null||v.onError({code:d,text:g},t,h?h.details:null,i)}})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,r){const a=new xl,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&r(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=u.value,d=h.length;return t.loaded+=d,d<s||a.dataLength?(a.push(h),a.dataLength>=s&&r(t,i,a.flush().buffer,e)):r(t,i,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function bm(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(je({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function Lm(n){const e=xm.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Rm(n){const e=n.get("Content-Range");if(e){const i=Lm(e);if(se(i))return i}const t=n.get("Content-Length");if(t)return parseInt(t)}function Dm(n,e){return new self.Request(n.url,e)}class Pm extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const _m=(n,e,t)=>Math.max(e,Math.min(n,t)),km=/^age:\s*[\d.]+\s*$/im;class uc extends oc{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r.call(this,i,t.url,t)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&se(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(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)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const u=t.status,h=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){const A=h??t.response;if(A!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const C=t.responseType==="arraybuffer"?A.byteLength:A.length;i.loaded=i.total=C,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const v=(a=this.callbacks)==null?void 0:a.onProgress;v&&v(i,e,A,t);const x={url:t.responseURL,data:A,code:u};e.rangeEnd&&C!==e.rangeEnd-e.rangeStart&&Ge.warn(`Payload length ${C} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(x,i,e,t);return}}const d=r.loadPolicy.errorRetry,g=i.retry,m={url:e.url,data:void 0,code:u};if(hs(d,g,!1,m))this.retry(d);else{var l;Ge.error(`${u} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:u,text:t.statusText},e,t,i)}}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&km.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 wm={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Mm=Ae(Ae({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:uc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:tl,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:wm},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Xu,abrController:Cd,bufferController:lg,capLevelController:Fn,errorController:Td,fpsController:Ep,id3TrackController:Hp,gapController:$p,latencyController:nm},Om()),{},{subtitleStreamController:am,subtitleTrackController:Bp,timelineController:ym,audioStreamController:ig,audioTrackController:sg,emeController:es,cmcdController:pp,contentSteeringController:Ap,iframeController:zp,interstitialsController:rm});function Om(){return{cueHandler:Tm,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Fm(n,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){const a=e.liveMaxUnchangedPlaylistRefresh,o=_m(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}const i=fa(n),s=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,u=[];r.forEach(h=>{const d=`${a}Loading${h}`,g=e[d];if(g!==void 0&&l){u.push(d);const m=i[o].default;switch(e[o]={default:m},h){case"TimeOut":m.maxLoadTimeMs=g,m.maxTimeToFirstByteMs=g;break;case"MaxRetry":m.errorRetry.maxNumRetry=g,m.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":m.errorRetry.retryDelayMs=g,m.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":m.errorRetry.maxRetryDelayMs=g,m.timeoutRetry.maxRetryDelayMs=g;break}}}),u.length&&t.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${o}": ${Xe(e[o])}`)}),Ae(Ae({},i),e)}function fa(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(fa):Object.keys(n).reduce((e,t)=>(e[t]=fa(n[t]),e),{}):n}function Nm(n,e){const t=n.loader;t!==lc&&t!==uc?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):Sm()&&(n.loader=lc,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Bm extends wn{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},a={};let o=!1,l=!1,u=!1,h=!1;t.levels.forEach(d=>{const g=d.attrs,m=dc(d,i),{audioCodec:A,videoCodec:C,imageCodec:v,width:x,height:R}=d;if(!m){this.log(`Some or all CODECS not supported "${g.CODECS}"`);return}o||(o=!!(x&&R)),l||(l=!!C),u||(u=!!A),h||(h=!!v);const{CODECS:b,"FRAME-RATE":D,"HDCP-LEVEL":_,"PATHWAY-ID":M,RESOLUTION:p,"VIDEO-RANGE":$}=g,O=`${`${M||"."}-`}${d.bitrate}-${p}-${D}-${b}-${$}-${_}`;if(r[O])if(r[O].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const W=a[O]+=1;d.attrs["PATHWAY-ID"]=new Array(W+1).join(".");const q=this.createLevel(d);r[O]=q,s.push(q)}else d.iframes||(r[O].addGroupId("audio",g.AUDIO),r[O].addGroupId("text",g.SUBTITLES));else{const W=this.createLevel(d);r[O]=W,a[O]=1,s.push(W)}}),this.filterAndSortMediaOptions(s,t,o,l,u,h)}createLevel(e){const t=new Cs(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!hc(i.videoCodec,this.hls.config.preferManagedMediaSource)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=Eo(s,[])}return t}filterAndSortMediaOptions(e,t,i,s,r,a){var o;let l=[],u=[],h=e;const d=((o=t.stats)==null?void 0:o.parsing)||{},g=this.hls.config.preferManagedMediaSource;if((i||s)&&r&&(h=h.filter(({videoCodec:_,videoRange:M,width:p,height:$})=>(!!_||!!(p&&$))&&cd(M))),s&&a&&(h=h.filter(_=>!_.imageCodec)),h.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",M=_;t.levels.length&&(M=`one or more CODECS in variant not supported: ${Xe(t.levels.map($=>$.attrs.CODECS).filter(($,N,O)=>O.indexOf($)===N))}`,this.warn(M),_+=` (${M})`);const p=new Error(_);this.hls.trigger(E.ERROR,{type:me.MEDIA_ERROR,details:U.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:p,reason:M})}}),d.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(_=>!_.audioCodec||cc(_.audioCodec,g)),fc(l)),t.subtitles&&(u=t.subtitles,fc(u));const m=h.slice(0);h.sort((_,M)=>{if(_.attrs["HDCP-LEVEL"]!==M.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(M.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&_.height!==M.height)return _.height-M.height;if(_.frameRate!==M.frameRate)return _.frameRate-M.frameRate;if(_.videoRange!==M.videoRange)return tr.indexOf(_.videoRange)-tr.indexOf(M.videoRange);if(_.videoCodec!==M.videoCodec){const p=Io(_.videoCodec),$=Io(M.videoCodec);if(p!==$)return $-p}if(_.uri===M.uri&&_.codecSet!==M.codecSet){const p=Qs(_.codecSet),$=Qs(M.codecSet);if(p!==$)return $-p}return _.averageBitrate!==M.averageBitrate?_.averageBitrate-M.averageBitrate:0});let A=m[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==m.length)){for(let _=0;_<m.length;_++)if(m[_].pathwayId===h[0].pathwayId){A=m[_];break}}this._levels=h;for(let _=0;_<h.length;_++)if(h[_]===A){var C;this._firstLevel=_;const M=A.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${M}`),((C=this.hls.userConfig)==null?void 0:C.abrEwmaDefaultEstimate)===void 0){const $=Math.min(M,this.hls.config.abrEwmaDefaultEstimateMax);$>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=$)}break}const v=t.iframeVariants.filter(_=>dc(_,g));this._iframeVariants=v;const x=r&&!s,R=this.hls.config,b=!!(R.audioStreamController&&R.audioTrackController),D={levels:h,audioTracks:l,subtitleTracks:u,iframeVariants:v,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:b&&!x&&l.some(_=>!!_.url)};d.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,D)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:h,reason:h.message}),d)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,l);const u=a.details;if(!u||u.live){const h=this.switchParams(a.uri,s?.details,u);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===ke.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===ge.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(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"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(E.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){const s=this.hls.config.abrSwitchInterval;if(s>0){const r=performance.now(),a=r-this.lastABRSwitchTime,o=s*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${s}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${s}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));yl(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(E.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function cc(n,e){return As(n,"audio",e)}function hc(n,e){return As(n,"video",e)}function dc(n,e){let{audioCodec:t,videoCodec:i}=n;t&&(n.audioCodec=t=Js(t,e)||void 0),i&&(i=n.videoCodec=td(i));const{unknownCodecs:s}=n;return!(s?.length||0||t&&!cc(t,e)||i&&!hc(i,e))}function fc(n){const e={};n.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Um extends wt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyLoaderInfo){const s=this.keyLoaderInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);const s=e.decryptdata;if(!s){const a=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Li(e,U.KEY_LOAD_ERROR,a))}const r=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Li(e,U.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){const i=Oh(e.initSegment.data);if(i.length){let s=i[0];const r=e.decryptdata.uri;if(s.some(a=>a!==0))this.log(`Using keyId found in init segment ${ut(s)} keyUri: ${r}`),gi.setKeyIdForUri(r,s);else{const a=gi.addKeyIdForUri(r);this.log(`Patching empty keyId with ${ut(a)} keyUri: ${r}`),s=a}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Li(e,U.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(Li(e,U.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(u=>(t.key=s.decryptdata.key,Ae(Ae({},u),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+ut(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const r=this.config,a=r.loader,o=new a(r);e.keyLoader=o;const l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((u,h)=>{const d={type:ke.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},g=r.keyLoadPolicy.default,m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},A={onSuccess:(C,v,x,R)=>{const{frag:b,keyInfo:D,url:_}=x;if(!b.decryptdata||D!==this.keyLoaderInfo[_])return h(Li(b,U.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),R));D.decryptdata.key=b.decryptdata.key=new Uint8Array(C.data),b.keyLoader=D.loader=D.keyLoadPromise=null,u({frag:b,keyInfo:D})},onError:(C,v,x,R)=>{this.resetLoader(v),h(Li(e,U.KEY_LOAD_ERROR,new Error(`HTTP Error ${C.code} loading key ${C.text}`),x,Ae({url:i,data:void 0},C)))},onTimeout:(C,v,x)=>{this.resetLoader(v),h(Li(e,U.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),x))},onAbort:(C,v,x)=>{this.resetLoader(v),h(Li(e,U.INTERNAL_ABORTED,new Error("key loading aborted"),x))}};o.load(d,m,A)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],r&&r.destroy()}}function Li(n,e=U.KEY_LOAD_ERROR,t,i,s){return new si({type:me.NETWORK_ERROR,details:e,fatal:!1,frag:n,response:s,error:t,networkDetails:i||null})}function gc(n){const{type:e}=n;switch(e){case ke.AUDIO_TRACK:return ge.AUDIO;case ke.SUBTITLE_TRACK:return ge.SUBTITLE;default:return ge.MAIN}}function ga(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class $m{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=i||s,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ke.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:ke.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ke.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:ke.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[ke.LEVEL];if(i){const s=i.context;s&&!t.levels.some(r=>r===s.levelOrTrack)&&(i.abort(),delete this.loaders[ke.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const u=this.hls.logger,h=s.context;if(h?.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?u.log(`[playlist-loader]: ignore ${e.url} ongoing request`):u.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}u.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===ke.MANIFEST?r=i.manifestLoadPolicy.default:r=je({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),se((t=e.deliveryDirectives)==null?void 0:t.part)){let u;if(e.type===ke.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===ke.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===ke.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){const h=u.partTarget,d=u.targetduration;if(h&&d){const g=Math.max(h*3,d*.8)*1e3;r=je({},r,{maxTimeToFirstByteMs:Math.min(g,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,h,d,g)=>{const m=this.getInternalLoader(d);this.resetInternalLoader(d.type);const A=u.data;h.parsing.start=performance.now(),ri.isMediaPlaylist(A)||d.type!==ke.MANIFEST?this.handleTrackOrLevelPlaylist(u,h,d,g||null,m):this.handleMasterPlaylist(u,h,d,g)},onError:(u,h,d,g)=>{this.handleNetworkError(h,d,!1,u,g)},onTimeout:(u,h,d)=>{this.handleNetworkError(h,d,!0,void 0,u)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const r=this.hls,a=e.data,o=ga(e,i),l=ri.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:u,levels:h,iframeVariants:d,sessionData:g,sessionKeys:m,startTimeOffset:A,variableList:C}=l;this.variableList=C,h.forEach(b=>{const{unknownCodecs:D}=b;if(D){const{preferManagedMediaSource:_}=this.hls.config;let{audioCodec:M,videoCodec:p}=b;for(let $=D.length;$--;){const N=D[$];As(N,"audio",_)?(b.audioCodec=M=M?`${M},${N}`:N,ji.audio[M.substring(0,4)]=2,D.splice($,1)):As(N,"video",_)&&(b.videoCodec=p=p?`${p},${N}`:N,ji.video[p.substring(0,4)]=2,D.splice($,1))}}});const{AUDIO:v=[],SUBTITLES:x,"CLOSED-CAPTIONS":R}=ri.parseMasterPlaylistMedia(a,o,l);v.length&&!v.some(D=>!D.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"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new tt({}),bitrate:0,url:""})),r.trigger(E.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:x,iframeVariants:d,captions:R,contentSteering:u,url:o,stats:t,networkDetails:s,sessionData:g,sessionKeys:m,startTimeOffset:A,variableList:C})}handleTrackOrLevelPlaylist(e,t,i,s,r){const a=this.hls,{id:o,level:l,type:u}=i,h=ga(e,i),d=se(l)?l:se(o)?o:0,g=gc(i),m=ri.parseLevelPlaylist(e.data,h,d,g,0,this.variableList);if(u===ke.MANIFEST){const A={attrs:new tt({}),bitrate:0,details:m,name:"",url:h};m.requestScheduled=t.loading.start+ml(m,0),a.trigger(E.MANIFEST_LOADED,{levels:[A],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(E.ERROR,{type:me.NETWORK_ERROR,details:U.MANIFEST_PARSING_ERROR,fatal:t.type===ke.MANIFEST,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 a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===ke.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ke.AUDIO_TRACK||e.type===ke.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=U.UNKNOWN,u=!1;const h=this.getInternalLoader(e);switch(e.type){case ke.MANIFEST:l=i?U.MANIFEST_LOAD_TIMEOUT:U.MANIFEST_LOAD_ERROR,u=!0;break;case ke.LEVEL:l=i?U.LEVEL_LOAD_TIMEOUT:U.LEVEL_LOAD_ERROR,u=!1;break;case ke.AUDIO_TRACK:l=i?U.AUDIO_TRACK_LOAD_TIMEOUT:U.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case ke.SUBTITLE_TRACK:l=i?U.SUBTITLE_TRACK_LOAD_TIMEOUT:U.SUBTITLE_LOAD_ERROR,u=!1;break}h&&this.resetInternalLoader(e.type);const d={type:me.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(s){let g=e.url;t&&"url"in t&&(g=t.url),d.response=Ae({url:g,data:void 0},s)}this.hls.trigger(E.ERROR,d)}handlePlaylistLoaded(e,t,i,s,r,a){const o=this.hls,{type:l,level:u,levelOrTrack:h,id:d,groupId:g,deliveryDirectives:m}=s,A=ga(t,s),C=gc(s);let v=typeof s.level=="number"&&C===ge.MAIN?u:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const x=e.playlistParsingError;if(x){if(this.hls.logger.warn(`${x} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:me.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:A,error:x,reason:x.message,response:t,context:s,level:v,parent:C,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const R=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:me.NETWORK_ERROR,details:U.LEVEL_EMPTY_ERROR,fatal:!1,url:A,error:R,reason:R.message,response:t,context:s,level:v,parent:C,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ke.MANIFEST:case ke.LEVEL:if(v){if(!h)v=0;else if(h!==o.levels[v]){const R=o.levels.indexOf(h);R>-1&&(v=R)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:v||0,id:d||0,stats:i,networkDetails:r,deliveryDirectives:m,withoutMultiVariant:l===ke.MANIFEST,context:s});break;case ke.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:m,context:s});break;case ke.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:g||"",stats:i,networkDetails:r,deliveryDirectives:m,context:s});break}}}class Tt{static get version(){return Ss}static isMSESupported(){return zu()}static isSupported(){return Vp()}static getMediaSource(){return Ei()}static get Events(){return E}static get MetadataSchema(){return Et}static get ErrorTypes(){return me}static get ErrorDetails(){return U}static get DefaultConfig(){return Tt.defaultConfig?Tt.defaultConfig:Mm}static set DefaultConfig(e){Tt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Sn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=lh(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=Fm(Tt.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Nm(i,t);const{streamController:s,abrController:r,bufferController:a,capLevelController:o,errorController:l,fpsController:u,id3TrackController:h,iframeController:d,gapController:g}=i,m=new l(this),A=this.abrController=new r(this),C=new Sd(this),v=i.interstitialsController,x=v?this.interstitialsController=new v(this,Tt):null,R=a?this.bufferController=new a(this,C):null,b=o?this.capLevelController=new o(this):null,D=u?new u(this):null,_=i.cmcdController,M=_?this.cmcdController=new _(this):null,p=new $m(this),$=i.contentSteeringController,N=$?new $(this):null,O=this.levelController=new Bm(this,N),W=h?new h(this):void 0,q=new Um(this.config,this.logger),z=this.streamController=new s(this,C,q),oe=this.gapController=g?new g(this,C):void 0;b&&b.setStreamController(z);const re=[p,O,z];x&&re.splice(1,0,x),N&&re.splice(1,0,N),this.networkControllers=re;const J=[A];R&&J.push(R),oe&&J.push(oe),b&&J.push(b),D&&(D.setStreamController(z),J.push(D)),W&&J.push(W),J.push(C),this.audioTrackController=this.createController(i.audioTrackController,re);const Z=i.audioStreamController;Z&&re.push(this.audioStreamController=new Z(this,C,q)),this.subtitleTrackController=this.createController(i.subtitleTrackController,re);const Q=i.subtitleStreamController;Q&&re.push(this.subtititleStreamController=new Q(this,C,q)),this.createController(i.timelineController,J),q.emeController=this.emeController=this.createController(i.emeController,J),M&&J.push(M),this.latencyController=this.createController(i.latencyController,J),this.coreComponents=J,this.iframeController=d?new d(this,Tt):void 0,re.push(m);const ee=m.onErrorOut;typeof ee=="function"&&this.on(E.ERROR,ee,m),this.on(E.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===E.ERROR;this.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(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,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:me.OTHER_ERROR,details:U.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(E.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(E.MEDIA_DETACHING,e),this._media=null,this.trigger(E.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(E.MEDIA_DETACHING,i),this.trigger(E.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();const i=this.media,s=this._url,r=this._url=Hr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==Y.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ge.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ge.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ge.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,i=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Xa()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ud(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let r=s;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=Do(t);return To(e,i,navigator.mediaCapabilities)}}Tt.defaultConfig=void 0;function Gm(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var _r={exports:{}};var Hm=_r.exports,pc;function Vm(){return pc||(pc=1,(function(n){(function(e,t){n.exports=e.document?t(e,!0):function(i){if(!i.document)throw new Error("jQuery requires a window with a document");return t(i)}})(typeof window<"u"?window:Hm,function(e,t){var i=[],s=Object.getPrototypeOf,r=i.slice,a=i.flat?function(c){return i.flat.call(c)}:function(c){return i.concat.apply([],c)},o=i.push,l=i.indexOf,u={},h=u.toString,d=u.hasOwnProperty,g=d.toString,m=g.call(Object),A={},C=function(f){return typeof f=="function"&&typeof f.nodeType!="number"&&typeof f.item!="function"},v=function(f){return f!=null&&f===f.window},x=e.document,R={type:!0,src:!0,nonce:!0,noModule:!0};function b(c,f,I){I=I||x;var y,T,S=I.createElement("script");if(S.text=c,f)for(y in R)T=f[y]||f.getAttribute&&f.getAttribute(y),T&&S.setAttribute(y,T);I.head.appendChild(S).parentNode.removeChild(S)}function D(c){return c==null?c+"":typeof c=="object"||typeof c=="function"?u[h.call(c)]||"object":typeof c}var _="3.7.1",M=/HTML$/i,p=function(c,f){return new p.fn.init(c,f)};p.fn=p.prototype={jquery:_,constructor:p,length:0,toArray:function(){return r.call(this)},get:function(c){return c==null?r.call(this):c<0?this[c+this.length]:this[c]},pushStack:function(c){var f=p.merge(this.constructor(),c);return f.prevObject=this,f},each:function(c){return p.each(this,c)},map:function(c){return this.pushStack(p.map(this,function(f,I){return c.call(f,I,f)}))},slice:function(){return this.pushStack(r.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(p.grep(this,function(c,f){return(f+1)%2}))},odd:function(){return this.pushStack(p.grep(this,function(c,f){return f%2}))},eq:function(c){var f=this.length,I=+c+(c<0?f:0);return this.pushStack(I>=0&&I<f?[this[I]]:[])},end:function(){return this.prevObject||this.constructor()},push:o,sort:i.sort,splice:i.splice},p.extend=p.fn.extend=function(){var c,f,I,y,T,S,L=arguments[0]||{},w=1,k=arguments.length,B=!1;for(typeof L=="boolean"&&(B=L,L=arguments[w]||{},w++),typeof L!="object"&&!C(L)&&(L={}),w===k&&(L=this,w--);w<k;w++)if((c=arguments[w])!=null)for(f in c)y=c[f],!(f==="__proto__"||L===y)&&(B&&y&&(p.isPlainObject(y)||(T=Array.isArray(y)))?(I=L[f],T&&!Array.isArray(I)?S=[]:!T&&!p.isPlainObject(I)?S={}:S=I,T=!1,L[f]=p.extend(B,S,y)):y!==void 0&&(L[f]=y));return L},p.extend({expando:"jQuery"+(_+Math.random()).replace(/\D/g,""),isReady:!0,error:function(c){throw new Error(c)},noop:function(){},isPlainObject:function(c){var f,I;return!c||h.call(c)!=="[object Object]"?!1:(f=s(c),f?(I=d.call(f,"constructor")&&f.constructor,typeof I=="function"&&g.call(I)===m):!0)},isEmptyObject:function(c){var f;for(f in c)return!1;return!0},globalEval:function(c,f,I){b(c,{nonce:f&&f.nonce},I)},each:function(c,f){var I,y=0;if($(c))for(I=c.length;y<I&&f.call(c[y],y,c[y])!==!1;y++);else for(y in c)if(f.call(c[y],y,c[y])===!1)break;return c},text:function(c){var f,I="",y=0,T=c.nodeType;if(!T)for(;f=c[y++];)I+=p.text(f);return T===1||T===11?c.textContent:T===9?c.documentElement.textContent:T===3||T===4?c.nodeValue:I},makeArray:function(c,f){var I=f||[];return c!=null&&($(Object(c))?p.merge(I,typeof c=="string"?[c]:c):o.call(I,c)),I},inArray:function(c,f,I){return f==null?-1:l.call(f,c,I)},isXMLDoc:function(c){var f=c&&c.namespaceURI,I=c&&(c.ownerDocument||c).documentElement;return!M.test(f||I&&I.nodeName||"HTML")},merge:function(c,f){for(var I=+f.length,y=0,T=c.length;y<I;y++)c[T++]=f[y];return c.length=T,c},grep:function(c,f,I){for(var y,T=[],S=0,L=c.length,w=!I;S<L;S++)y=!f(c[S],S),y!==w&&T.push(c[S]);return T},map:function(c,f,I){var y,T,S=0,L=[];if($(c))for(y=c.length;S<y;S++)T=f(c[S],S,I),T!=null&&L.push(T);else for(S in c)T=f(c[S],S,I),T!=null&&L.push(T);return a(L)},guid:1,support:A}),typeof Symbol=="function"&&(p.fn[Symbol.iterator]=i[Symbol.iterator]),p.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(c,f){u["[object "+f+"]"]=f.toLowerCase()});function $(c){var f=!!c&&"length"in c&&c.length,I=D(c);return C(c)||v(c)?!1:I==="array"||f===0||typeof f=="number"&&f>0&&f-1 in c}function N(c,f){return c.nodeName&&c.nodeName.toLowerCase()===f.toLowerCase()}var O=i.pop,W=i.sort,q=i.splice,z="[\\x20\\t\\r\\n\\f]",oe=new RegExp("^"+z+"+|((?:^|[^\\\\])(?:\\\\.)*)"+z+"+$","g");p.contains=function(c,f){var I=f&&f.parentNode;return c===I||!!(I&&I.nodeType===1&&(c.contains?c.contains(I):c.compareDocumentPosition&&c.compareDocumentPosition(I)&16))};var re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;function J(c,f){return f?c==="\0"?"�":c.slice(0,-1)+"\\"+c.charCodeAt(c.length-1).toString(16)+" ":"\\"+c}p.escapeSelector=function(c){return(c+"").replace(re,J)};var Z=x,Q=o;(function(){var c,f,I,y,T,S=Q,L,w,k,B,K,X=p.expando,H=0,ie=0,De=Nr(),$e=Nr(),Me=Nr(),It=Nr(),ht=function(P,F){return P===F&&(T=!0),0},ui="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ci="(?:\\\\[\\da-fA-F]{1,6}"+z+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",Ue="\\["+z+"*("+ci+")(?:"+z+"*([*^$|!~]?=)"+z+`*(?:'((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)"|(`+ci+"))|)"+z+"*\\]",Hi=":("+ci+`)(?:\\((('((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)")|((?:\\\\.|[^\\\\()[\\]]|`+Ue+")*)|.*)\\)|)",He=new RegExp(z+"+","g"),ot=new RegExp("^"+z+"*,"+z+"*"),Us=new RegExp("^"+z+"*([>+~]|"+z+")"+z+"*"),Da=new RegExp(z+"|>"),hi=new RegExp(Hi),$s=new RegExp("^"+ci+"$"),di={ID:new RegExp("^#("+ci+")"),CLASS:new RegExp("^\\.("+ci+")"),TAG:new RegExp("^("+ci+"|[*])"),ATTR:new RegExp("^"+Ue),PSEUDO:new RegExp("^"+Hi),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+z+"*(even|odd|(([+-]|)(\\d*)n|)"+z+"*(?:([+-]|)"+z+"*(\\d+)|))"+z+"*\\)|)","i"),bool:new RegExp("^(?:"+ui+")$","i"),needsContext:new RegExp("^"+z+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+z+"*((?:-\\d)?\\d*)"+z+"*\\)|)(?=[^-]|$)","i")},Pi=/^(?:input|select|textarea|button)$/i,_i=/^h\d$/i,Vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Pa=/[+~]/,Ci=new RegExp("\\\\[\\da-fA-F]{1,6}"+z+"?|\\\\([^\\r\\n\\f])","g"),yi=function(P,F){var G="0x"+P.slice(1)-65536;return F||(G<0?String.fromCharCode(G+65536):String.fromCharCode(G>>10|55296,G&1023|56320))},_0=function(){ki()},k0=Ur(function(P){return P.disabled===!0&&N(P,"fieldset")},{dir:"parentNode",next:"legend"});function w0(){try{return L.activeElement}catch{}}try{S.apply(i=r.call(Z.childNodes),Z.childNodes),i[Z.childNodes.length].nodeType}catch{S={apply:function(F,G){Q.apply(F,r.call(G))},call:function(F){Q.apply(F,r.call(arguments,1))}}}function qe(P,F,G,V){var j,ae,de,Ce,fe,Ne,be,Pe=F&&F.ownerDocument,Be=F?F.nodeType:9;if(G=G||[],typeof P!="string"||!P||Be!==1&&Be!==9&&Be!==11)return G;if(!V&&(ki(F),F=F||L,k)){if(Be!==11&&(fe=Vt.exec(P)))if(j=fe[1]){if(Be===9)if(de=F.getElementById(j)){if(de.id===j)return S.call(G,de),G}else return G;else if(Pe&&(de=Pe.getElementById(j))&&qe.contains(F,de)&&de.id===j)return S.call(G,de),G}else{if(fe[2])return S.apply(G,F.getElementsByTagName(P)),G;if((j=fe[3])&&F.getElementsByClassName)return S.apply(G,F.getElementsByClassName(j)),G}if(!It[P+" "]&&(!B||!B.test(P))){if(be=P,Pe=F,Be===1&&(Da.test(P)||Us.test(P))){for(Pe=Pa.test(P)&&_a(F.parentNode)||F,(Pe!=F||!A.scope)&&((Ce=F.getAttribute("id"))?Ce=p.escapeSelector(Ce):F.setAttribute("id",Ce=X)),Ne=Gs(P),ae=Ne.length;ae--;)Ne[ae]=(Ce?"#"+Ce:":scope")+" "+Br(Ne[ae]);be=Ne.join(",")}try{return S.apply(G,Pe.querySelectorAll(be)),G}catch{It(P,!0)}finally{Ce===X&&F.removeAttribute("id")}}}return jc(P.replace(oe,"$1"),F,G,V)}function Nr(){var P=[];function F(G,V){return P.push(G+" ")>f.cacheLength&&delete F[P.shift()],F[G+" "]=V}return F}function Qt(P){return P[X]=!0,P}function ls(P){var F=L.createElement("fieldset");try{return!!P(F)}catch{return!1}finally{F.parentNode&&F.parentNode.removeChild(F),F=null}}function M0(P){return function(F){return N(F,"input")&&F.type===P}}function O0(P){return function(F){return(N(F,"input")||N(F,"button"))&&F.type===P}}function Yc(P){return function(F){return"form"in F?F.parentNode&&F.disabled===!1?"label"in F?"label"in F.parentNode?F.parentNode.disabled===P:F.disabled===P:F.isDisabled===P||F.isDisabled!==!P&&k0(F)===P:F.disabled===P:"label"in F?F.disabled===P:!1}}function Vi(P){return Qt(function(F){return F=+F,Qt(function(G,V){for(var j,ae=P([],G.length,F),de=ae.length;de--;)G[j=ae[de]]&&(G[j]=!(V[j]=G[j]))})})}function _a(P){return P&&typeof P.getElementsByTagName<"u"&&P}function ki(P){var F,G=P?P.ownerDocument||P:Z;return G==L||G.nodeType!==9||!G.documentElement||(L=G,w=L.documentElement,k=!p.isXMLDoc(L),K=w.matches||w.webkitMatchesSelector||w.msMatchesSelector,w.msMatchesSelector&&Z!=L&&(F=L.defaultView)&&F.top!==F&&F.addEventListener("unload",_0),A.getById=ls(function(V){return w.appendChild(V).id=p.expando,!L.getElementsByName||!L.getElementsByName(p.expando).length}),A.disconnectedMatch=ls(function(V){return K.call(V,"*")}),A.scope=ls(function(){return L.querySelectorAll(":scope")}),A.cssHas=ls(function(){try{return L.querySelector(":has(*,:jqfake)"),!1}catch{return!0}}),A.getById?(f.filter.ID=function(V){var j=V.replace(Ci,yi);return function(ae){return ae.getAttribute("id")===j}},f.find.ID=function(V,j){if(typeof j.getElementById<"u"&&k){var ae=j.getElementById(V);return ae?[ae]:[]}}):(f.filter.ID=function(V){var j=V.replace(Ci,yi);return function(ae){var de=typeof ae.getAttributeNode<"u"&&ae.getAttributeNode("id");return de&&de.value===j}},f.find.ID=function(V,j){if(typeof j.getElementById<"u"&&k){var ae,de,Ce,fe=j.getElementById(V);if(fe){if(ae=fe.getAttributeNode("id"),ae&&ae.value===V)return[fe];for(Ce=j.getElementsByName(V),de=0;fe=Ce[de++];)if(ae=fe.getAttributeNode("id"),ae&&ae.value===V)return[fe]}return[]}}),f.find.TAG=function(V,j){return typeof j.getElementsByTagName<"u"?j.getElementsByTagName(V):j.querySelectorAll(V)},f.find.CLASS=function(V,j){if(typeof j.getElementsByClassName<"u"&&k)return j.getElementsByClassName(V)},B=[],ls(function(V){var j;w.appendChild(V).innerHTML="<a id='"+X+"' href='' disabled='disabled'></a><select id='"+X+"-\r\\' disabled='disabled'><option selected=''></option></select>",V.querySelectorAll("[selected]").length||B.push("\\["+z+"*(?:value|"+ui+")"),V.querySelectorAll("[id~="+X+"-]").length||B.push("~="),V.querySelectorAll("a#"+X+"+*").length||B.push(".#.+[+~]"),V.querySelectorAll(":checked").length||B.push(":checked"),j=L.createElement("input"),j.setAttribute("type","hidden"),V.appendChild(j).setAttribute("name","D"),w.appendChild(V).disabled=!0,V.querySelectorAll(":disabled").length!==2&&B.push(":enabled",":disabled"),j=L.createElement("input"),j.setAttribute("name",""),V.appendChild(j),V.querySelectorAll("[name='']").length||B.push("\\["+z+"*name"+z+"*="+z+`*(?:''|"")`)}),A.cssHas||B.push(":has"),B=B.length&&new RegExp(B.join("|")),ht=function(V,j){if(V===j)return T=!0,0;var ae=!V.compareDocumentPosition-!j.compareDocumentPosition;return ae||(ae=(V.ownerDocument||V)==(j.ownerDocument||j)?V.compareDocumentPosition(j):1,ae&1||!A.sortDetached&&j.compareDocumentPosition(V)===ae?V===L||V.ownerDocument==Z&&qe.contains(Z,V)?-1:j===L||j.ownerDocument==Z&&qe.contains(Z,j)?1:y?l.call(y,V)-l.call(y,j):0:ae&4?-1:1)}),L}qe.matches=function(P,F){return qe(P,null,null,F)},qe.matchesSelector=function(P,F){if(ki(P),k&&!It[F+" "]&&(!B||!B.test(F)))try{var G=K.call(P,F);if(G||A.disconnectedMatch||P.document&&P.document.nodeType!==11)return G}catch{It(F,!0)}return qe(F,L,null,[P]).length>0},qe.contains=function(P,F){return(P.ownerDocument||P)!=L&&ki(P),p.contains(P,F)},qe.attr=function(P,F){(P.ownerDocument||P)!=L&&ki(P);var G=f.attrHandle[F.toLowerCase()],V=G&&d.call(f.attrHandle,F.toLowerCase())?G(P,F,!k):void 0;return V!==void 0?V:P.getAttribute(F)},qe.error=function(P){throw new Error("Syntax error, unrecognized expression: "+P)},p.uniqueSort=function(P){var F,G=[],V=0,j=0;if(T=!A.sortStable,y=!A.sortStable&&r.call(P,0),W.call(P,ht),T){for(;F=P[j++];)F===P[j]&&(V=G.push(j));for(;V--;)q.call(P,G[V],1)}return y=null,P},p.fn.uniqueSort=function(){return this.pushStack(p.uniqueSort(r.apply(this)))},f=p.expr={cacheLength:50,createPseudo:Qt,match:di,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(P){return P[1]=P[1].replace(Ci,yi),P[3]=(P[3]||P[4]||P[5]||"").replace(Ci,yi),P[2]==="~="&&(P[3]=" "+P[3]+" "),P.slice(0,4)},CHILD:function(P){return P[1]=P[1].toLowerCase(),P[1].slice(0,3)==="nth"?(P[3]||qe.error(P[0]),P[4]=+(P[4]?P[5]+(P[6]||1):2*(P[3]==="even"||P[3]==="odd")),P[5]=+(P[7]+P[8]||P[3]==="odd")):P[3]&&qe.error(P[0]),P},PSEUDO:function(P){var F,G=!P[6]&&P[2];return di.CHILD.test(P[0])?null:(P[3]?P[2]=P[4]||P[5]||"":G&&hi.test(G)&&(F=Gs(G,!0))&&(F=G.indexOf(")",G.length-F)-G.length)&&(P[0]=P[0].slice(0,F),P[2]=G.slice(0,F)),P.slice(0,3))}},filter:{TAG:function(P){var F=P.replace(Ci,yi).toLowerCase();return P==="*"?function(){return!0}:function(G){return N(G,F)}},CLASS:function(P){var F=De[P+" "];return F||(F=new RegExp("(^|"+z+")"+P+"("+z+"|$)"))&&De(P,function(G){return F.test(typeof G.className=="string"&&G.className||typeof G.getAttribute<"u"&&G.getAttribute("class")||"")})},ATTR:function(P,F,G){return function(V){var j=qe.attr(V,P);return j==null?F==="!=":F?(j+="",F==="="?j===G:F==="!="?j!==G:F==="^="?G&&j.indexOf(G)===0:F==="*="?G&&j.indexOf(G)>-1:F==="$="?G&&j.slice(-G.length)===G:F==="~="?(" "+j.replace(He," ")+" ").indexOf(G)>-1:F==="|="?j===G||j.slice(0,G.length+1)===G+"-":!1):!0}},CHILD:function(P,F,G,V,j){var ae=P.slice(0,3)!=="nth",de=P.slice(-4)!=="last",Ce=F==="of-type";return V===1&&j===0?function(fe){return!!fe.parentNode}:function(fe,Ne,be){var Pe,Be,Se,Qe,kt,vt=ae!==de?"nextSibling":"previousSibling",Kt=fe.parentNode,fi=Ce&&fe.nodeName.toLowerCase(),us=!be&&!Ce,bt=!1;if(Kt){if(ae){for(;vt;){for(Se=fe;Se=Se[vt];)if(Ce?N(Se,fi):Se.nodeType===1)return!1;kt=vt=P==="only"&&!kt&&"nextSibling"}return!0}if(kt=[de?Kt.firstChild:Kt.lastChild],de&&us){for(Be=Kt[X]||(Kt[X]={}),Pe=Be[P]||[],Qe=Pe[0]===H&&Pe[1],bt=Qe&&Pe[2],Se=Qe&&Kt.childNodes[Qe];Se=++Qe&&Se&&Se[vt]||(bt=Qe=0)||kt.pop();)if(Se.nodeType===1&&++bt&&Se===fe){Be[P]=[H,Qe,bt];break}}else if(us&&(Be=fe[X]||(fe[X]={}),Pe=Be[P]||[],Qe=Pe[0]===H&&Pe[1],bt=Qe),bt===!1)for(;(Se=++Qe&&Se&&Se[vt]||(bt=Qe=0)||kt.pop())&&!((Ce?N(Se,fi):Se.nodeType===1)&&++bt&&(us&&(Be=Se[X]||(Se[X]={}),Be[P]=[H,bt]),Se===fe)););return bt-=j,bt===V||bt%V===0&&bt/V>=0}}},PSEUDO:function(P,F){var G,V=f.pseudos[P]||f.setFilters[P.toLowerCase()]||qe.error("unsupported pseudo: "+P);return V[X]?V(F):V.length>1?(G=[P,P,"",F],f.setFilters.hasOwnProperty(P.toLowerCase())?Qt(function(j,ae){for(var de,Ce=V(j,F),fe=Ce.length;fe--;)de=l.call(j,Ce[fe]),j[de]=!(ae[de]=Ce[fe])}):function(j){return V(j,0,G)}):V}},pseudos:{not:Qt(function(P){var F=[],G=[],V=Oa(P.replace(oe,"$1"));return V[X]?Qt(function(j,ae,de,Ce){for(var fe,Ne=V(j,null,Ce,[]),be=j.length;be--;)(fe=Ne[be])&&(j[be]=!(ae[be]=fe))}):function(j,ae,de){return F[0]=j,V(F,null,de,G),F[0]=null,!G.pop()}}),has:Qt(function(P){return function(F){return qe(P,F).length>0}}),contains:Qt(function(P){return P=P.replace(Ci,yi),function(F){return(F.textContent||p.text(F)).indexOf(P)>-1}}),lang:Qt(function(P){return $s.test(P||"")||qe.error("unsupported lang: "+P),P=P.replace(Ci,yi).toLowerCase(),function(F){var G;do if(G=k?F.lang:F.getAttribute("xml:lang")||F.getAttribute("lang"))return G=G.toLowerCase(),G===P||G.indexOf(P+"-")===0;while((F=F.parentNode)&&F.nodeType===1);return!1}}),target:function(P){var F=e.location&&e.location.hash;return F&&F.slice(1)===P.id},root:function(P){return P===w},focus:function(P){return P===w0()&&L.hasFocus()&&!!(P.type||P.href||~P.tabIndex)},enabled:Yc(!1),disabled:Yc(!0),checked:function(P){return N(P,"input")&&!!P.checked||N(P,"option")&&!!P.selected},selected:function(P){return P.parentNode&&P.parentNode.selectedIndex,P.selected===!0},empty:function(P){for(P=P.firstChild;P;P=P.nextSibling)if(P.nodeType<6)return!1;return!0},parent:function(P){return!f.pseudos.empty(P)},header:function(P){return _i.test(P.nodeName)},input:function(P){return Pi.test(P.nodeName)},button:function(P){return N(P,"input")&&P.type==="button"||N(P,"button")},text:function(P){var F;return N(P,"input")&&P.type==="text"&&((F=P.getAttribute("type"))==null||F.toLowerCase()==="text")},first:Vi(function(){return[0]}),last:Vi(function(P,F){return[F-1]}),eq:Vi(function(P,F,G){return[G<0?G+F:G]}),even:Vi(function(P,F){for(var G=0;G<F;G+=2)P.push(G);return P}),odd:Vi(function(P,F){for(var G=1;G<F;G+=2)P.push(G);return P}),lt:Vi(function(P,F,G){var V;for(G<0?V=G+F:G>F?V=F:V=G;--V>=0;)P.push(V);return P}),gt:Vi(function(P,F,G){for(var V=G<0?G+F:G;++V<F;)P.push(V);return P})}},f.pseudos.nth=f.pseudos.eq;for(c in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})f.pseudos[c]=M0(c);for(c in{submit:!0,reset:!0})f.pseudos[c]=O0(c);function Wc(){}Wc.prototype=f.filters=f.pseudos,f.setFilters=new Wc;function Gs(P,F){var G,V,j,ae,de,Ce,fe,Ne=$e[P+" "];if(Ne)return F?0:Ne.slice(0);for(de=P,Ce=[],fe=f.preFilter;de;){(!G||(V=ot.exec(de)))&&(V&&(de=de.slice(V[0].length)||de),Ce.push(j=[])),G=!1,(V=Us.exec(de))&&(G=V.shift(),j.push({value:G,type:V[0].replace(oe," ")}),de=de.slice(G.length));for(ae in f.filter)(V=di[ae].exec(de))&&(!fe[ae]||(V=fe[ae](V)))&&(G=V.shift(),j.push({value:G,type:ae,matches:V}),de=de.slice(G.length));if(!G)break}return F?de.length:de?qe.error(P):$e(P,Ce).slice(0)}function Br(P){for(var F=0,G=P.length,V="";F<G;F++)V+=P[F].value;return V}function Ur(P,F,G){var V=F.dir,j=F.next,ae=j||V,de=G&&ae==="parentNode",Ce=ie++;return F.first?function(fe,Ne,be){for(;fe=fe[V];)if(fe.nodeType===1||de)return P(fe,Ne,be);return!1}:function(fe,Ne,be){var Pe,Be,Se=[H,Ce];if(be){for(;fe=fe[V];)if((fe.nodeType===1||de)&&P(fe,Ne,be))return!0}else for(;fe=fe[V];)if(fe.nodeType===1||de)if(Be=fe[X]||(fe[X]={}),j&&N(fe,j))fe=fe[V]||fe;else{if((Pe=Be[ae])&&Pe[0]===H&&Pe[1]===Ce)return Se[2]=Pe[2];if(Be[ae]=Se,Se[2]=P(fe,Ne,be))return!0}return!1}}function ka(P){return P.length>1?function(F,G,V){for(var j=P.length;j--;)if(!P[j](F,G,V))return!1;return!0}:P[0]}function F0(P,F,G){for(var V=0,j=F.length;V<j;V++)qe(P,F[V],G);return G}function $r(P,F,G,V,j){for(var ae,de=[],Ce=0,fe=P.length,Ne=F!=null;Ce<fe;Ce++)(ae=P[Ce])&&(!G||G(ae,V,j))&&(de.push(ae),Ne&&F.push(Ce));return de}function wa(P,F,G,V,j,ae){return V&&!V[X]&&(V=wa(V)),j&&!j[X]&&(j=wa(j,ae)),Qt(function(de,Ce,fe,Ne){var be,Pe,Be,Se,Qe=[],kt=[],vt=Ce.length,Kt=de||F0(F||"*",fe.nodeType?[fe]:fe,[]),fi=P&&(de||!F)?$r(Kt,Qe,P,fe,Ne):Kt;if(G?(Se=j||(de?P:vt||V)?[]:Ce,G(fi,Se,fe,Ne)):Se=fi,V)for(be=$r(Se,kt),V(be,[],fe,Ne),Pe=be.length;Pe--;)(Be=be[Pe])&&(Se[kt[Pe]]=!(fi[kt[Pe]]=Be));if(de){if(j||P){if(j){for(be=[],Pe=Se.length;Pe--;)(Be=Se[Pe])&&be.push(fi[Pe]=Be);j(null,Se=[],be,Ne)}for(Pe=Se.length;Pe--;)(Be=Se[Pe])&&(be=j?l.call(de,Be):Qe[Pe])>-1&&(de[be]=!(Ce[be]=Be))}}else Se=$r(Se===Ce?Se.splice(vt,Se.length):Se),j?j(null,Ce,Se,Ne):S.apply(Ce,Se)})}function Ma(P){for(var F,G,V,j=P.length,ae=f.relative[P[0].type],de=ae||f.relative[" "],Ce=ae?1:0,fe=Ur(function(Pe){return Pe===F},de,!0),Ne=Ur(function(Pe){return l.call(F,Pe)>-1},de,!0),be=[function(Pe,Be,Se){var Qe=!ae&&(Se||Be!=I)||((F=Be).nodeType?fe(Pe,Be,Se):Ne(Pe,Be,Se));return F=null,Qe}];Ce<j;Ce++)if(G=f.relative[P[Ce].type])be=[Ur(ka(be),G)];else{if(G=f.filter[P[Ce].type].apply(null,P[Ce].matches),G[X]){for(V=++Ce;V<j&&!f.relative[P[V].type];V++);return wa(Ce>1&&ka(be),Ce>1&&Br(P.slice(0,Ce-1).concat({value:P[Ce-2].type===" "?"*":""})).replace(oe,"$1"),G,Ce<V&&Ma(P.slice(Ce,V)),V<j&&Ma(P=P.slice(V)),V<j&&Br(P))}be.push(G)}return ka(be)}function N0(P,F){var G=F.length>0,V=P.length>0,j=function(ae,de,Ce,fe,Ne){var be,Pe,Be,Se=0,Qe="0",kt=ae&&[],vt=[],Kt=I,fi=ae||V&&f.find.TAG("*",Ne),us=H+=Kt==null?1:Math.random()||.1,bt=fi.length;for(Ne&&(I=de==L||de||Ne);Qe!==bt&&(be=fi[Qe])!=null;Qe++){if(V&&be){for(Pe=0,!de&&be.ownerDocument!=L&&(ki(be),Ce=!k);Be=P[Pe++];)if(Be(be,de||L,Ce)){S.call(fe,be);break}Ne&&(H=us)}G&&((be=!Be&&be)&&Se--,ae&&kt.push(be))}if(Se+=Qe,G&&Qe!==Se){for(Pe=0;Be=F[Pe++];)Be(kt,vt,de,Ce);if(ae){if(Se>0)for(;Qe--;)kt[Qe]||vt[Qe]||(vt[Qe]=O.call(fe));vt=$r(vt)}S.apply(fe,vt),Ne&&!ae&&vt.length>0&&Se+F.length>1&&p.uniqueSort(fe)}return Ne&&(H=us,I=Kt),kt};return G?Qt(j):j}function Oa(P,F){var G,V=[],j=[],ae=Me[P+" "];if(!ae){for(F||(F=Gs(P)),G=F.length;G--;)ae=Ma(F[G]),ae[X]?V.push(ae):j.push(ae);ae=Me(P,N0(j,V)),ae.selector=P}return ae}function jc(P,F,G,V){var j,ae,de,Ce,fe,Ne=typeof P=="function"&&P,be=!V&&Gs(P=Ne.selector||P);if(G=G||[],be.length===1){if(ae=be[0]=be[0].slice(0),ae.length>2&&(de=ae[0]).type==="ID"&&F.nodeType===9&&k&&f.relative[ae[1].type]){if(F=(f.find.ID(de.matches[0].replace(Ci,yi),F)||[])[0],F)Ne&&(F=F.parentNode);else return G;P=P.slice(ae.shift().value.length)}for(j=di.needsContext.test(P)?0:ae.length;j--&&(de=ae[j],!f.relative[Ce=de.type]);)if((fe=f.find[Ce])&&(V=fe(de.matches[0].replace(Ci,yi),Pa.test(ae[0].type)&&_a(F.parentNode)||F))){if(ae.splice(j,1),P=V.length&&Br(ae),!P)return S.apply(G,V),G;break}}return(Ne||Oa(P,be))(V,F,!k,G,!F||Pa.test(P)&&_a(F.parentNode)||F),G}A.sortStable=X.split("").sort(ht).join("")===X,ki(),A.sortDetached=ls(function(P){return P.compareDocumentPosition(L.createElement("fieldset"))&1}),p.find=qe,p.expr[":"]=p.expr.pseudos,p.unique=p.uniqueSort,qe.compile=Oa,qe.select=jc,qe.setDocument=ki,qe.tokenize=Gs,qe.escape=p.escapeSelector,qe.getText=p.text,qe.isXML=p.isXMLDoc,qe.selectors=p.expr,qe.support=p.support,qe.uniqueSort=p.uniqueSort})();var ee=function(c,f,I){for(var y=[],T=I!==void 0;(c=c[f])&&c.nodeType!==9;)if(c.nodeType===1){if(T&&p(c).is(I))break;y.push(c)}return y},he=function(c,f){for(var I=[];c;c=c.nextSibling)c.nodeType===1&&c!==f&&I.push(c);return I},te=p.expr.match.needsContext,ne=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function Ee(c,f,I){return C(f)?p.grep(c,function(y,T){return!!f.call(y,T,y)!==I}):f.nodeType?p.grep(c,function(y){return y===f!==I}):typeof f!="string"?p.grep(c,function(y){return l.call(f,y)>-1!==I}):p.filter(f,c,I)}p.filter=function(c,f,I){var y=f[0];return I&&(c=":not("+c+")"),f.length===1&&y.nodeType===1?p.find.matchesSelector(y,c)?[y]:[]:p.find.matches(c,p.grep(f,function(T){return T.nodeType===1}))},p.fn.extend({find:function(c){var f,I,y=this.length,T=this;if(typeof c!="string")return this.pushStack(p(c).filter(function(){for(f=0;f<y;f++)if(p.contains(T[f],this))return!0}));for(I=this.pushStack([]),f=0;f<y;f++)p.find(c,T[f],I);return y>1?p.uniqueSort(I):I},filter:function(c){return this.pushStack(Ee(this,c||[],!1))},not:function(c){return this.pushStack(Ee(this,c||[],!0))},is:function(c){return!!Ee(this,typeof c=="string"&&te.test(c)?p(c):c||[],!1).length}});var Ie,_e=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,ye=p.fn.init=function(c,f,I){var y,T;if(!c)return this;if(I=I||Ie,typeof c=="string")if(c[0]==="<"&&c[c.length-1]===">"&&c.length>=3?y=[null,c,null]:y=_e.exec(c),y&&(y[1]||!f))if(y[1]){if(f=f instanceof p?f[0]:f,p.merge(this,p.parseHTML(y[1],f&&f.nodeType?f.ownerDocument||f:x,!0)),ne.test(y[1])&&p.isPlainObject(f))for(y in f)C(this[y])?this[y](f[y]):this.attr(y,f[y]);return this}else return T=x.getElementById(y[2]),T&&(this[0]=T,this.length=1),this;else return!f||f.jquery?(f||I).find(c):this.constructor(f).find(c);else{if(c.nodeType)return this[0]=c,this.length=1,this;if(C(c))return I.ready!==void 0?I.ready(c):c(p)}return p.makeArray(c,this)};ye.prototype=p.fn,Ie=p(x);var Oe=/^(?:parents|prev(?:Until|All))/,Le={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({has:function(c){var f=p(c,this),I=f.length;return this.filter(function(){for(var y=0;y<I;y++)if(p.contains(this,f[y]))return!0})},closest:function(c,f){var I,y=0,T=this.length,S=[],L=typeof c!="string"&&p(c);if(!te.test(c)){for(;y<T;y++)for(I=this[y];I&&I!==f;I=I.parentNode)if(I.nodeType<11&&(L?L.index(I)>-1:I.nodeType===1&&p.find.matchesSelector(I,c))){S.push(I);break}}return this.pushStack(S.length>1?p.uniqueSort(S):S)},index:function(c){return c?typeof c=="string"?l.call(p(c),this[0]):l.call(this,c.jquery?c[0]:c):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(c,f){return this.pushStack(p.uniqueSort(p.merge(this.get(),p(c,f))))},addBack:function(c){return this.add(c==null?this.prevObject:this.prevObject.filter(c))}});function Fe(c,f){for(;(c=c[f])&&c.nodeType!==1;);return c}p.each({parent:function(c){var f=c.parentNode;return f&&f.nodeType!==11?f:null},parents:function(c){return ee(c,"parentNode")},parentsUntil:function(c,f,I){return ee(c,"parentNode",I)},next:function(c){return Fe(c,"nextSibling")},prev:function(c){return Fe(c,"previousSibling")},nextAll:function(c){return ee(c,"nextSibling")},prevAll:function(c){return ee(c,"previousSibling")},nextUntil:function(c,f,I){return ee(c,"nextSibling",I)},prevUntil:function(c,f,I){return ee(c,"previousSibling",I)},siblings:function(c){return he((c.parentNode||{}).firstChild,c)},children:function(c){return he(c.firstChild)},contents:function(c){return c.contentDocument!=null&&s(c.contentDocument)?c.contentDocument:(N(c,"template")&&(c=c.content||c),p.merge([],c.childNodes))}},function(c,f){p.fn[c]=function(I,y){var T=p.map(this,f,I);return c.slice(-5)!=="Until"&&(y=I),y&&typeof y=="string"&&(T=p.filter(y,T)),this.length>1&&(Le[c]||p.uniqueSort(T),Oe.test(c)&&T.reverse()),this.pushStack(T)}});var Ye=/[^\x20\t\r\n\f]+/g;function Ct(c){var f={};return p.each(c.match(Ye)||[],function(I,y){f[y]=!0}),f}p.Callbacks=function(c){c=typeof c=="string"?Ct(c):p.extend({},c);var f,I,y,T,S=[],L=[],w=-1,k=function(){for(T=T||c.once,y=f=!0;L.length;w=-1)for(I=L.shift();++w<S.length;)S[w].apply(I[0],I[1])===!1&&c.stopOnFalse&&(w=S.length,I=!1);c.memory||(I=!1),f=!1,T&&(I?S=[]:S="")},B={add:function(){return S&&(I&&!f&&(w=S.length-1,L.push(I)),(function K(X){p.each(X,function(H,ie){C(ie)?(!c.unique||!B.has(ie))&&S.push(ie):ie&&ie.length&&D(ie)!=="string"&&K(ie)})})(arguments),I&&!f&&k()),this},remove:function(){return p.each(arguments,function(K,X){for(var H;(H=p.inArray(X,S,H))>-1;)S.splice(H,1),H<=w&&w--}),this},has:function(K){return K?p.inArray(K,S)>-1:S.length>0},empty:function(){return S&&(S=[]),this},disable:function(){return T=L=[],S=I="",this},disabled:function(){return!S},lock:function(){return T=L=[],!I&&!f&&(S=I=""),this},locked:function(){return!!T},fireWith:function(K,X){return T||(X=X||[],X=[K,X.slice?X.slice():X],L.push(X),f||k()),this},fire:function(){return B.fireWith(this,arguments),this},fired:function(){return!!y}};return B};function yt(c){return c}function We(c){throw c}function St(c,f,I,y){var T;try{c&&C(T=c.promise)?T.call(c).done(f).fail(I):c&&C(T=c.then)?T.call(c,f,I):f.apply(void 0,[c].slice(y))}catch(S){I.apply(void 0,[S])}}p.extend({Deferred:function(c){var f=[["notify","progress",p.Callbacks("memory"),p.Callbacks("memory"),2],["resolve","done",p.Callbacks("once memory"),p.Callbacks("once memory"),0,"resolved"],["reject","fail",p.Callbacks("once memory"),p.Callbacks("once memory"),1,"rejected"]],I="pending",y={state:function(){return I},always:function(){return T.done(arguments).fail(arguments),this},catch:function(S){return y.then(null,S)},pipe:function(){var S=arguments;return p.Deferred(function(L){p.each(f,function(w,k){var B=C(S[k[4]])&&S[k[4]];T[k[1]](function(){var K=B&&B.apply(this,arguments);K&&C(K.promise)?K.promise().progress(L.notify).done(L.resolve).fail(L.reject):L[k[0]+"With"](this,B?[K]:arguments)})}),S=null}).promise()},then:function(S,L,w){var k=0;function B(K,X,H,ie){return function(){var De=this,$e=arguments,Me=function(){var ht,ui;if(!(K<k)){if(ht=H.apply(De,$e),ht===X.promise())throw new TypeError("Thenable self-resolution");ui=ht&&(typeof ht=="object"||typeof ht=="function")&&ht.then,C(ui)?ie?ui.call(ht,B(k,X,yt,ie),B(k,X,We,ie)):(k++,ui.call(ht,B(k,X,yt,ie),B(k,X,We,ie),B(k,X,yt,X.notifyWith))):(H!==yt&&(De=void 0,$e=[ht]),(ie||X.resolveWith)(De,$e))}},It=ie?Me:function(){try{Me()}catch(ht){p.Deferred.exceptionHook&&p.Deferred.exceptionHook(ht,It.error),K+1>=k&&(H!==We&&(De=void 0,$e=[ht]),X.rejectWith(De,$e))}};K?It():(p.Deferred.getErrorHook?It.error=p.Deferred.getErrorHook():p.Deferred.getStackHook&&(It.error=p.Deferred.getStackHook()),e.setTimeout(It))}}return p.Deferred(function(K){f[0][3].add(B(0,K,C(w)?w:yt,K.notifyWith)),f[1][3].add(B(0,K,C(S)?S:yt)),f[2][3].add(B(0,K,C(L)?L:We))}).promise()},promise:function(S){return S!=null?p.extend(S,y):y}},T={};return p.each(f,function(S,L){var w=L[2],k=L[5];y[L[1]]=w.add,k&&w.add(function(){I=k},f[3-S][2].disable,f[3-S][3].disable,f[0][2].lock,f[0][3].lock),w.add(L[3].fire),T[L[0]]=function(){return T[L[0]+"With"](this===T?void 0:this,arguments),this},T[L[0]+"With"]=w.fireWith}),y.promise(T),c&&c.call(T,T),T},when:function(c){var f=arguments.length,I=f,y=Array(I),T=r.call(arguments),S=p.Deferred(),L=function(w){return function(k){y[w]=this,T[w]=arguments.length>1?r.call(arguments):k,--f||S.resolveWith(y,T)}};if(f<=1&&(St(c,S.done(L(I)).resolve,S.reject,!f),S.state()==="pending"||C(T[I]&&T[I].then)))return S.then();for(;I--;)St(T[I],L(I),S.reject);return S.promise()}});var $t=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;p.Deferred.exceptionHook=function(c,f){e.console&&e.console.warn&&c&&$t.test(c.name)&&e.console.warn("jQuery.Deferred exception: "+c.message,c.stack,f)},p.readyException=function(c){e.setTimeout(function(){throw c})};var pe=p.Deferred();p.fn.ready=function(c){return pe.then(c).catch(function(f){p.readyException(f)}),this},p.extend({isReady:!1,readyWait:1,ready:function(c){(c===!0?--p.readyWait:p.isReady)||(p.isReady=!0,!(c!==!0&&--p.readyWait>0)&&pe.resolveWith(x,[p]))}}),p.ready.then=pe.then;function we(){x.removeEventListener("DOMContentLoaded",we),e.removeEventListener("load",we),p.ready()}x.readyState==="complete"||x.readyState!=="loading"&&!x.documentElement.doScroll?e.setTimeout(p.ready):(x.addEventListener("DOMContentLoaded",we),e.addEventListener("load",we));var Re=function(c,f,I,y,T,S,L){var w=0,k=c.length,B=I==null;if(D(I)==="object"){T=!0;for(w in I)Re(c,f,w,I[w],!0,S,L)}else if(y!==void 0&&(T=!0,C(y)||(L=!0),B&&(L?(f.call(c,y),f=null):(B=f,f=function(K,X,H){return B.call(p(K),H)})),f))for(;w<k;w++)f(c[w],I,L?y:y.call(c[w],w,f(c[w],I)));return T?c:B?f.call(c):k?f(c[0],I):S},nt=/^-ms-/,it=/-([a-z])/g;function At(c,f){return f.toUpperCase()}function at(c){return c.replace(nt,"ms-").replace(it,At)}var Nt=function(c){return c.nodeType===1||c.nodeType===9||!+c.nodeType};function rt(){this.expando=p.expando+rt.uid++}rt.uid=1,rt.prototype={cache:function(c){var f=c[this.expando];return f||(f={},Nt(c)&&(c.nodeType?c[this.expando]=f:Object.defineProperty(c,this.expando,{value:f,configurable:!0}))),f},set:function(c,f,I){var y,T=this.cache(c);if(typeof f=="string")T[at(f)]=I;else for(y in f)T[at(y)]=f[y];return T},get:function(c,f){return f===void 0?this.cache(c):c[this.expando]&&c[this.expando][at(f)]},access:function(c,f,I){return f===void 0||f&&typeof f=="string"&&I===void 0?this.get(c,f):(this.set(c,f,I),I!==void 0?I:f)},remove:function(c,f){var I,y=c[this.expando];if(y!==void 0){if(f!==void 0)for(Array.isArray(f)?f=f.map(at):(f=at(f),f=f in y?[f]:f.match(Ye)||[]),I=f.length;I--;)delete y[f[I]];(f===void 0||p.isEmptyObject(y))&&(c.nodeType?c[this.expando]=void 0:delete c[this.expando])}},hasData:function(c){var f=c[this.expando];return f!==void 0&&!p.isEmptyObject(f)}};var ue=new rt,Ze=new rt,xt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ft=/[A-Z]/g;function li(c){return c==="true"?!0:c==="false"?!1:c==="null"?null:c===+c+""?+c:xt.test(c)?JSON.parse(c):c}function Gt(c,f,I){var y;if(I===void 0&&c.nodeType===1)if(y="data-"+f.replace(ft,"-$&").toLowerCase(),I=c.getAttribute(y),typeof I=="string"){try{I=li(I)}catch{}Ze.set(c,f,I)}else I=void 0;return I}p.extend({hasData:function(c){return Ze.hasData(c)||ue.hasData(c)},data:function(c,f,I){return Ze.access(c,f,I)},removeData:function(c,f){Ze.remove(c,f)},_data:function(c,f,I){return ue.access(c,f,I)},_removeData:function(c,f){ue.remove(c,f)}}),p.fn.extend({data:function(c,f){var I,y,T,S=this[0],L=S&&S.attributes;if(c===void 0){if(this.length&&(T=Ze.get(S),S.nodeType===1&&!ue.get(S,"hasDataAttrs"))){for(I=L.length;I--;)L[I]&&(y=L[I].name,y.indexOf("data-")===0&&(y=at(y.slice(5)),Gt(S,y,T[y])));ue.set(S,"hasDataAttrs",!0)}return T}return typeof c=="object"?this.each(function(){Ze.set(this,c)}):Re(this,function(w){var k;if(S&&w===void 0)return k=Ze.get(S,c),k!==void 0||(k=Gt(S,c),k!==void 0)?k:void 0;this.each(function(){Ze.set(this,c,w)})},null,f,arguments.length>1,null,!0)},removeData:function(c){return this.each(function(){Ze.remove(this,c)})}}),p.extend({queue:function(c,f,I){var y;if(c)return f=(f||"fx")+"queue",y=ue.get(c,f),I&&(!y||Array.isArray(I)?y=ue.access(c,f,p.makeArray(I)):y.push(I)),y||[]},dequeue:function(c,f){f=f||"fx";var I=p.queue(c,f),y=I.length,T=I.shift(),S=p._queueHooks(c,f),L=function(){p.dequeue(c,f)};T==="inprogress"&&(T=I.shift(),y--),T&&(f==="fx"&&I.unshift("inprogress"),delete S.stop,T.call(c,L,S)),!y&&S&&S.empty.fire()},_queueHooks:function(c,f){var I=f+"queueHooks";return ue.get(c,I)||ue.access(c,I,{empty:p.Callbacks("once memory").add(function(){ue.remove(c,[f+"queue",I])})})}}),p.fn.extend({queue:function(c,f){var I=2;return typeof c!="string"&&(f=c,c="fx",I--),arguments.length<I?p.queue(this[0],c):f===void 0?this:this.each(function(){var y=p.queue(this,c,f);p._queueHooks(this,c),c==="fx"&&y[0]!=="inprogress"&&p.dequeue(this,c)})},dequeue:function(c){return this.each(function(){p.dequeue(this,c)})},clearQueue:function(c){return this.queue(c||"fx",[])},promise:function(c,f){var I,y=1,T=p.Deferred(),S=this,L=this.length,w=function(){--y||T.resolveWith(S,[S])};for(typeof c!="string"&&(f=c,c=void 0),c=c||"fx";L--;)I=ue.get(S[L],c+"queueHooks"),I&&I.empty&&(y++,I.empty.add(w));return w(),T.promise(f)}});var Dt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Di=new RegExp("^(?:([+-])=|)("+Dt+")([a-z%]*)$","i"),Ii=["Top","Right","Bottom","Left"],Ui=x.documentElement,is=function(c){return p.contains(c.ownerDocument,c)},zm={composed:!0};Ui.getRootNode&&(is=function(c){return p.contains(c.ownerDocument,c)||c.getRootNode(zm)===c.ownerDocument});var kr=function(c,f){return c=f||c,c.style.display==="none"||c.style.display===""&&is(c)&&p.css(c,"display")==="none"};function mc(c,f,I,y){var T,S,L=20,w=y?function(){return y.cur()}:function(){return p.css(c,f,"")},k=w(),B=I&&I[3]||(p.cssNumber[f]?"":"px"),K=c.nodeType&&(p.cssNumber[f]||B!=="px"&&+k)&&Di.exec(p.css(c,f));if(K&&K[3]!==B){for(k=k/2,B=B||K[3],K=+k||1;L--;)p.style(c,f,K+B),(1-S)*(1-(S=w()/k||.5))<=0&&(L=0),K=K/S;K=K*2,p.style(c,f,K+B),I=I||[]}return I&&(K=+K||+k||0,T=I[1]?K+(I[1]+1)*I[2]:+I[2],y&&(y.unit=B,y.start=K,y.end=T)),T}var Ac={};function Xm(c){var f,I=c.ownerDocument,y=c.nodeName,T=Ac[y];return T||(f=I.body.appendChild(I.createElement(y)),T=p.css(f,"display"),f.parentNode.removeChild(f),T==="none"&&(T="block"),Ac[y]=T,T)}function ss(c,f){for(var I,y,T=[],S=0,L=c.length;S<L;S++)y=c[S],y.style&&(I=y.style.display,f?(I==="none"&&(T[S]=ue.get(y,"display")||null,T[S]||(y.style.display="")),y.style.display===""&&kr(y)&&(T[S]=Xm(y))):I!=="none"&&(T[S]="none",ue.set(y,"display",I)));for(S=0;S<L;S++)T[S]!=null&&(c[S].style.display=T[S]);return c}p.fn.extend({show:function(){return ss(this,!0)},hide:function(){return ss(this)},toggle:function(c){return typeof c=="boolean"?c?this.show():this.hide():this.each(function(){kr(this)?p(this).show():p(this).hide()})}});var Ms=/^(?:checkbox|radio)$/i,Ic=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,Cc=/^$|^module$|\/(?:java|ecma)script/i;(function(){var c=x.createDocumentFragment(),f=c.appendChild(x.createElement("div")),I=x.createElement("input");I.setAttribute("type","radio"),I.setAttribute("checked","checked"),I.setAttribute("name","t"),f.appendChild(I),A.checkClone=f.cloneNode(!0).cloneNode(!0).lastChild.checked,f.innerHTML="<textarea>x</textarea>",A.noCloneChecked=!!f.cloneNode(!0).lastChild.defaultValue,f.innerHTML="<option></option>",A.option=!!f.lastChild})();var Ht={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Ht.tbody=Ht.tfoot=Ht.colgroup=Ht.caption=Ht.thead,Ht.th=Ht.td,A.option||(Ht.optgroup=Ht.option=[1,"<select multiple='multiple'>","</select>"]);function Pt(c,f){var I;return typeof c.getElementsByTagName<"u"?I=c.getElementsByTagName(f||"*"):typeof c.querySelectorAll<"u"?I=c.querySelectorAll(f||"*"):I=[],f===void 0||f&&N(c,f)?p.merge([c],I):I}function pa(c,f){for(var I=0,y=c.length;I<y;I++)ue.set(c[I],"globalEval",!f||ue.get(f[I],"globalEval"))}var Zm=/<|&#?\w+;/;function yc(c,f,I,y,T){for(var S,L,w,k,B,K,X=f.createDocumentFragment(),H=[],ie=0,De=c.length;ie<De;ie++)if(S=c[ie],S||S===0)if(D(S)==="object")p.merge(H,S.nodeType?[S]:S);else if(!Zm.test(S))H.push(f.createTextNode(S));else{for(L=L||X.appendChild(f.createElement("div")),w=(Ic.exec(S)||["",""])[1].toLowerCase(),k=Ht[w]||Ht._default,L.innerHTML=k[1]+p.htmlPrefilter(S)+k[2],K=k[0];K--;)L=L.lastChild;p.merge(H,L.childNodes),L=X.firstChild,L.textContent=""}for(X.textContent="",ie=0;S=H[ie++];){if(y&&p.inArray(S,y)>-1){T&&T.push(S);continue}if(B=is(S),L=Pt(X.appendChild(S),"script"),B&&pa(L),I)for(K=0;S=L[K++];)Cc.test(S.type||"")&&I.push(S)}return X}var vc=/^([^.]*)(?:\.(.+)|)/;function rs(){return!0}function ns(){return!1}function ma(c,f,I,y,T,S){var L,w;if(typeof f=="object"){typeof I!="string"&&(y=y||I,I=void 0);for(w in f)ma(c,w,I,y,f[w],S);return c}if(y==null&&T==null?(T=I,y=I=void 0):T==null&&(typeof I=="string"?(T=y,y=void 0):(T=y,y=I,I=void 0)),T===!1)T=ns;else if(!T)return c;return S===1&&(L=T,T=function(k){return p().off(k),L.apply(this,arguments)},T.guid=L.guid||(L.guid=p.guid++)),c.each(function(){p.event.add(this,f,T,y,I)})}p.event={global:{},add:function(c,f,I,y,T){var S,L,w,k,B,K,X,H,ie,De,$e,Me=ue.get(c);if(Nt(c))for(I.handler&&(S=I,I=S.handler,T=S.selector),T&&p.find.matchesSelector(Ui,T),I.guid||(I.guid=p.guid++),(k=Me.events)||(k=Me.events=Object.create(null)),(L=Me.handle)||(L=Me.handle=function(It){return typeof p<"u"&&p.event.triggered!==It.type?p.event.dispatch.apply(c,arguments):void 0}),f=(f||"").match(Ye)||[""],B=f.length;B--;)w=vc.exec(f[B])||[],ie=$e=w[1],De=(w[2]||"").split(".").sort(),ie&&(X=p.event.special[ie]||{},ie=(T?X.delegateType:X.bindType)||ie,X=p.event.special[ie]||{},K=p.extend({type:ie,origType:$e,data:y,handler:I,guid:I.guid,selector:T,needsContext:T&&p.expr.match.needsContext.test(T),namespace:De.join(".")},S),(H=k[ie])||(H=k[ie]=[],H.delegateCount=0,(!X.setup||X.setup.call(c,y,De,L)===!1)&&c.addEventListener&&c.addEventListener(ie,L)),X.add&&(X.add.call(c,K),K.handler.guid||(K.handler.guid=I.guid)),T?H.splice(H.delegateCount++,0,K):H.push(K),p.event.global[ie]=!0)},remove:function(c,f,I,y,T){var S,L,w,k,B,K,X,H,ie,De,$e,Me=ue.hasData(c)&&ue.get(c);if(!(!Me||!(k=Me.events))){for(f=(f||"").match(Ye)||[""],B=f.length;B--;){if(w=vc.exec(f[B])||[],ie=$e=w[1],De=(w[2]||"").split(".").sort(),!ie){for(ie in k)p.event.remove(c,ie+f[B],I,y,!0);continue}for(X=p.event.special[ie]||{},ie=(y?X.delegateType:X.bindType)||ie,H=k[ie]||[],w=w[2]&&new RegExp("(^|\\.)"+De.join("\\.(?:.*\\.|)")+"(\\.|$)"),L=S=H.length;S--;)K=H[S],(T||$e===K.origType)&&(!I||I.guid===K.guid)&&(!w||w.test(K.namespace))&&(!y||y===K.selector||y==="**"&&K.selector)&&(H.splice(S,1),K.selector&&H.delegateCount--,X.remove&&X.remove.call(c,K));L&&!H.length&&((!X.teardown||X.teardown.call(c,De,Me.handle)===!1)&&p.removeEvent(c,ie,Me.handle),delete k[ie])}p.isEmptyObject(k)&&ue.remove(c,"handle events")}},dispatch:function(c){var f,I,y,T,S,L,w=new Array(arguments.length),k=p.event.fix(c),B=(ue.get(this,"events")||Object.create(null))[k.type]||[],K=p.event.special[k.type]||{};for(w[0]=k,f=1;f<arguments.length;f++)w[f]=arguments[f];if(k.delegateTarget=this,!(K.preDispatch&&K.preDispatch.call(this,k)===!1)){for(L=p.event.handlers.call(this,k,B),f=0;(T=L[f++])&&!k.isPropagationStopped();)for(k.currentTarget=T.elem,I=0;(S=T.handlers[I++])&&!k.isImmediatePropagationStopped();)(!k.rnamespace||S.namespace===!1||k.rnamespace.test(S.namespace))&&(k.handleObj=S,k.data=S.data,y=((p.event.special[S.origType]||{}).handle||S.handler).apply(T.elem,w),y!==void 0&&(k.result=y)===!1&&(k.preventDefault(),k.stopPropagation()));return K.postDispatch&&K.postDispatch.call(this,k),k.result}},handlers:function(c,f){var I,y,T,S,L,w=[],k=f.delegateCount,B=c.target;if(k&&B.nodeType&&!(c.type==="click"&&c.button>=1)){for(;B!==this;B=B.parentNode||this)if(B.nodeType===1&&!(c.type==="click"&&B.disabled===!0)){for(S=[],L={},I=0;I<k;I++)y=f[I],T=y.selector+" ",L[T]===void 0&&(L[T]=y.needsContext?p(T,this).index(B)>-1:p.find(T,this,null,[B]).length),L[T]&&S.push(y);S.length&&w.push({elem:B,handlers:S})}}return B=this,k<f.length&&w.push({elem:B,handlers:f.slice(k)}),w},addProp:function(c,f){Object.defineProperty(p.Event.prototype,c,{enumerable:!0,configurable:!0,get:C(f)?function(){if(this.originalEvent)return f(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[c]},set:function(I){Object.defineProperty(this,c,{enumerable:!0,configurable:!0,writable:!0,value:I})}})},fix:function(c){return c[p.expando]?c:new p.Event(c)},special:{load:{noBubble:!0},click:{setup:function(c){var f=this||c;return Ms.test(f.type)&&f.click&&N(f,"input")&&wr(f,"click",!0),!1},trigger:function(c){var f=this||c;return Ms.test(f.type)&&f.click&&N(f,"input")&&wr(f,"click"),!0},_default:function(c){var f=c.target;return Ms.test(f.type)&&f.click&&N(f,"input")&&ue.get(f,"click")||N(f,"a")}},beforeunload:{postDispatch:function(c){c.result!==void 0&&c.originalEvent&&(c.originalEvent.returnValue=c.result)}}}};function wr(c,f,I){if(!I){ue.get(c,f)===void 0&&p.event.add(c,f,rs);return}ue.set(c,f,!1),p.event.add(c,f,{namespace:!1,handler:function(y){var T,S=ue.get(this,f);if(y.isTrigger&1&&this[f]){if(S)(p.event.special[f]||{}).delegateType&&y.stopPropagation();else if(S=r.call(arguments),ue.set(this,f,S),this[f](),T=ue.get(this,f),ue.set(this,f,!1),S!==T)return y.stopImmediatePropagation(),y.preventDefault(),T}else S&&(ue.set(this,f,p.event.trigger(S[0],S.slice(1),this)),y.stopPropagation(),y.isImmediatePropagationStopped=rs)}})}p.removeEvent=function(c,f,I){c.removeEventListener&&c.removeEventListener(f,I)},p.Event=function(c,f){if(!(this instanceof p.Event))return new p.Event(c,f);c&&c.type?(this.originalEvent=c,this.type=c.type,this.isDefaultPrevented=c.defaultPrevented||c.defaultPrevented===void 0&&c.returnValue===!1?rs:ns,this.target=c.target&&c.target.nodeType===3?c.target.parentNode:c.target,this.currentTarget=c.currentTarget,this.relatedTarget=c.relatedTarget):this.type=c,f&&p.extend(this,f),this.timeStamp=c&&c.timeStamp||Date.now(),this[p.expando]=!0},p.Event.prototype={constructor:p.Event,isDefaultPrevented:ns,isPropagationStopped:ns,isImmediatePropagationStopped:ns,isSimulated:!1,preventDefault:function(){var c=this.originalEvent;this.isDefaultPrevented=rs,c&&!this.isSimulated&&c.preventDefault()},stopPropagation:function(){var c=this.originalEvent;this.isPropagationStopped=rs,c&&!this.isSimulated&&c.stopPropagation()},stopImmediatePropagation:function(){var c=this.originalEvent;this.isImmediatePropagationStopped=rs,c&&!this.isSimulated&&c.stopImmediatePropagation(),this.stopPropagation()}},p.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,char:!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:!0},p.event.addProp),p.each({focus:"focusin",blur:"focusout"},function(c,f){function I(y){if(x.documentMode){var T=ue.get(this,"handle"),S=p.event.fix(y);S.type=y.type==="focusin"?"focus":"blur",S.isSimulated=!0,T(y),S.target===S.currentTarget&&T(S)}else p.event.simulate(f,y.target,p.event.fix(y))}p.event.special[c]={setup:function(){var y;if(wr(this,c,!0),x.documentMode)y=ue.get(this,f),y||this.addEventListener(f,I),ue.set(this,f,(y||0)+1);else return!1},trigger:function(){return wr(this,c),!0},teardown:function(){var y;if(x.documentMode)y=ue.get(this,f)-1,y?ue.set(this,f,y):(this.removeEventListener(f,I),ue.remove(this,f));else return!1},_default:function(y){return ue.get(y.target,c)},delegateType:f},p.event.special[f]={setup:function(){var y=this.ownerDocument||this.document||this,T=x.documentMode?this:y,S=ue.get(T,f);S||(x.documentMode?this.addEventListener(f,I):y.addEventListener(c,I,!0)),ue.set(T,f,(S||0)+1)},teardown:function(){var y=this.ownerDocument||this.document||this,T=x.documentMode?this:y,S=ue.get(T,f)-1;S?ue.set(T,f,S):(x.documentMode?this.removeEventListener(f,I):y.removeEventListener(c,I,!0),ue.remove(T,f))}}}),p.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(c,f){p.event.special[c]={delegateType:f,bindType:f,handle:function(I){var y,T=this,S=I.relatedTarget,L=I.handleObj;return(!S||S!==T&&!p.contains(T,S))&&(I.type=L.origType,y=L.handler.apply(this,arguments),I.type=f),y}}}),p.fn.extend({on:function(c,f,I,y){return ma(this,c,f,I,y)},one:function(c,f,I,y){return ma(this,c,f,I,y,1)},off:function(c,f,I){var y,T;if(c&&c.preventDefault&&c.handleObj)return y=c.handleObj,p(c.delegateTarget).off(y.namespace?y.origType+"."+y.namespace:y.origType,y.selector,y.handler),this;if(typeof c=="object"){for(T in c)this.off(T,f,c[T]);return this}return(f===!1||typeof f=="function")&&(I=f,f=void 0),I===!1&&(I=ns),this.each(function(){p.event.remove(this,c,I,f)})}});var Qm=/<script|<style|<link/i,Jm=/checked\s*(?:[^=]|=\s*.checked.)/i,e0=/^\s*<!\[CDATA\[|\]\]>\s*$/g;function Ec(c,f){return N(c,"table")&&N(f.nodeType!==11?f:f.firstChild,"tr")&&p(c).children("tbody")[0]||c}function t0(c){return c.type=(c.getAttribute("type")!==null)+"/"+c.type,c}function i0(c){return(c.type||"").slice(0,5)==="true/"?c.type=c.type.slice(5):c.removeAttribute("type"),c}function Tc(c,f){var I,y,T,S,L,w,k;if(f.nodeType===1){if(ue.hasData(c)&&(S=ue.get(c),k=S.events,k)){ue.remove(f,"handle events");for(T in k)for(I=0,y=k[T].length;I<y;I++)p.event.add(f,T,k[T][I])}Ze.hasData(c)&&(L=Ze.access(c),w=p.extend({},L),Ze.set(f,w))}}function s0(c,f){var I=f.nodeName.toLowerCase();I==="input"&&Ms.test(c.type)?f.checked=c.checked:(I==="input"||I==="textarea")&&(f.defaultValue=c.defaultValue)}function as(c,f,I,y){f=a(f);var T,S,L,w,k,B,K=0,X=c.length,H=X-1,ie=f[0],De=C(ie);if(De||X>1&&typeof ie=="string"&&!A.checkClone&&Jm.test(ie))return c.each(function($e){var Me=c.eq($e);De&&(f[0]=ie.call(this,$e,Me.html())),as(Me,f,I,y)});if(X&&(T=yc(f,c[0].ownerDocument,!1,c,y),S=T.firstChild,T.childNodes.length===1&&(T=S),S||y)){for(L=p.map(Pt(T,"script"),t0),w=L.length;K<X;K++)k=T,K!==H&&(k=p.clone(k,!0,!0),w&&p.merge(L,Pt(k,"script"))),I.call(c[K],k,K);if(w)for(B=L[L.length-1].ownerDocument,p.map(L,i0),K=0;K<w;K++)k=L[K],Cc.test(k.type||"")&&!ue.access(k,"globalEval")&&p.contains(B,k)&&(k.src&&(k.type||"").toLowerCase()!=="module"?p._evalUrl&&!k.noModule&&p._evalUrl(k.src,{nonce:k.nonce||k.getAttribute("nonce")},B):b(k.textContent.replace(e0,""),k,B))}return c}function Sc(c,f,I){for(var y,T=f?p.filter(f,c):c,S=0;(y=T[S])!=null;S++)!I&&y.nodeType===1&&p.cleanData(Pt(y)),y.parentNode&&(I&&is(y)&&pa(Pt(y,"script")),y.parentNode.removeChild(y));return c}p.extend({htmlPrefilter:function(c){return c},clone:function(c,f,I){var y,T,S,L,w=c.cloneNode(!0),k=is(c);if(!A.noCloneChecked&&(c.nodeType===1||c.nodeType===11)&&!p.isXMLDoc(c))for(L=Pt(w),S=Pt(c),y=0,T=S.length;y<T;y++)s0(S[y],L[y]);if(f)if(I)for(S=S||Pt(c),L=L||Pt(w),y=0,T=S.length;y<T;y++)Tc(S[y],L[y]);else Tc(c,w);return L=Pt(w,"script"),L.length>0&&pa(L,!k&&Pt(c,"script")),w},cleanData:function(c){for(var f,I,y,T=p.event.special,S=0;(I=c[S])!==void 0;S++)if(Nt(I)){if(f=I[ue.expando]){if(f.events)for(y in f.events)T[y]?p.event.remove(I,y):p.removeEvent(I,y,f.handle);I[ue.expando]=void 0}I[Ze.expando]&&(I[Ze.expando]=void 0)}}}),p.fn.extend({detach:function(c){return Sc(this,c,!0)},remove:function(c){return Sc(this,c)},text:function(c){return Re(this,function(f){return f===void 0?p.text(this):this.empty().each(function(){(this.nodeType===1||this.nodeType===11||this.nodeType===9)&&(this.textContent=f)})},null,c,arguments.length)},append:function(){return as(this,arguments,function(c){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var f=Ec(this,c);f.appendChild(c)}})},prepend:function(){return as(this,arguments,function(c){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var f=Ec(this,c);f.insertBefore(c,f.firstChild)}})},before:function(){return as(this,arguments,function(c){this.parentNode&&this.parentNode.insertBefore(c,this)})},after:function(){return as(this,arguments,function(c){this.parentNode&&this.parentNode.insertBefore(c,this.nextSibling)})},empty:function(){for(var c,f=0;(c=this[f])!=null;f++)c.nodeType===1&&(p.cleanData(Pt(c,!1)),c.textContent="");return this},clone:function(c,f){return c=c??!1,f=f??c,this.map(function(){return p.clone(this,c,f)})},html:function(c){return Re(this,function(f){var I=this[0]||{},y=0,T=this.length;if(f===void 0&&I.nodeType===1)return I.innerHTML;if(typeof f=="string"&&!Qm.test(f)&&!Ht[(Ic.exec(f)||["",""])[1].toLowerCase()]){f=p.htmlPrefilter(f);try{for(;y<T;y++)I=this[y]||{},I.nodeType===1&&(p.cleanData(Pt(I,!1)),I.innerHTML=f);I=0}catch{}}I&&this.empty().append(f)},null,c,arguments.length)},replaceWith:function(){var c=[];return as(this,arguments,function(f){var I=this.parentNode;p.inArray(this,c)<0&&(p.cleanData(Pt(this)),I&&I.replaceChild(f,this))},c)}}),p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(c,f){p.fn[c]=function(I){for(var y,T=[],S=p(I),L=S.length-1,w=0;w<=L;w++)y=w===L?this:this.clone(!0),p(S[w])[f](y),o.apply(T,y.get());return this.pushStack(T)}});var Aa=new RegExp("^("+Dt+")(?!px)[a-z%]+$","i"),Ia=/^--/,Mr=function(c){var f=c.ownerDocument.defaultView;return(!f||!f.opener)&&(f=e),f.getComputedStyle(c)},xc=function(c,f,I){var y,T,S={};for(T in f)S[T]=c.style[T],c.style[T]=f[T];y=I.call(c);for(T in f)c.style[T]=S[T];return y},r0=new RegExp(Ii.join("|"),"i");(function(){function c(){if(B){k.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",B.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",Ui.appendChild(k).appendChild(B);var K=e.getComputedStyle(B);I=K.top!=="1%",w=f(K.marginLeft)===12,B.style.right="60%",S=f(K.right)===36,y=f(K.width)===36,B.style.position="absolute",T=f(B.offsetWidth/3)===12,Ui.removeChild(k),B=null}}function f(K){return Math.round(parseFloat(K))}var I,y,T,S,L,w,k=x.createElement("div"),B=x.createElement("div");B.style&&(B.style.backgroundClip="content-box",B.cloneNode(!0).style.backgroundClip="",A.clearCloneStyle=B.style.backgroundClip==="content-box",p.extend(A,{boxSizingReliable:function(){return c(),y},pixelBoxStyles:function(){return c(),S},pixelPosition:function(){return c(),I},reliableMarginLeft:function(){return c(),w},scrollboxSize:function(){return c(),T},reliableTrDimensions:function(){var K,X,H,ie;return L==null&&(K=x.createElement("table"),X=x.createElement("tr"),H=x.createElement("div"),K.style.cssText="position:absolute;left:-11111px;border-collapse:separate",X.style.cssText="box-sizing:content-box;border:1px solid",X.style.height="1px",H.style.height="9px",H.style.display="block",Ui.appendChild(K).appendChild(X).appendChild(H),ie=e.getComputedStyle(X),L=parseInt(ie.height,10)+parseInt(ie.borderTopWidth,10)+parseInt(ie.borderBottomWidth,10)===X.offsetHeight,Ui.removeChild(K)),L}}))})();function Os(c,f,I){var y,T,S,L,w=Ia.test(f),k=c.style;return I=I||Mr(c),I&&(L=I.getPropertyValue(f)||I[f],w&&L&&(L=L.replace(oe,"$1")||void 0),L===""&&!is(c)&&(L=p.style(c,f)),!A.pixelBoxStyles()&&Aa.test(L)&&r0.test(f)&&(y=k.width,T=k.minWidth,S=k.maxWidth,k.minWidth=k.maxWidth=k.width=L,L=I.width,k.width=y,k.minWidth=T,k.maxWidth=S)),L!==void 0?L+"":L}function bc(c,f){return{get:function(){if(c()){delete this.get;return}return(this.get=f).apply(this,arguments)}}}var Lc=["Webkit","Moz","ms"],Rc=x.createElement("div").style,Dc={};function n0(c){for(var f=c[0].toUpperCase()+c.slice(1),I=Lc.length;I--;)if(c=Lc[I]+f,c in Rc)return c}function Ca(c){var f=p.cssProps[c]||Dc[c];return f||(c in Rc?c:Dc[c]=n0(c)||c)}var a0=/^(none|table(?!-c[ea]).+)/,o0={position:"absolute",visibility:"hidden",display:"block"},Pc={letterSpacing:"0",fontWeight:"400"};function _c(c,f,I){var y=Di.exec(f);return y?Math.max(0,y[2]-(I||0))+(y[3]||"px"):f}function ya(c,f,I,y,T,S){var L=f==="width"?1:0,w=0,k=0,B=0;if(I===(y?"border":"content"))return 0;for(;L<4;L+=2)I==="margin"&&(B+=p.css(c,I+Ii[L],!0,T)),y?(I==="content"&&(k-=p.css(c,"padding"+Ii[L],!0,T)),I!=="margin"&&(k-=p.css(c,"border"+Ii[L]+"Width",!0,T))):(k+=p.css(c,"padding"+Ii[L],!0,T),I!=="padding"?k+=p.css(c,"border"+Ii[L]+"Width",!0,T):w+=p.css(c,"border"+Ii[L]+"Width",!0,T));return!y&&S>=0&&(k+=Math.max(0,Math.ceil(c["offset"+f[0].toUpperCase()+f.slice(1)]-S-k-w-.5))||0),k+B}function kc(c,f,I){var y=Mr(c),T=!A.boxSizingReliable()||I,S=T&&p.css(c,"boxSizing",!1,y)==="border-box",L=S,w=Os(c,f,y),k="offset"+f[0].toUpperCase()+f.slice(1);if(Aa.test(w)){if(!I)return w;w="auto"}return(!A.boxSizingReliable()&&S||!A.reliableTrDimensions()&&N(c,"tr")||w==="auto"||!parseFloat(w)&&p.css(c,"display",!1,y)==="inline")&&c.getClientRects().length&&(S=p.css(c,"boxSizing",!1,y)==="border-box",L=k in c,L&&(w=c[k])),w=parseFloat(w)||0,w+ya(c,f,I||(S?"border":"content"),L,y,w)+"px"}p.extend({cssHooks:{opacity:{get:function(c,f){if(f){var I=Os(c,"opacity");return I===""?"1":I}}}},cssNumber:{animationIterationCount:!0,aspectRatio:!0,borderImageSlice:!0,columnCount:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,scale:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeMiterlimit:!0,strokeOpacity:!0},cssProps:{},style:function(c,f,I,y){if(!(!c||c.nodeType===3||c.nodeType===8||!c.style)){var T,S,L,w=at(f),k=Ia.test(f),B=c.style;if(k||(f=Ca(w)),L=p.cssHooks[f]||p.cssHooks[w],I!==void 0){if(S=typeof I,S==="string"&&(T=Di.exec(I))&&T[1]&&(I=mc(c,f,T),S="number"),I==null||I!==I)return;S==="number"&&!k&&(I+=T&&T[3]||(p.cssNumber[w]?"":"px")),!A.clearCloneStyle&&I===""&&f.indexOf("background")===0&&(B[f]="inherit"),(!L||!("set"in L)||(I=L.set(c,I,y))!==void 0)&&(k?B.setProperty(f,I):B[f]=I)}else return L&&"get"in L&&(T=L.get(c,!1,y))!==void 0?T:B[f]}},css:function(c,f,I,y){var T,S,L,w=at(f),k=Ia.test(f);return k||(f=Ca(w)),L=p.cssHooks[f]||p.cssHooks[w],L&&"get"in L&&(T=L.get(c,!0,I)),T===void 0&&(T=Os(c,f,y)),T==="normal"&&f in Pc&&(T=Pc[f]),I===""||I?(S=parseFloat(T),I===!0||isFinite(S)?S||0:T):T}}),p.each(["height","width"],function(c,f){p.cssHooks[f]={get:function(I,y,T){if(y)return a0.test(p.css(I,"display"))&&(!I.getClientRects().length||!I.getBoundingClientRect().width)?xc(I,o0,function(){return kc(I,f,T)}):kc(I,f,T)},set:function(I,y,T){var S,L=Mr(I),w=!A.scrollboxSize()&&L.position==="absolute",k=w||T,B=k&&p.css(I,"boxSizing",!1,L)==="border-box",K=T?ya(I,f,T,B,L):0;return B&&w&&(K-=Math.ceil(I["offset"+f[0].toUpperCase()+f.slice(1)]-parseFloat(L[f])-ya(I,f,"border",!1,L)-.5)),K&&(S=Di.exec(y))&&(S[3]||"px")!=="px"&&(I.style[f]=y,y=p.css(I,f)),_c(I,y,K)}}}),p.cssHooks.marginLeft=bc(A.reliableMarginLeft,function(c,f){if(f)return(parseFloat(Os(c,"marginLeft"))||c.getBoundingClientRect().left-xc(c,{marginLeft:0},function(){return c.getBoundingClientRect().left}))+"px"}),p.each({margin:"",padding:"",border:"Width"},function(c,f){p.cssHooks[c+f]={expand:function(I){for(var y=0,T={},S=typeof I=="string"?I.split(" "):[I];y<4;y++)T[c+Ii[y]+f]=S[y]||S[y-2]||S[0];return T}},c!=="margin"&&(p.cssHooks[c+f].set=_c)}),p.fn.extend({css:function(c,f){return Re(this,function(I,y,T){var S,L,w={},k=0;if(Array.isArray(y)){for(S=Mr(I),L=y.length;k<L;k++)w[y[k]]=p.css(I,y[k],!1,S);return w}return T!==void 0?p.style(I,y,T):p.css(I,y)},c,f,arguments.length>1)}});function _t(c,f,I,y,T){return new _t.prototype.init(c,f,I,y,T)}p.Tween=_t,_t.prototype={constructor:_t,init:function(c,f,I,y,T,S){this.elem=c,this.prop=I,this.easing=T||p.easing._default,this.options=f,this.start=this.now=this.cur(),this.end=y,this.unit=S||(p.cssNumber[I]?"":"px")},cur:function(){var c=_t.propHooks[this.prop];return c&&c.get?c.get(this):_t.propHooks._default.get(this)},run:function(c){var f,I=_t.propHooks[this.prop];return this.options.duration?this.pos=f=p.easing[this.easing](c,this.options.duration*c,0,1,this.options.duration):this.pos=f=c,this.now=(this.end-this.start)*f+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),I&&I.set?I.set(this):_t.propHooks._default.set(this),this}},_t.prototype.init.prototype=_t.prototype,_t.propHooks={_default:{get:function(c){var f;return c.elem.nodeType!==1||c.elem[c.prop]!=null&&c.elem.style[c.prop]==null?c.elem[c.prop]:(f=p.css(c.elem,c.prop,""),!f||f==="auto"?0:f)},set:function(c){p.fx.step[c.prop]?p.fx.step[c.prop](c):c.elem.nodeType===1&&(p.cssHooks[c.prop]||c.elem.style[Ca(c.prop)]!=null)?p.style(c.elem,c.prop,c.now+c.unit):c.elem[c.prop]=c.now}}},_t.propHooks.scrollTop=_t.propHooks.scrollLeft={set:function(c){c.elem.nodeType&&c.elem.parentNode&&(c.elem[c.prop]=c.now)}},p.easing={linear:function(c){return c},swing:function(c){return .5-Math.cos(c*Math.PI)/2},_default:"swing"},p.fx=_t.prototype.init,p.fx.step={};var os,Or,l0=/^(?:toggle|show|hide)$/,u0=/queueHooks$/;function va(){Or&&(x.hidden===!1&&e.requestAnimationFrame?e.requestAnimationFrame(va):e.setTimeout(va,p.fx.interval),p.fx.tick())}function wc(){return e.setTimeout(function(){os=void 0}),os=Date.now()}function Fr(c,f){var I,y=0,T={height:c};for(f=f?1:0;y<4;y+=2-f)I=Ii[y],T["margin"+I]=T["padding"+I]=c;return f&&(T.opacity=T.width=c),T}function Mc(c,f,I){for(var y,T=(Zt.tweeners[f]||[]).concat(Zt.tweeners["*"]),S=0,L=T.length;S<L;S++)if(y=T[S].call(I,f,c))return y}function c0(c,f,I){var y,T,S,L,w,k,B,K,X="width"in f||"height"in f,H=this,ie={},De=c.style,$e=c.nodeType&&kr(c),Me=ue.get(c,"fxshow");I.queue||(L=p._queueHooks(c,"fx"),L.unqueued==null&&(L.unqueued=0,w=L.empty.fire,L.empty.fire=function(){L.unqueued||w()}),L.unqueued++,H.always(function(){H.always(function(){L.unqueued--,p.queue(c,"fx").length||L.empty.fire()})}));for(y in f)if(T=f[y],l0.test(T)){if(delete f[y],S=S||T==="toggle",T===($e?"hide":"show"))if(T==="show"&&Me&&Me[y]!==void 0)$e=!0;else continue;ie[y]=Me&&Me[y]||p.style(c,y)}if(k=!p.isEmptyObject(f),!(!k&&p.isEmptyObject(ie))){X&&c.nodeType===1&&(I.overflow=[De.overflow,De.overflowX,De.overflowY],B=Me&&Me.display,B==null&&(B=ue.get(c,"display")),K=p.css(c,"display"),K==="none"&&(B?K=B:(ss([c],!0),B=c.style.display||B,K=p.css(c,"display"),ss([c]))),(K==="inline"||K==="inline-block"&&B!=null)&&p.css(c,"float")==="none"&&(k||(H.done(function(){De.display=B}),B==null&&(K=De.display,B=K==="none"?"":K)),De.display="inline-block")),I.overflow&&(De.overflow="hidden",H.always(function(){De.overflow=I.overflow[0],De.overflowX=I.overflow[1],De.overflowY=I.overflow[2]})),k=!1;for(y in ie)k||(Me?"hidden"in Me&&($e=Me.hidden):Me=ue.access(c,"fxshow",{display:B}),S&&(Me.hidden=!$e),$e&&ss([c],!0),H.done(function(){$e||ss([c]),ue.remove(c,"fxshow");for(y in ie)p.style(c,y,ie[y])})),k=Mc($e?Me[y]:0,y,H),y in Me||(Me[y]=k.start,$e&&(k.end=k.start,k.start=0))}}function h0(c,f){var I,y,T,S,L;for(I in c)if(y=at(I),T=f[y],S=c[I],Array.isArray(S)&&(T=S[1],S=c[I]=S[0]),I!==y&&(c[y]=S,delete c[I]),L=p.cssHooks[y],L&&"expand"in L){S=L.expand(S),delete c[y];for(I in S)I in c||(c[I]=S[I],f[I]=T)}else f[y]=T}function Zt(c,f,I){var y,T,S=0,L=Zt.prefilters.length,w=p.Deferred().always(function(){delete k.elem}),k=function(){if(T)return!1;for(var X=os||wc(),H=Math.max(0,B.startTime+B.duration-X),ie=H/B.duration||0,De=1-ie,$e=0,Me=B.tweens.length;$e<Me;$e++)B.tweens[$e].run(De);return w.notifyWith(c,[B,De,H]),De<1&&Me?H:(Me||w.notifyWith(c,[B,1,0]),w.resolveWith(c,[B]),!1)},B=w.promise({elem:c,props:p.extend({},f),opts:p.extend(!0,{specialEasing:{},easing:p.easing._default},I),originalProperties:f,originalOptions:I,startTime:os||wc(),duration:I.duration,tweens:[],createTween:function(X,H){var ie=p.Tween(c,B.opts,X,H,B.opts.specialEasing[X]||B.opts.easing);return B.tweens.push(ie),ie},stop:function(X){var H=0,ie=X?B.tweens.length:0;if(T)return this;for(T=!0;H<ie;H++)B.tweens[H].run(1);return X?(w.notifyWith(c,[B,1,0]),w.resolveWith(c,[B,X])):w.rejectWith(c,[B,X]),this}}),K=B.props;for(h0(K,B.opts.specialEasing);S<L;S++)if(y=Zt.prefilters[S].call(B,c,K,B.opts),y)return C(y.stop)&&(p._queueHooks(B.elem,B.opts.queue).stop=y.stop.bind(y)),y;return p.map(K,Mc,B),C(B.opts.start)&&B.opts.start.call(c,B),B.progress(B.opts.progress).done(B.opts.done,B.opts.complete).fail(B.opts.fail).always(B.opts.always),p.fx.timer(p.extend(k,{elem:c,anim:B,queue:B.opts.queue})),B}p.Animation=p.extend(Zt,{tweeners:{"*":[function(c,f){var I=this.createTween(c,f);return mc(I.elem,c,Di.exec(f),I),I}]},tweener:function(c,f){C(c)?(f=c,c=["*"]):c=c.match(Ye);for(var I,y=0,T=c.length;y<T;y++)I=c[y],Zt.tweeners[I]=Zt.tweeners[I]||[],Zt.tweeners[I].unshift(f)},prefilters:[c0],prefilter:function(c,f){f?Zt.prefilters.unshift(c):Zt.prefilters.push(c)}}),p.speed=function(c,f,I){var y=c&&typeof c=="object"?p.extend({},c):{complete:I||!I&&f||C(c)&&c,duration:c,easing:I&&f||f&&!C(f)&&f};return p.fx.off?y.duration=0:typeof y.duration!="number"&&(y.duration in p.fx.speeds?y.duration=p.fx.speeds[y.duration]:y.duration=p.fx.speeds._default),(y.queue==null||y.queue===!0)&&(y.queue="fx"),y.old=y.complete,y.complete=function(){C(y.old)&&y.old.call(this),y.queue&&p.dequeue(this,y.queue)},y},p.fn.extend({fadeTo:function(c,f,I,y){return this.filter(kr).css("opacity",0).show().end().animate({opacity:f},c,I,y)},animate:function(c,f,I,y){var T=p.isEmptyObject(c),S=p.speed(f,I,y),L=function(){var w=Zt(this,p.extend({},c),S);(T||ue.get(this,"finish"))&&w.stop(!0)};return L.finish=L,T||S.queue===!1?this.each(L):this.queue(S.queue,L)},stop:function(c,f,I){var y=function(T){var S=T.stop;delete T.stop,S(I)};return typeof c!="string"&&(I=f,f=c,c=void 0),f&&this.queue(c||"fx",[]),this.each(function(){var T=!0,S=c!=null&&c+"queueHooks",L=p.timers,w=ue.get(this);if(S)w[S]&&w[S].stop&&y(w[S]);else for(S in w)w[S]&&w[S].stop&&u0.test(S)&&y(w[S]);for(S=L.length;S--;)L[S].elem===this&&(c==null||L[S].queue===c)&&(L[S].anim.stop(I),T=!1,L.splice(S,1));(T||!I)&&p.dequeue(this,c)})},finish:function(c){return c!==!1&&(c=c||"fx"),this.each(function(){var f,I=ue.get(this),y=I[c+"queue"],T=I[c+"queueHooks"],S=p.timers,L=y?y.length:0;for(I.finish=!0,p.queue(this,c,[]),T&&T.stop&&T.stop.call(this,!0),f=S.length;f--;)S[f].elem===this&&S[f].queue===c&&(S[f].anim.stop(!0),S.splice(f,1));for(f=0;f<L;f++)y[f]&&y[f].finish&&y[f].finish.call(this);delete I.finish})}}),p.each(["toggle","show","hide"],function(c,f){var I=p.fn[f];p.fn[f]=function(y,T,S){return y==null||typeof y=="boolean"?I.apply(this,arguments):this.animate(Fr(f,!0),y,T,S)}}),p.each({slideDown:Fr("show"),slideUp:Fr("hide"),slideToggle:Fr("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(c,f){p.fn[c]=function(I,y,T){return this.animate(f,I,y,T)}}),p.timers=[],p.fx.tick=function(){var c,f=0,I=p.timers;for(os=Date.now();f<I.length;f++)c=I[f],!c()&&I[f]===c&&I.splice(f--,1);I.length||p.fx.stop(),os=void 0},p.fx.timer=function(c){p.timers.push(c),p.fx.start()},p.fx.interval=13,p.fx.start=function(){Or||(Or=!0,va())},p.fx.stop=function(){Or=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fn.delay=function(c,f){return c=p.fx&&p.fx.speeds[c]||c,f=f||"fx",this.queue(f,function(I,y){var T=e.setTimeout(I,c);y.stop=function(){e.clearTimeout(T)}})},(function(){var c=x.createElement("input"),f=x.createElement("select"),I=f.appendChild(x.createElement("option"));c.type="checkbox",A.checkOn=c.value!=="",A.optSelected=I.selected,c=x.createElement("input"),c.value="t",c.type="radio",A.radioValue=c.value==="t"})();var Oc,Fs=p.expr.attrHandle;p.fn.extend({attr:function(c,f){return Re(this,p.attr,c,f,arguments.length>1)},removeAttr:function(c){return this.each(function(){p.removeAttr(this,c)})}}),p.extend({attr:function(c,f,I){var y,T,S=c.nodeType;if(!(S===3||S===8||S===2)){if(typeof c.getAttribute>"u")return p.prop(c,f,I);if((S!==1||!p.isXMLDoc(c))&&(T=p.attrHooks[f.toLowerCase()]||(p.expr.match.bool.test(f)?Oc:void 0)),I!==void 0){if(I===null){p.removeAttr(c,f);return}return T&&"set"in T&&(y=T.set(c,I,f))!==void 0?y:(c.setAttribute(f,I+""),I)}return T&&"get"in T&&(y=T.get(c,f))!==null?y:(y=p.find.attr(c,f),y??void 0)}},attrHooks:{type:{set:function(c,f){if(!A.radioValue&&f==="radio"&&N(c,"input")){var I=c.value;return c.setAttribute("type",f),I&&(c.value=I),f}}}},removeAttr:function(c,f){var I,y=0,T=f&&f.match(Ye);if(T&&c.nodeType===1)for(;I=T[y++];)c.removeAttribute(I)}}),Oc={set:function(c,f,I){return f===!1?p.removeAttr(c,I):c.setAttribute(I,I),I}},p.each(p.expr.match.bool.source.match(/\w+/g),function(c,f){var I=Fs[f]||p.find.attr;Fs[f]=function(y,T,S){var L,w,k=T.toLowerCase();return S||(w=Fs[k],Fs[k]=L,L=I(y,T,S)!=null?k:null,Fs[k]=w),L}});var d0=/^(?:input|select|textarea|button)$/i,f0=/^(?:a|area)$/i;p.fn.extend({prop:function(c,f){return Re(this,p.prop,c,f,arguments.length>1)},removeProp:function(c){return this.each(function(){delete this[p.propFix[c]||c]})}}),p.extend({prop:function(c,f,I){var y,T,S=c.nodeType;if(!(S===3||S===8||S===2))return(S!==1||!p.isXMLDoc(c))&&(f=p.propFix[f]||f,T=p.propHooks[f]),I!==void 0?T&&"set"in T&&(y=T.set(c,I,f))!==void 0?y:c[f]=I:T&&"get"in T&&(y=T.get(c,f))!==null?y:c[f]},propHooks:{tabIndex:{get:function(c){var f=p.find.attr(c,"tabindex");return f?parseInt(f,10):d0.test(c.nodeName)||f0.test(c.nodeName)&&c.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),A.optSelected||(p.propHooks.selected={get:function(c){var f=c.parentNode;return f&&f.parentNode&&f.parentNode.selectedIndex,null},set:function(c){var f=c.parentNode;f&&(f.selectedIndex,f.parentNode&&f.parentNode.selectedIndex)}}),p.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){p.propFix[this.toLowerCase()]=this});function $i(c){var f=c.match(Ye)||[];return f.join(" ")}function Gi(c){return c.getAttribute&&c.getAttribute("class")||""}function Ea(c){return Array.isArray(c)?c:typeof c=="string"?c.match(Ye)||[]:[]}p.fn.extend({addClass:function(c){var f,I,y,T,S,L;return C(c)?this.each(function(w){p(this).addClass(c.call(this,w,Gi(this)))}):(f=Ea(c),f.length?this.each(function(){if(y=Gi(this),I=this.nodeType===1&&" "+$i(y)+" ",I){for(S=0;S<f.length;S++)T=f[S],I.indexOf(" "+T+" ")<0&&(I+=T+" ");L=$i(I),y!==L&&this.setAttribute("class",L)}}):this)},removeClass:function(c){var f,I,y,T,S,L;return C(c)?this.each(function(w){p(this).removeClass(c.call(this,w,Gi(this)))}):arguments.length?(f=Ea(c),f.length?this.each(function(){if(y=Gi(this),I=this.nodeType===1&&" "+$i(y)+" ",I){for(S=0;S<f.length;S++)for(T=f[S];I.indexOf(" "+T+" ")>-1;)I=I.replace(" "+T+" "," ");L=$i(I),y!==L&&this.setAttribute("class",L)}}):this):this.attr("class","")},toggleClass:function(c,f){var I,y,T,S,L=typeof c,w=L==="string"||Array.isArray(c);return C(c)?this.each(function(k){p(this).toggleClass(c.call(this,k,Gi(this),f),f)}):typeof f=="boolean"&&w?f?this.addClass(c):this.removeClass(c):(I=Ea(c),this.each(function(){if(w)for(S=p(this),T=0;T<I.length;T++)y=I[T],S.hasClass(y)?S.removeClass(y):S.addClass(y);else(c===void 0||L==="boolean")&&(y=Gi(this),y&&ue.set(this,"__className__",y),this.setAttribute&&this.setAttribute("class",y||c===!1?"":ue.get(this,"__className__")||""))}))},hasClass:function(c){var f,I,y=0;for(f=" "+c+" ";I=this[y++];)if(I.nodeType===1&&(" "+$i(Gi(I))+" ").indexOf(f)>-1)return!0;return!1}});var g0=/\r/g;p.fn.extend({val:function(c){var f,I,y,T=this[0];return arguments.length?(y=C(c),this.each(function(S){var L;this.nodeType===1&&(y?L=c.call(this,S,p(this).val()):L=c,L==null?L="":typeof L=="number"?L+="":Array.isArray(L)&&(L=p.map(L,function(w){return w==null?"":w+""})),f=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()],(!f||!("set"in f)||f.set(this,L,"value")===void 0)&&(this.value=L))})):T?(f=p.valHooks[T.type]||p.valHooks[T.nodeName.toLowerCase()],f&&"get"in f&&(I=f.get(T,"value"))!==void 0?I:(I=T.value,typeof I=="string"?I.replace(g0,""):I??"")):void 0}}),p.extend({valHooks:{option:{get:function(c){var f=p.find.attr(c,"value");return f??$i(p.text(c))}},select:{get:function(c){var f,I,y,T=c.options,S=c.selectedIndex,L=c.type==="select-one",w=L?null:[],k=L?S+1:T.length;for(S<0?y=k:y=L?S:0;y<k;y++)if(I=T[y],(I.selected||y===S)&&!I.disabled&&(!I.parentNode.disabled||!N(I.parentNode,"optgroup"))){if(f=p(I).val(),L)return f;w.push(f)}return w},set:function(c,f){for(var I,y,T=c.options,S=p.makeArray(f),L=T.length;L--;)y=T[L],(y.selected=p.inArray(p.valHooks.option.get(y),S)>-1)&&(I=!0);return I||(c.selectedIndex=-1),S}}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]={set:function(c,f){if(Array.isArray(f))return c.checked=p.inArray(p(c).val(),f)>-1}},A.checkOn||(p.valHooks[this].get=function(c){return c.getAttribute("value")===null?"on":c.value})});var Ns=e.location,Fc={guid:Date.now()},Ta=/\?/;p.parseXML=function(c){var f,I;if(!c||typeof c!="string")return null;try{f=new e.DOMParser().parseFromString(c,"text/xml")}catch{}return I=f&&f.getElementsByTagName("parsererror")[0],(!f||I)&&p.error("Invalid XML: "+(I?p.map(I.childNodes,function(y){return y.textContent}).join(`
|
|
43
|
-
`):c)),f};var Nc=/^(?:focusinfocus|focusoutblur)$/,Bc=function(c){c.stopPropagation()};p.extend(p.event,{trigger:function(c,f,I,y){var T,S,L,w,k,B,K,X,H=[I||x],ie=d.call(c,"type")?c.type:c,De=d.call(c,"namespace")?c.namespace.split("."):[];if(S=X=L=I=I||x,!(I.nodeType===3||I.nodeType===8)&&!Nc.test(ie+p.event.triggered)&&(ie.indexOf(".")>-1&&(De=ie.split("."),ie=De.shift(),De.sort()),k=ie.indexOf(":")<0&&"on"+ie,c=c[p.expando]?c:new p.Event(ie,typeof c=="object"&&c),c.isTrigger=y?2:3,c.namespace=De.join("."),c.rnamespace=c.namespace?new RegExp("(^|\\.)"+De.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,c.result=void 0,c.target||(c.target=I),f=f==null?[c]:p.makeArray(f,[c]),K=p.event.special[ie]||{},!(!y&&K.trigger&&K.trigger.apply(I,f)===!1))){if(!y&&!K.noBubble&&!v(I)){for(w=K.delegateType||ie,Nc.test(w+ie)||(S=S.parentNode);S;S=S.parentNode)H.push(S),L=S;L===(I.ownerDocument||x)&&H.push(L.defaultView||L.parentWindow||e)}for(T=0;(S=H[T++])&&!c.isPropagationStopped();)X=S,c.type=T>1?w:K.bindType||ie,B=(ue.get(S,"events")||Object.create(null))[c.type]&&ue.get(S,"handle"),B&&B.apply(S,f),B=k&&S[k],B&&B.apply&&Nt(S)&&(c.result=B.apply(S,f),c.result===!1&&c.preventDefault());return c.type=ie,!y&&!c.isDefaultPrevented()&&(!K._default||K._default.apply(H.pop(),f)===!1)&&Nt(I)&&k&&C(I[ie])&&!v(I)&&(L=I[k],L&&(I[k]=null),p.event.triggered=ie,c.isPropagationStopped()&&X.addEventListener(ie,Bc),I[ie](),c.isPropagationStopped()&&X.removeEventListener(ie,Bc),p.event.triggered=void 0,L&&(I[k]=L)),c.result}},simulate:function(c,f,I){var y=p.extend(new p.Event,I,{type:c,isSimulated:!0});p.event.trigger(y,null,f)}}),p.fn.extend({trigger:function(c,f){return this.each(function(){p.event.trigger(c,f,this)})},triggerHandler:function(c,f){var I=this[0];if(I)return p.event.trigger(c,f,I,!0)}});var p0=/\[\]$/,Uc=/\r?\n/g,m0=/^(?:submit|button|image|reset|file)$/i,A0=/^(?:input|select|textarea|keygen)/i;function Sa(c,f,I,y){var T;if(Array.isArray(f))p.each(f,function(S,L){I||p0.test(c)?y(c,L):Sa(c+"["+(typeof L=="object"&&L!=null?S:"")+"]",L,I,y)});else if(!I&&D(f)==="object")for(T in f)Sa(c+"["+T+"]",f[T],I,y);else y(c,f)}p.param=function(c,f){var I,y=[],T=function(S,L){var w=C(L)?L():L;y[y.length]=encodeURIComponent(S)+"="+encodeURIComponent(w??"")};if(c==null)return"";if(Array.isArray(c)||c.jquery&&!p.isPlainObject(c))p.each(c,function(){T(this.name,this.value)});else for(I in c)Sa(I,c[I],f,T);return y.join("&")},p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var c=p.prop(this,"elements");return c?p.makeArray(c):this}).filter(function(){var c=this.type;return this.name&&!p(this).is(":disabled")&&A0.test(this.nodeName)&&!m0.test(c)&&(this.checked||!Ms.test(c))}).map(function(c,f){var I=p(this).val();return I==null?null:Array.isArray(I)?p.map(I,function(y){return{name:f.name,value:y.replace(Uc,`\r
|
|
44
|
-
`)}}):{name:f.name,value:I.replace(Uc,`\r
|
|
45
|
-
`)}}).get()}});var I0=/%20/g,C0=/#.*$/,y0=/([?&])_=[^&]*/,v0=/^(.*?):[ \t]*([^\r\n]*)$/mg,E0=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,T0=/^(?:GET|HEAD)$/,S0=/^\/\//,$c={},xa={},Gc="*/".concat("*"),ba=x.createElement("a");ba.href=Ns.href;function Hc(c){return function(f,I){typeof f!="string"&&(I=f,f="*");var y,T=0,S=f.toLowerCase().match(Ye)||[];if(C(I))for(;y=S[T++];)y[0]==="+"?(y=y.slice(1)||"*",(c[y]=c[y]||[]).unshift(I)):(c[y]=c[y]||[]).push(I)}}function Vc(c,f,I,y){var T={},S=c===xa;function L(w){var k;return T[w]=!0,p.each(c[w]||[],function(B,K){var X=K(f,I,y);if(typeof X=="string"&&!S&&!T[X])return f.dataTypes.unshift(X),L(X),!1;if(S)return!(k=X)}),k}return L(f.dataTypes[0])||!T["*"]&&L("*")}function La(c,f){var I,y,T=p.ajaxSettings.flatOptions||{};for(I in f)f[I]!==void 0&&((T[I]?c:y||(y={}))[I]=f[I]);return y&&p.extend(!0,c,y),c}function x0(c,f,I){for(var y,T,S,L,w=c.contents,k=c.dataTypes;k[0]==="*";)k.shift(),y===void 0&&(y=c.mimeType||f.getResponseHeader("Content-Type"));if(y){for(T in w)if(w[T]&&w[T].test(y)){k.unshift(T);break}}if(k[0]in I)S=k[0];else{for(T in I){if(!k[0]||c.converters[T+" "+k[0]]){S=T;break}L||(L=T)}S=S||L}if(S)return S!==k[0]&&k.unshift(S),I[S]}function b0(c,f,I,y){var T,S,L,w,k,B={},K=c.dataTypes.slice();if(K[1])for(L in c.converters)B[L.toLowerCase()]=c.converters[L];for(S=K.shift();S;)if(c.responseFields[S]&&(I[c.responseFields[S]]=f),!k&&y&&c.dataFilter&&(f=c.dataFilter(f,c.dataType)),k=S,S=K.shift(),S){if(S==="*")S=k;else if(k!=="*"&&k!==S){if(L=B[k+" "+S]||B["* "+S],!L){for(T in B)if(w=T.split(" "),w[1]===S&&(L=B[k+" "+w[0]]||B["* "+w[0]],L)){L===!0?L=B[T]:B[T]!==!0&&(S=w[0],K.unshift(w[1]));break}}if(L!==!0)if(L&&c.throws)f=L(f);else try{f=L(f)}catch(X){return{state:"parsererror",error:L?X:"No conversion from "+k+" to "+S}}}}return{state:"success",data:f}}p.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ns.href,type:"GET",isLocal:E0.test(Ns.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Gc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":p.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(c,f){return f?La(La(c,p.ajaxSettings),f):La(p.ajaxSettings,c)},ajaxPrefilter:Hc($c),ajaxTransport:Hc(xa),ajax:function(c,f){typeof c=="object"&&(f=c,c=void 0),f=f||{};var I,y,T,S,L,w,k,B,K,X,H=p.ajaxSetup({},f),ie=H.context||H,De=H.context&&(ie.nodeType||ie.jquery)?p(ie):p.event,$e=p.Deferred(),Me=p.Callbacks("once memory"),It=H.statusCode||{},ht={},ui={},ci="canceled",Ue={readyState:0,getResponseHeader:function(He){var ot;if(k){if(!S)for(S={};ot=v0.exec(T);)S[ot[1].toLowerCase()+" "]=(S[ot[1].toLowerCase()+" "]||[]).concat(ot[2]);ot=S[He.toLowerCase()+" "]}return ot==null?null:ot.join(", ")},getAllResponseHeaders:function(){return k?T:null},setRequestHeader:function(He,ot){return k==null&&(He=ui[He.toLowerCase()]=ui[He.toLowerCase()]||He,ht[He]=ot),this},overrideMimeType:function(He){return k==null&&(H.mimeType=He),this},statusCode:function(He){var ot;if(He)if(k)Ue.always(He[Ue.status]);else for(ot in He)It[ot]=[It[ot],He[ot]];return this},abort:function(He){var ot=He||ci;return I&&I.abort(ot),Hi(0,ot),this}};if($e.promise(Ue),H.url=((c||H.url||Ns.href)+"").replace(S0,Ns.protocol+"//"),H.type=f.method||f.type||H.method||H.type,H.dataTypes=(H.dataType||"*").toLowerCase().match(Ye)||[""],H.crossDomain==null){w=x.createElement("a");try{w.href=H.url,w.href=w.href,H.crossDomain=ba.protocol+"//"+ba.host!=w.protocol+"//"+w.host}catch{H.crossDomain=!0}}if(H.data&&H.processData&&typeof H.data!="string"&&(H.data=p.param(H.data,H.traditional)),Vc($c,H,f,Ue),k)return Ue;B=p.event&&H.global,B&&p.active++===0&&p.event.trigger("ajaxStart"),H.type=H.type.toUpperCase(),H.hasContent=!T0.test(H.type),y=H.url.replace(C0,""),H.hasContent?H.data&&H.processData&&(H.contentType||"").indexOf("application/x-www-form-urlencoded")===0&&(H.data=H.data.replace(I0,"+")):(X=H.url.slice(y.length),H.data&&(H.processData||typeof H.data=="string")&&(y+=(Ta.test(y)?"&":"?")+H.data,delete H.data),H.cache===!1&&(y=y.replace(y0,"$1"),X=(Ta.test(y)?"&":"?")+"_="+Fc.guid+++X),H.url=y+X),H.ifModified&&(p.lastModified[y]&&Ue.setRequestHeader("If-Modified-Since",p.lastModified[y]),p.etag[y]&&Ue.setRequestHeader("If-None-Match",p.etag[y])),(H.data&&H.hasContent&&H.contentType!==!1||f.contentType)&&Ue.setRequestHeader("Content-Type",H.contentType),Ue.setRequestHeader("Accept",H.dataTypes[0]&&H.accepts[H.dataTypes[0]]?H.accepts[H.dataTypes[0]]+(H.dataTypes[0]!=="*"?", "+Gc+"; q=0.01":""):H.accepts["*"]);for(K in H.headers)Ue.setRequestHeader(K,H.headers[K]);if(H.beforeSend&&(H.beforeSend.call(ie,Ue,H)===!1||k))return Ue.abort();if(ci="abort",Me.add(H.complete),Ue.done(H.success),Ue.fail(H.error),I=Vc(xa,H,f,Ue),!I)Hi(-1,"No Transport");else{if(Ue.readyState=1,B&&De.trigger("ajaxSend",[Ue,H]),k)return Ue;H.async&&H.timeout>0&&(L=e.setTimeout(function(){Ue.abort("timeout")},H.timeout));try{k=!1,I.send(ht,Hi)}catch(He){if(k)throw He;Hi(-1,He)}}function Hi(He,ot,Us,Da){var hi,$s,di,Pi,_i,Vt=ot;k||(k=!0,L&&e.clearTimeout(L),I=void 0,T=Da||"",Ue.readyState=He>0?4:0,hi=He>=200&&He<300||He===304,Us&&(Pi=x0(H,Ue,Us)),!hi&&p.inArray("script",H.dataTypes)>-1&&p.inArray("json",H.dataTypes)<0&&(H.converters["text script"]=function(){}),Pi=b0(H,Pi,Ue,hi),hi?(H.ifModified&&(_i=Ue.getResponseHeader("Last-Modified"),_i&&(p.lastModified[y]=_i),_i=Ue.getResponseHeader("etag"),_i&&(p.etag[y]=_i)),He===204||H.type==="HEAD"?Vt="nocontent":He===304?Vt="notmodified":(Vt=Pi.state,$s=Pi.data,di=Pi.error,hi=!di)):(di=Vt,(He||!Vt)&&(Vt="error",He<0&&(He=0))),Ue.status=He,Ue.statusText=(ot||Vt)+"",hi?$e.resolveWith(ie,[$s,Vt,Ue]):$e.rejectWith(ie,[Ue,Vt,di]),Ue.statusCode(It),It=void 0,B&&De.trigger(hi?"ajaxSuccess":"ajaxError",[Ue,H,hi?$s:di]),Me.fireWith(ie,[Ue,Vt]),B&&(De.trigger("ajaxComplete",[Ue,H]),--p.active||p.event.trigger("ajaxStop")))}return Ue},getJSON:function(c,f,I){return p.get(c,f,I,"json")},getScript:function(c,f){return p.get(c,void 0,f,"script")}}),p.each(["get","post"],function(c,f){p[f]=function(I,y,T,S){return C(y)&&(S=S||T,T=y,y=void 0),p.ajax(p.extend({url:I,type:f,dataType:S,data:y,success:T},p.isPlainObject(I)&&I))}}),p.ajaxPrefilter(function(c){var f;for(f in c.headers)f.toLowerCase()==="content-type"&&(c.contentType=c.headers[f]||"")}),p._evalUrl=function(c,f,I){return p.ajax({url:c,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(y){p.globalEval(y,f,I)}})},p.fn.extend({wrapAll:function(c){var f;return this[0]&&(C(c)&&(c=c.call(this[0])),f=p(c,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&f.insertBefore(this[0]),f.map(function(){for(var I=this;I.firstElementChild;)I=I.firstElementChild;return I}).append(this)),this},wrapInner:function(c){return C(c)?this.each(function(f){p(this).wrapInner(c.call(this,f))}):this.each(function(){var f=p(this),I=f.contents();I.length?I.wrapAll(c):f.append(c)})},wrap:function(c){var f=C(c);return this.each(function(I){p(this).wrapAll(f?c.call(this,I):c)})},unwrap:function(c){return this.parent(c).not("body").each(function(){p(this).replaceWith(this.childNodes)}),this}}),p.expr.pseudos.hidden=function(c){return!p.expr.pseudos.visible(c)},p.expr.pseudos.visible=function(c){return!!(c.offsetWidth||c.offsetHeight||c.getClientRects().length)},p.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch{}};var L0={0:200,1223:204},Bs=p.ajaxSettings.xhr();A.cors=!!Bs&&"withCredentials"in Bs,A.ajax=Bs=!!Bs,p.ajaxTransport(function(c){var f,I;if(A.cors||Bs&&!c.crossDomain)return{send:function(y,T){var S,L=c.xhr();if(L.open(c.type,c.url,c.async,c.username,c.password),c.xhrFields)for(S in c.xhrFields)L[S]=c.xhrFields[S];c.mimeType&&L.overrideMimeType&&L.overrideMimeType(c.mimeType),!c.crossDomain&&!y["X-Requested-With"]&&(y["X-Requested-With"]="XMLHttpRequest");for(S in y)L.setRequestHeader(S,y[S]);f=function(w){return function(){f&&(f=I=L.onload=L.onerror=L.onabort=L.ontimeout=L.onreadystatechange=null,w==="abort"?L.abort():w==="error"?typeof L.status!="number"?T(0,"error"):T(L.status,L.statusText):T(L0[L.status]||L.status,L.statusText,(L.responseType||"text")!=="text"||typeof L.responseText!="string"?{binary:L.response}:{text:L.responseText},L.getAllResponseHeaders()))}},L.onload=f(),I=L.onerror=L.ontimeout=f("error"),L.onabort!==void 0?L.onabort=I:L.onreadystatechange=function(){L.readyState===4&&e.setTimeout(function(){f&&I()})},f=f("abort");try{L.send(c.hasContent&&c.data||null)}catch(w){if(f)throw w}},abort:function(){f&&f()}}}),p.ajaxPrefilter(function(c){c.crossDomain&&(c.contents.script=!1)}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(c){return p.globalEval(c),c}}}),p.ajaxPrefilter("script",function(c){c.cache===void 0&&(c.cache=!1),c.crossDomain&&(c.type="GET")}),p.ajaxTransport("script",function(c){if(c.crossDomain||c.scriptAttrs){var f,I;return{send:function(y,T){f=p("<script>").attr(c.scriptAttrs||{}).prop({charset:c.scriptCharset,src:c.url}).on("load error",I=function(S){f.remove(),I=null,S&&T(S.type==="error"?404:200,S.type)}),x.head.appendChild(f[0])},abort:function(){I&&I()}}}});var Kc=[],Ra=/(=)\?(?=&|$)|\?\?/;p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var c=Kc.pop()||p.expando+"_"+Fc.guid++;return this[c]=!0,c}}),p.ajaxPrefilter("json jsonp",function(c,f,I){var y,T,S,L=c.jsonp!==!1&&(Ra.test(c.url)?"url":typeof c.data=="string"&&(c.contentType||"").indexOf("application/x-www-form-urlencoded")===0&&Ra.test(c.data)&&"data");if(L||c.dataTypes[0]==="jsonp")return y=c.jsonpCallback=C(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,L?c[L]=c[L].replace(Ra,"$1"+y):c.jsonp!==!1&&(c.url+=(Ta.test(c.url)?"&":"?")+c.jsonp+"="+y),c.converters["script json"]=function(){return S||p.error(y+" was not called"),S[0]},c.dataTypes[0]="json",T=e[y],e[y]=function(){S=arguments},I.always(function(){T===void 0?p(e).removeProp(y):e[y]=T,c[y]&&(c.jsonpCallback=f.jsonpCallback,Kc.push(y)),S&&C(T)&&T(S[0]),S=T=void 0}),"script"}),A.createHTMLDocument=(function(){var c=x.implementation.createHTMLDocument("").body;return c.innerHTML="<form></form><form></form>",c.childNodes.length===2})(),p.parseHTML=function(c,f,I){if(typeof c!="string")return[];typeof f=="boolean"&&(I=f,f=!1);var y,T,S;return f||(A.createHTMLDocument?(f=x.implementation.createHTMLDocument(""),y=f.createElement("base"),y.href=x.location.href,f.head.appendChild(y)):f=x),T=ne.exec(c),S=!I&&[],T?[f.createElement(T[1])]:(T=yc([c],f,S),S&&S.length&&p(S).remove(),p.merge([],T.childNodes))},p.fn.load=function(c,f,I){var y,T,S,L=this,w=c.indexOf(" ");return w>-1&&(y=$i(c.slice(w)),c=c.slice(0,w)),C(f)?(I=f,f=void 0):f&&typeof f=="object"&&(T="POST"),L.length>0&&p.ajax({url:c,type:T||"GET",dataType:"html",data:f}).done(function(k){S=arguments,L.html(y?p("<div>").append(p.parseHTML(k)).find(y):k)}).always(I&&function(k,B){L.each(function(){I.apply(this,S||[k.responseText,B,k])})}),this},p.expr.pseudos.animated=function(c){return p.grep(p.timers,function(f){return c===f.elem}).length},p.offset={setOffset:function(c,f,I){var y,T,S,L,w,k,B,K=p.css(c,"position"),X=p(c),H={};K==="static"&&(c.style.position="relative"),w=X.offset(),S=p.css(c,"top"),k=p.css(c,"left"),B=(K==="absolute"||K==="fixed")&&(S+k).indexOf("auto")>-1,B?(y=X.position(),L=y.top,T=y.left):(L=parseFloat(S)||0,T=parseFloat(k)||0),C(f)&&(f=f.call(c,I,p.extend({},w))),f.top!=null&&(H.top=f.top-w.top+L),f.left!=null&&(H.left=f.left-w.left+T),"using"in f?f.using.call(c,H):X.css(H)}},p.fn.extend({offset:function(c){if(arguments.length)return c===void 0?this:this.each(function(T){p.offset.setOffset(this,c,T)});var f,I,y=this[0];if(y)return y.getClientRects().length?(f=y.getBoundingClientRect(),I=y.ownerDocument.defaultView,{top:f.top+I.pageYOffset,left:f.left+I.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var c,f,I,y=this[0],T={top:0,left:0};if(p.css(y,"position")==="fixed")f=y.getBoundingClientRect();else{for(f=this.offset(),I=y.ownerDocument,c=y.offsetParent||I.documentElement;c&&(c===I.body||c===I.documentElement)&&p.css(c,"position")==="static";)c=c.parentNode;c&&c!==y&&c.nodeType===1&&(T=p(c).offset(),T.top+=p.css(c,"borderTopWidth",!0),T.left+=p.css(c,"borderLeftWidth",!0))}return{top:f.top-T.top-p.css(y,"marginTop",!0),left:f.left-T.left-p.css(y,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var c=this.offsetParent;c&&p.css(c,"position")==="static";)c=c.offsetParent;return c||Ui})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(c,f){var I=f==="pageYOffset";p.fn[c]=function(y){return Re(this,function(T,S,L){var w;if(v(T)?w=T:T.nodeType===9&&(w=T.defaultView),L===void 0)return w?w[f]:T[S];w?w.scrollTo(I?w.pageXOffset:L,I?L:w.pageYOffset):T[S]=L},c,y,arguments.length)}}),p.each(["top","left"],function(c,f){p.cssHooks[f]=bc(A.pixelPosition,function(I,y){if(y)return y=Os(I,f),Aa.test(y)?p(I).position()[f]+"px":y})}),p.each({Height:"height",Width:"width"},function(c,f){p.each({padding:"inner"+c,content:f,"":"outer"+c},function(I,y){p.fn[y]=function(T,S){var L=arguments.length&&(I||typeof T!="boolean"),w=I||(T===!0||S===!0?"margin":"border");return Re(this,function(k,B,K){var X;return v(k)?y.indexOf("outer")===0?k["inner"+c]:k.document.documentElement["client"+c]:k.nodeType===9?(X=k.documentElement,Math.max(k.body["scroll"+c],X["scroll"+c],k.body["offset"+c],X["offset"+c],X["client"+c])):K===void 0?p.css(k,B,w):p.style(k,B,K,w)},f,L?T:void 0,L)}})}),p.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(c,f){p.fn[f]=function(I){return this.on(f,I)}}),p.fn.extend({bind:function(c,f,I){return this.on(c,null,f,I)},unbind:function(c,f){return this.off(c,null,f)},delegate:function(c,f,I,y){return this.on(f,c,I,y)},undelegate:function(c,f,I){return arguments.length===1?this.off(c,"**"):this.off(f,c||"**",I)},hover:function(c,f){return this.on("mouseenter",c).on("mouseleave",f||c)}}),p.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(c,f){p.fn[f]=function(I,y){return arguments.length>0?this.on(f,null,I,y):this.trigger(f)}});var R0=/^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;p.proxy=function(c,f){var I,y,T;if(typeof f=="string"&&(I=c[f],f=c,c=I),!!C(c))return y=r.call(arguments,2),T=function(){return c.apply(f||this,y.concat(r.call(arguments)))},T.guid=c.guid=c.guid||p.guid++,T},p.holdReady=function(c){c?p.readyWait++:p.ready(!0)},p.isArray=Array.isArray,p.parseJSON=JSON.parse,p.nodeName=N,p.isFunction=C,p.isWindow=v,p.camelCase=at,p.type=D,p.now=Date.now,p.isNumeric=function(c){var f=p.type(c);return(f==="number"||f==="string")&&!isNaN(c-parseFloat(c))},p.trim=function(c){return c==null?"":(c+"").replace(R0,"$1")};var D0=e.jQuery,P0=e.$;return p.noConflict=function(c){return e.$===p&&(e.$=P0),c&&e.jQuery===p&&(e.jQuery=D0),p},typeof t>"u"&&(e.jQuery=e.$=p),p})})(_r)),_r.exports}var Km=Vm();const Bi=Gm(Km),Ut={None:"none",DualLayer:"dual-layer",Segments:"segments",MinimalWave:"minimal-wave"},Ym={[Ut.None]:`
|
|
1
|
+
(function(kt,Oe){typeof exports=="object"&&typeof module<"u"?Oe(exports):typeof define=="function"&&define.amd?define(["exports"],Oe):(kt=typeof globalThis<"u"?globalThis:kt||self,Oe(kt.V360Player={}))})(this,(function(kt){"use strict";const Oe={None:"none",DualLayer:"dual-layer",Segments:"segments",MinimalWave:"minimal-wave"},Il={[Oe.None]:`
|
|
46
2
|
.progress-bar {
|
|
47
3
|
flex: 1;
|
|
48
4
|
height: 4px;
|
|
@@ -59,7 +15,7 @@ Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
59
15
|
background: #0A84FF;
|
|
60
16
|
border-radius: 2px;
|
|
61
17
|
}
|
|
62
|
-
`,[
|
|
18
|
+
`,[Oe.DualLayer]:`
|
|
63
19
|
.progress-bar {
|
|
64
20
|
flex: 1;
|
|
65
21
|
height: 8px;
|
|
@@ -101,7 +57,7 @@ Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
101
57
|
.progress-bar:hover .progress-handle {
|
|
102
58
|
transform: translateY(-50%) scale(1.2);
|
|
103
59
|
}
|
|
104
|
-
`,[
|
|
60
|
+
`,[Oe.Segments]:`
|
|
105
61
|
.progress-bar {
|
|
106
62
|
flex: 1;
|
|
107
63
|
height: 4px;
|
|
@@ -138,7 +94,7 @@ Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
138
94
|
.progress-segment.filled:hover {
|
|
139
95
|
background: #40A2FF;
|
|
140
96
|
}
|
|
141
|
-
`,[
|
|
97
|
+
`,[Oe.MinimalWave]:`
|
|
142
98
|
.progress-bar {
|
|
143
99
|
flex: 1;
|
|
144
100
|
height: 2px;
|
|
@@ -175,7 +131,7 @@ Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
175
131
|
50% { transform: translateY(-50%) scaleY(0.6); }
|
|
176
132
|
100% { transform: translateY(-50%) scaleY(1); }
|
|
177
133
|
}
|
|
178
|
-
`},
|
|
134
|
+
`},He={play:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
179
135
|
<path d="M8 5v14l11-7z"/>
|
|
180
136
|
</svg>`,pause:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
181
137
|
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
|
|
@@ -185,226 +141,317 @@ Schedule: ${l.map(C=>Ft(C))} pos: ${this.timelinePos}`),h.length&&this.log(`Remo
|
|
|
185
141
|
<path d="M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z"/>
|
|
186
142
|
</svg>`,fullscreen:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
187
143
|
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>
|
|
188
|
-
</svg>`,"speed-0.50":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUADXo0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7KrC+8P9nTvYJgEtZyvka/xNzvdBc6qomVfhKJdHftjR9FLP56ErolkesRo9EuoXELCZwddAvVc1pZL+Ncl7MdZ99tK4nzSLEbjsta/n33P7+qIXjfMI8yHkGwoRS4HZD6WpKJBKEkQDpSKti7LJn55goC8itM9Ydo0pqv6ctADlXuLXtvTMy3la4g8BTnf65f2RPaaygr9l5k1rhY/2l1OqbQ9RX8Ff/QYa81YRdWMUOdrUbelrBbGAYfOqSNBL2+OxyDhKxfkwK5u2Ap9a9uO3KgQA9cgpU6VBh2rbtTgovKR2NFgbizLGOJcuMnJD5kGuxTpEoDcFnYVvvtCa9qytbRmC8zcCUOZIEb45O2c3v1gjHkUiLa4xwp+Mc9gw41JbpYYBiI0rqDaCvAtP6fJVUDQZpTnESkI7H5K7EZ/bgJZoAUDDfV5Bsn7JYAQYWqDMzgTSqBGYpRpc2YnQiADgCpcZ1HeQYDMuMNJVpEMNsFzanzitIayMcwJdlxmIGGSxcGmSAUsVcP+cQ3soWpiambZ3MKK1SxZs+WcPc9Lsbq4JjfP7h5evIaEhkUOj4gStXARXJpWcvESpZRaMWeFcsXXFQNq3XmXXXdLe959j73stWH7NG3WcvMWrbTauUvH/dFz9x699HrQga106GFHPvyIoxx1YKsNSUOHjTx8xCij3qldWL/lN6jRRY0XqTnQ79Rgdb9J0LxObDIDME5KIO4TATY0T2ZbkCpPcpPZVhinwhhO2mTWaRIDQT2IbdCNXeKT6CT3v7gl1wdu/F/JpYnuTXLfub2i1ufPUFvEzlM4g7oJTh/6j6gcdf7YfavT3zrerT9CH6GP0EfoI/QR+gj9Q0IDfzzM/wJ/AwtlqMgGWC/6AAAAYXpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHjaPYk7DoAwDEP3nIIj5GPUch2Sha0D9xemUuunWLGePONNOWbgEh2OC6UgO1aW6tH49vBQ3sm2n2mS5uYCMZomXmuqygcwfhTVhYB0sAAAAYVpQ0NQSUNDIHByb2ZpbGUAAHicfZE9SMNQFIVPW7VWKw52EHHIUJ0siIo4ahWKUCHUCq06mLz0D5o0JCkujoJrwcGfxaqDi7OuDq6CIPgD4i44KbpIifclhRYxXni8j/PuObx3H+Cvl5lqdowDqmYZqURcyGRXheArfOhFCF0ISczU50QxCc/6uqduqrsYz/Lu+7P6lJzJAJ9APMt0wyLeIJ7etHTO+8QRVpQU4nPiMYMuSPzIddnlN84Fh/08M2KkU/PEEWKh0MZyG7OioRJPEUcVVaN8f8ZlhfMWZ7VcZc178heGc9rKMtdpDSOBRSxBhAAZVZRQhoUY7RopJlJ0HvfwDzl+kVwyuUpg5FhABSokxw/+B79na+YnJ9ykcBzofLHtjxEguAs0arb9fWzbjRMg8AxcaS1/pQ7MfJJea2nRI6B/G7i4bmnyHnC5Aww+6ZIhOVKAlj+fB97P6JuywMAt0LPmzq15jtMHIE2zSt4AB4fAaIGy1z3e3d0+t397mvP7AdDBcmazf/6+AAAPw2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImdpbXA6ZG9jaWQ6Z2ltcDpmNzU5ZmE3Zi1mYWYzLTRiYjUtOTU2OC01ZWZmOTQ5MzhmOWEiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MmE1YTUxZWQtMjFkNi00MzY2LWJmY2ItZDcyNzJjNzdhN2U3IgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6MGI4NjEwY2EtMDU3Ni00MTJlLTg2NzEtYjRjZWU1YzJkZGFiIgogICBkYzpGb3JtYXQ9ImltYWdlL3BuZyIKICAgR0lNUDpBUEk9IjIuMCIKICAgR0lNUDpQbGF0Zm9ybT0iTGludXgiCiAgIEdJTVA6VGltZVN0YW1wPSIxNzM2NTg2NjY3OTU1MTQ1IgogICBHSU1QOlZlcnNpb249IjIuMTAuMzAiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdG9yVG9vbD0iR0lNUCAyLjEwIj4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6ZTZkNDA1MzYtMmM4Mi00YmMyLTgwYzctYWM2ZjU0ZGM3YjIxIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNToxMTozNiswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDphN2IwZGUxZi1iYmFhLTQ1ZWQtOGU3Mi1mNzIxZDViMGUzZmIiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjMyOjIwKzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjZiNTdlZmMzLTdmNjMtNGE0MS1hZWYzLTc4MGQ0NzU1YmRjZiIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTEtMDNUMTI6MjE6NTUrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MzJhOTk4N2MtMWE5ZS00MjNiLWJiZGUtMWQxMmE2Njg4MDQ1IgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyNS0wMS0xMVQxNDo0MTowNyswNTozMCIvPgogICAgPC9yZGY6U2VxPgogICA8L3htcE1NOkhpc3Rvcnk+CiAgPC9yZGY6RGVzY3JpcHRpb24+CiA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz64X1WPAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6QELCQsHZb85vAAABP5JREFUeNrtm2toXEUUgL+ka0xM0lQ2YlCs1aYlaCHxnVqxUir4qLZaS7UI9odVqq2g+IT8kZaqoIjxjfgCkdbaH6Xon7RUrdhCqZWUCkbUGmwVnzE20aZu1h/3LDm5vfu4m4m79+75YODu7MyZe8+eO+fMmVkwDMMwDMMwDMMwDMMwjMhQFeF7rwYagKlS5gGnA33AEeBzYNh+4vE0ArcDHwAjQDpHOQ7sB14GVgJtETeYojkZWAJsEotKT6D8ANwFJCrlFV4CvAU0+er/ArYCXwODQBLoku+6gO+AS4BO4AL5ETRfSbstotjY8r6ynmFgM3ALUOdr16naLQ+w4E7gYZkbtUXuBRbGWYGzgGeAOwKsUHOhUspNOdqdAjwK/O5T5Bb5rmKpFiV8JJ45H6cCTwBDSom7gWbz0+E4A/hUKfFPYH5UnUhSPG19lu+/kRDGNXXAZ0CHfB4GzgO+j5o1LCwgDJmao/9c4DZgSshxVwGjvnH2ADVRU2AS2C5zUVB5J0+AfVQe/oYQY14DpJSX71FK7K6kuWymevA1IfqtU8q7WqaPA0rWskpR4Cz10PeE6NcMPA5cpuraJDhPAz9WSngzWylwtQN5q5W8+ytBgW3qge92IK9GvHBeK6wu8YNPA1oKKI0hwjEXa9sRYINctziyaudMB/4uMIsyELD+1Zyv2t7p6P5qgEMi80A5WmAzUFtg26Y8VujaAjNWuFGu58gPfgKJEirwCwlipxXQ9gjwc561cIZRh/f4IfCIXF8HvBJXJ9KuXuFVDuUmgD9E7ra4Km+FeMqMAkeBp0JMD/nYLHJ/i6Pyns7hePZxYia6GDYomXVxUt4ilQQYAl4EXgMOqwde52CcNUrezFzea7KpAm6VpEEYBoB3A5xDj2RwUnj7HplQoxZv8ygpa9yGIjzzWcD1Mge2q9DoSmBXOaxXw5YOn6yTVAy5MWCsbtX3zCLutS/LfXSVMg4cBI4V0e+4WKG/bkSuWwP6ZKw8JYoOy5dZ6g+X8hUG7+RAY8g+Q+Jl/ewCrpDrxRJmpGVu3CrGsQcv0VoMM+QVXgQ8K3WX4u3kxYK5jCVDM5vm+tX7l5D7G1lYq2TOiFsY85C8zv656hhwr6Mx1iu5DcSQi/BS/pmH3BngdCbCTpHbT4y5SilwsUO5DWLNaeD1cksm1ANvk/vEgU4mrMwRz2WC5yrHS675jO3O9ZSb1XSGjAXzxXNLHScSAF6SsVNkObVQyo31JrxzfoVa4LW4TVXl4zS8U171eBvv8zBC8aSy/htNHeFIMra1uZ8KPdk6EV5Q1nezqSM77eJd71N1yxifU4yU9dVK7BVUJuOwj57n1ktiYkA+/0pA/q+caSX3Nmc/7rNHs4Ff1Bg/MXbCf0GUVxNBJTVJa9F2Cb71WGsL7ZwoIwXuBh4j+wHLQ3hH2Fwzwvg85T7g+Up0CHUUtsesWeGzvt4CA/vYUS/z11GynCDw0QbsYHz660FKf1bIOUuBg8AbwOUFrquX52g3B3hOZVjSeEnYi+NqWe/5JvdemeBbfdaSTYFVwNl4W5N7AxzTm8Q0SapDm20EZ50H8fZFuoFXVf0mvD3ijxk7lqHLP9JmARVEi8xRvRS/NXoQeADHf6aJ4iK5Q+bGc8VhTMfLFU5RYUm/hD3f4qWkPsFLSTknLlmGBHCOKLGP/zdvaBiGYRiGYRiGYRiGYRhR4T+g4LtceW1yGQAAAABJRU5ErkJggg==" width="24" height="24" alt="0.5x speed">',"speed-1.00":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUADXo0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7KrC+8P9nTvYJgEtZyvka/xNzvdBc6qomVfhKJdHftjR9FLP56ErolkesRo9EuoXELCZwddAvVc1pZL+Ncl7MdZ99tK4nzSLEbjsta/n33P7+qIXjfMI8yHkGwoRS4HZD6WpKJBKEkQDpSKtqJr2vnyBAF5Fad7wrRpTFf15aAHKvcWvbanZ1rK1xB5CnK+1y/tiew1lRX6LzNrXC1+tLucUml7iv4K/ugx1pqxiqoZoc7Xom5LWS2MAw6dU0eCXt4cj0HCVy7IgV3dsBX61rYduVEhBq5BSp0qDTpW3ajBReUjsaPB3FiWMcS5cJOTHzINdinSJUCyLexgeveF1rRla2nNFpi5E4YyQYzwyds5vfvBGPMoEG1xjxX8Yp7BhhuT3CwxDERoXEG1FeBbfk6Tq4CgzSjPI1IQ2P2U2I3+3ASyQAsGGurzDJL3SwAhwtQGZ3AmlECNxCjT5sxOhEAGAFW4zqK8gwCZcYeTrCIZbILn1PjEaQ1lY5gT7LjMQMIki4NNkQpYqob94xrYQ9XE1MyyuYUVq1myZss5e56XYnVxTW6e3T28eA0JDYscHhElauEiuDSt5OIlSim1Ys4K5YqvKwbUuvMuu+6W9rz7HnvZa8P2adqs5eYtWmm1c5eO+6Pn7j166fWgA1vp0MOOfPgRRznqwFYbkoYOG3n4iFFGvVO7sH7Lb1CjixovUnOg36nB6n6ToHmd2GQGYJyUQNwnAmxonsy2IFWe5CazrTBOhTGctMms0yQGgnoQ26Abu8Qn0Unuf3FLrg/c+L+SSxPdm+S+c3tFrc+fobaInadwBnUTnD70H1E56vyx+1anv3W8W3+EPkIfoY/QR+gj9BH6h4QG/niY/wX+BtKUqMT2Ahu4AAAAYHpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHja48osKEnmUgADEyMuYwsTIxNLkxQDEyCEA8MUw2QDI2NzINPC2MjYAIhNgaQhCIJlkoEySUCeCRCC5bmMUmBcAwMuADBKFNK6HFPnAAABhWlDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw1AUhU9btVYrDnYQcchQnSyIijhqFYpQIdQKrTqYvPQPmjQkKS6OgmvBwZ/FqoOLs64OroIg+APiLjgpukiJ9yWFFjFeeLyP8+45vHcf4K+XmWp2jAOqZhmpRFzIZFeF4Ct86EUIXQhJzNTnRDEJz/q6p26quxjP8u77s/qUnMkAn0A8y3TDIt4gnt60dM77xBFWlBTic+Ixgy5I/Mh12eU3zgWH/TwzYqRT88QRYqHQxnIbs6KhEk8RRxVVo3x/xmWF8xZntVxlzXvyF4Zz2soy12kNI4FFLEGEABlVlFCGhRjtGikmUnQe9/APOX6RXDK5SmDkWEAFKiTHD/4Hv2dr5icn3KRwHOh8se2PESC4CzRqtv19bNuNEyDwDFxpLX+lDsx8kl5radEjoH8buLhuafIecLkDDD7pkiE5UoCWP58H3s/om7LAwC3Qs+bOrXmO0wcgTbNK3gAHh8BogbLXPd7d3T63f3ua8/sB0MFyZrN//r4AAA/DaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA0LjQuMC1FeGl2MiI+CiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICB4bWxuczpHSU1QPSJodHRwOi8vd3d3LmdpbXAub3JnL3htcC8iCiAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyIKICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIKICAgeG1wTU06RG9jdW1lbnRJRD0iZ2ltcDpkb2NpZDpnaW1wOmIwMWJkMTBiLTY4ZTUtNDI3Yy05MjZjLWYxMmI1NGE5MDIxZSIKICAgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyYWRhMTI4OS0yMDdiLTQwYTMtYjdjNS02OTc4NGQ1Yjc3NTIiCiAgIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NDQ3MTYxMC0zYWY0LTQ0MDAtYTZiMC02NGJjZDgyNDIzMzEiCiAgIGRjOkZvcm1hdD0iaW1hZ2UvcG5nIgogICBHSU1QOkFQST0iMi4wIgogICBHSU1QOlBsYXRmb3JtPSJMaW51eCIKICAgR0lNUDpUaW1lU3RhbXA9IjE3MzY1ODY3MjI2MDkwNzgiCiAgIEdJTVA6VmVyc2lvbj0iMi4xMC4zMCIKICAgdGlmZjpPcmllbnRhdGlvbj0iMSIKICAgeG1wOkNyZWF0b3JUb29sPSJHSU1QIDIuMTAiPgogICA8eG1wTU06SGlzdG9yeT4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDoxMTg0Y2IxMi1lMTE2LTRlNTEtYTdlYi05ZTBhY2ZhMWNmZDIiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjExOjM4KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmQ5OTdhZmU2LTAwYzQtNDhiYS05MzYxLTRmZmU3MWFlNjIwYSIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTAtMzFUMTU6MzI6MTArMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MzRlYTZjOTAtNjY0OS00ZGUwLTk3NjUtZTNiOGIyMDMxNDgxIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMS0wM1QxMjoyMToxOCswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo4MDAxYTYxNy01ZTQxLTQ2YjQtOTk3MS1mMzNhYjIyNDNmMWUiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDI1LTAxLTExVDE0OjQyOjAyKzA1OjMwIi8+CiAgICA8L3JkZjpTZXE+CiAgIDwveG1wTU06SGlzdG9yeT4KICA8L3JkZjpEZXNjcmlwdGlvbj4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/Pk8m2PUAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQfpAQsJDAJalFv0AAAFB0lEQVR42u2bfYgVVRTAf7u+LdvNNXar1azdLFoQtlIqWJCicjH72IrokyJFLaIIo5aWNiusxUAMURApsCCyyCUL2TBLihIiU4wk0z7dDDOzWrNNe7nP1x/3DHvfNO9j3sxr9s07P7jMvJn7NeedO+fcc++AoiiKoiiKoiiKoiiKopQNVWXe9zqgXtI0YAqwE/gN2Ar8oX9xJicCNwKvAUNAOkc6DuwCXgLuA6YCiUoU2higA1gNDOYRWr40CPQAtZUyhC8C+oEJrutJYAPwOXBItG253HsB2AhcArTLsc5Vfj/wtPwpx+KsfYst7RkWwcwBxrvyNVr5nnDdS8jwvR/Y7dLIb4Dbgeq4CvA0YIk8fFOOfPVASoTyaI58CWA+8KNLkB8Dp1e6gVkGbAPOKSDvSUAX8KslxO+AVrXT/hgP9FlC/FteEWVhRK4GHhcrWwhfAfNkqIZJNbAOuEF+p4DpwJbR/u/3F+GGtJWgH1cBR13tDIhhykuUjuVK4BSfGrgr5D5MAd4ExoortF4c9RbgZaBTritZuFs0LgXMleG8wdLEHhVRfmv8GHCNde1UYK9lVM5SMWXSKcM0Fx2WFq5SkY3Q68MgfSj5kkBz1G5MU4C2UsDBEPqwEHhGzg8C5wJ/5sh/BfC+nD8vEZ1IeDFgBCUNPBWwD11WXb/L3LgQHC08DJwQlQC3hCDAvgDtP2jVc0iiM4UyzyrbEZUfeBdwfYAhPAysLbLsvYyEuYbE2m71Ud5xaaqk7KY4G4ix4oI4zLYiNEPAZUXWu13q2B1Xwd0MfIYJjKYlwvKOJbwjwIwA9dsxyca4CW95nndnUoIWQZhj1XdBnIR3rcxTHSu5BngW+N564O0htDPTqm9WKY1IG3B5yELaL5N9rwn9HZZhug74SM57JJrSDFyIiVYf9tluIya8VQtMtK6XbFpXBewLwV3xStmG4Bdyf4fHvXus8lcW8TxvZ+nLG+6MYS2mODG0sEkCP2W5d0SODR5Obot1PlhEu19mub6vlFO5GlfHw2AQs8vAixXiJAMsBbplqLcAn2IWif4BxsnRL5MkWtMmrxGAO4FX42JEbnENr1/EaBy3ri0OoZ1ZVn0z4yK8yWSuqHmlt2RUBGW2Vee0KKZypaDTcmqXynGqXNspc+f1IbU1XY7HgG/jooFNwOvWO7CU7BHt2xxVMOFWzG6AIPHAJYzE5gAOALf9D31vBc6W83ej0pYdIfiC/RH1/SGrD+1RaeBK4IGA4azVEQivBlgg5z/jLwymkBlMfUTF4Y+EWFzHv6xTkfhjgaV93SqO7JwhBqqXkS0mF2MW1NMSDRo3mh+gFji5wDSmBO3PtTRtjTjijt+XtJzoUUm3a96aLw2IIMOkAbNpyWnDDsnNH+3DZ10R/mApdpBOwuyVtttZ4cfaREWXONl+trd9XYJ+DGP2B2L5fA9XokGowWxK98MMMtdQ9lLB+6S3YQKnlxaQd6IYDfurpmWYL6FiRTvmY5o+TGCzOocxcISxMEd9k4FFmEUmJ/8Bgi99jlp6XS/3PcCTwPmu93euD20mYIKiH3hY/Y389yuoWNEAvAL85WGRj2I2Lq0ic/fAJuA54D2ZhrnLDWNW3W6ivL9W9UW9+GWbffqOaZeBWETIC1/l+A+chwnStmIWz5vFl3MMQArzKdeApB+AT0QjUyieVANnYnYiJFQciqIoiqIoiqIoiqIoiuLJv3j56EqFGeTaAAAAAElFTkSuQmCC" width="24" height="24" alt="1x speed">',"speed-1.50":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUAEHr0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7JrCO8P/ek+wOgS1HK+Rr7sb/10FziripZ9EYp2DeyPA0Uv/XgSuiaS6RGj0S+hcgkJnwN0CdRzWVsu4V+XsB9n3W8rifNJsxiNy1r/fo49v6sjet0wjzAfQrKhFLkckPlYkooGoSRBOFAq2oqhCtNyeYKAvIrTPcEujemqvjR6oHJv0ev+9ExL+TKRpyDne/2yP5G9prJC/2VmjavFj/0up1TanqK/gj96jLVmrKJqRqjztajbUlYLdsChc+pI0Mub4zFI+MoFObCrG7ZC39q2IzcqxMA1SKlTpUHHqhs1uKh8JHY0mBvL6gxxLtzk5IdMg12KdAmQbAs7mN59oTVt2VpaswVm7gRTJogRPnk7p3c/GGMeBaIt7rGCX8wz2HBjkpslzECExhVUWwG+5ec0uQoI2ozyPCIFgd1Pid3oz00gC7TA0FCfZ5C8XwIIEaY2OIMzoQRqJEaZNmd2IgQyAKjCdRblHQTIjDucZBXJYBM8p8YnTsuUjdGd0I/LDCRMsjjYFKmApWrYP66BPVRNTM0sm1tYsZola7acs+d5KVYX1+Tm2d3Di9eQ0LDI4RFRohYugkvTSi5eopRSK+asUK74usKg1p132XW3tOfd99jLXhu2T9NmLTdv0Uqrnbt03B89d+/RS68HHdhKhx525MOPOMpRB7bakDR02MjDR4wy6p3ahfVbfoMaXdR4kZqGfqeGXvebBM3rxCYzAOOkBOI+EWBD82S2BanyJDeZbYVxKozhpE1mnSYxENSD2Abd2CU+iU5y/4tbcn3gxv+VXJro3iT3ndsran3+DLVF7DyFM6ib4PRh/IjKUeeP3bc6/W3g3foj9BH6CH2EPkIfoY/QPyQ08MfD/C/wN2CdqM5T/ye5AAAAYXpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHjaPYnBDYAwDAP/mYIRktiIdh3SD78+2F+YSuCTLVu2a95l2xLT0JjsHE7xK0aUJw7VhoTLuzJe1lN6Ti2KBNAtxzfd7QEw5hTcAducfAAAAYVpQ0NQSUNDIHByb2ZpbGUAAHicfZE9SMNQFIVPW7VWKw52EHHIUJ0siIo4ahWKUCHUCq06mLz0D5o0JCkujoJrwcGfxaqDi7OuDq6CIPgD4i44KbpIifclhRYxXni8j/PuObx3H+Cvl5lqdowDqmYZqURcyGRXheArfOhFCF0ISczU50QxCc/6uqduqrsYz/Lu+7P6lJzJAJ9APMt0wyLeIJ7etHTO+8QRVpQU4nPiMYMuSPzIddnlN84Fh/08M2KkU/PEEWKh0MZyG7OioRJPEUcVVaN8f8ZlhfMWZ7VcZc178heGc9rKMtdpDSOBRSxBhAAZVZRQhoUY7RopJlJ0HvfwDzl+kVwyuUpg5FhABSokxw/+B79na+YnJ9ykcBzofLHtjxEguAs0arb9fWzbjRMg8AxcaS1/pQ7MfJJea2nRI6B/G7i4bmnyHnC5Aww+6ZIhOVKAlj+fB97P6JuywMAt0LPmzq15jtMHIE2zSt4AB4fAaIGy1z3e3d0+t397mvP7AdDBcmazf/6+AAAPw2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImdpbXA6ZG9jaWQ6Z2ltcDplNDBjOGRjOC1kY2QwLTRkMTctYmJiYy03YWNlOWM1NTQ0OGIiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6YmJhNjM3NmYtZGU4Yy00NmM3LTljZjMtZjQ3Nzc4MWJlZjJkIgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ODI2OWFlMzQtYThmMy00OTg2LTgyOGMtYzgwZDJkYzg5MGM2IgogICBkYzpGb3JtYXQ9ImltYWdlL3BuZyIKICAgR0lNUDpBUEk9IjIuMCIKICAgR0lNUDpQbGF0Zm9ybT0iTGludXgiCiAgIEdJTVA6VGltZVN0YW1wPSIxNzM2NTg2NzU5MzM3NjcwIgogICBHSU1QOlZlcnNpb249IjIuMTAuMzAiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdG9yVG9vbD0iR0lNUCAyLjEwIj4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6NzBiNTI5NjQtNTc0NC00NmNiLWE5NDYtYjYwMmNjMWVkOWRmIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNToxMTo0MSswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo0YmZmMjFlNy03ODE5LTQyYzgtODAwYi1lYjFlNmY2MDRiZDQiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjMxOjU5KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmQ3YWQ3ZmQ3LWY0YTItNDM2MC05ZDE1LTgwM2E0NzliZDFhMCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTEtMDNUMTI6MjA6NDQrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6YjUwZjgyM2QtYjEzNy00ODUxLTk3NGEtOGQxMDE4YmIwOThkIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyNS0wMS0xMVQxNDo0MjozOSswNTozMCIvPgogICAgPC9yZGY6U2VxPgogICA8L3htcE1NOkhpc3Rvcnk+CiAgPC9yZGY6RGVzY3JpcHRpb24+CiA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz53lMvMAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6QELCQwnEZCPswAABNZJREFUeNrtm2uIVVUUgD9nUhvL0Ap7EDOOlmMxPc0cGBKNkH74qLCcHxFR2EPwTxYkQQQWJo5GRIX1J9FIf/ig1IEaqIgY1LG0iIjKsdBQnCy1cnzMmX7sdbj7ns45d87cfe69c+76YMO9++579j7rrL3X2muvA4qiKIqiKIqiKIqiKIoybBgxjMdeA1xmlTlSfxg4BBwAzuojzudK4GngM6AfGIgpfUAX8DrQBkyqVqGNBR4BdgLnCgitUPkBWOhy5lX6FF4CtAN1gfpeYDvwK/AXcBPwjPz2BOABM4AWoBm4KPD/bmA50Jl17eu2tOcUsB64L0QgbVa7lsBvlwCzgBUibFsjO4HpWRbgXcAamXZ1Me0esIRye0y78cBK4B+rvQe8FfJQqopLgc+BLWKdC3Et8E5gTf0IGKN2OhlNYlh8IR4DplayERkn0yWpS+EB7wHvpzCmK4D9wHXy/ZgI9mQlPvGFRbggv6U0phUhfW0drHJVuwYuBt6VzyeAg8Cd8n0ZsFZXuXg2iMb1ArcCVwO/S905oFVFFE+jTGHbcMwEzosQ9w/zeEHZWGWthw+qOIZmmU+JAA/E+Za1KQYALhcHt9jSJ0aklJyRe7gbuAr4TvzFkvCw3PSAo3JQ9rPl0MLTMoYdUY1qUuj4ZmC0w+s1yM2Umj8wITSA2VF78TQ20K8BPTKFXbA3RSe6ELuARbJHngV0ZHXRvxgT95vi+LoTyEW+38yq4FZZfpu/5XvUYR975bpfZ014o4F9McbH1TbsAytSkylesYR1BHgVWE0uWOoBcx30s1qu1w+MdGVEJgD3A6NStoLbxCXyGQMskKDE81a7yVa7DcA34mG0AxPlc02IB+LXdWMCsj5TgXvk90lW+2tcGbROh35eXFke6PftkDabQsbXlbAfz9oP1/H/sxO/zHPlB/5Ygil6AfglUHc8pF1dhBOchCPWGndWnPcwjgYriok01Kc8hU9GCKxRDMhm4BbRnvmW0zsX+Niamg9Z//UitoVH5YHZitUo8nkKeM5auo5nxYjMlJv2p9cXwPfW9wuYs+FiWWMZkVoyxhKZcsG16jzwrKM+NpILumaSO8TyHsZkKnQA0xxev0cE+CVKYm6wtPqlUgUTmjBh8vGOrrcHeLFMApxjff60VJ2uTcEfbCqTAHdK/39GGZA0NHAj5mjQpQb+VAbhNWMSmZB1tV9XtGRssnYpt6k4knEjuTjgdhVHMkbITsbXvmkqkmhmS2CkzapbZhmvbZU46FqSH22mlbf3oaVpizGpHH7O4M+U5zArlskS+UjqxnjAuhTG0wr8a/Vxglw6cXMlat+8InzBtFyZe8k/x/YwweJBUeq84A7gcYaW3rYlpTGdkWnrn2VvrVbLO474RPSwtXipNYUHMGH9kdUovHrgb0xgdDBpIC2YY0r7FYrHsiiYpZjEnjcwKSNRLLKEMaOA4NaT/5rYHuD6rGrW7oAh+UrW0InkH0dEvWhTgwlJvUB+Nr4fYV6Z9Sk7HfNioRdilXsxIaZ2zPmIX79OSpdM6+D/TmPyratqh9EIvIw5pRuqG7QbeBKT9+d03zfc9qmtmFO4BjEe9ZgDb/9e+jDvCx/CHE/2AJ8A3+rONZpRYmQa0KRwRVEURVEURVEURVEURYniPzhn3IN1irUKAAAAAElFTkSuQmCC" width="24" height="24" alt="1.5x speed">',"speed-2.00":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC83pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZdNkuQoDIX3nGKOYP0hcRwMJqJvMMefB3Z6qrKyFzmz6oiEMGCBn0AfkFXp+PvXSH8hUYmc1DxyyXlD0qKFKxqxnamukjZd5Up2deH9mz3dHQyToJbzNfI1/mGnW+CsKlr2RSja1bF/7yh66ceT0OVI5owYjX4JlUtI+OygS6Cey9pyCf+6hP046/5YSZxPmsVoXNb697Pv+V0d0esGP8J8CMmGUuSagMzHklQ0CCUJwoFS0VbY6jWUzoC8itOd4DaNOVV9OegblbtFr+3pmZbyNUSegpzv+qU9kb2mskL/xbPG1eLvdpdTKm1P0V/BHz3GWjNWUTUj1Pla1B21BWV04NDpOhL08uZ4DBK+ckEO7OqGrdC3tu3IjQoxcA1S6lRp0LHqRg1TVD4SOxrMjWUZQ5wLNzn5IdNglyJdApDbwq7C91xouS1bS8tbwHMnDGWCGOGTt3N694Mx5lEg2uKOFebFPIONaUxys8QwEKFxBdVWgB/5OU2uAoI2ozyPSEFg91NiN/r3JpAFWjDQUJ9nkLxfAggRXBsmgzOhBGokRpk2Z3YiBDIAqGLqLMo7CJAZd0ySVSSDTfB0jU+c1lA2hjnBjssMJEyyONgUqYClatg/roE9VE1MzSybW1ixmiVrtpyz53kpVhfX5ObZ3cOL15DQsMjhEVGiFi6CS9NKLl6ilFIrfFYoV3xdMaDWnXfZdbe059332MteG7ZP02YtN2/RSqudu3TcHz1379FLrwcd2EqHHnbkw484ylEHttqQNHTYyMNHjDLqTe3C+iO/QY0uarxIzYF+U4PV/SFB8zqxyQzAOCmBuE8E2NA8mW1BqjzJTWZbYZwKY0zSJrNOkxgI6kFsgx7sEp9EJ7n/xS25fuPG/5VcmujeJPeT2ytqff4MtUXsPIUzqJvg9KH/iMpR54/djzr9ruPd+iP0EfoIfYQ+Qh+hj9AfJDTwx8P8L/AfxFyow7c2uoEAAABgelRYdFJhdyBwcm9maWxlIHR5cGUgaXB0YwAAeNo9icENgFAMQu+dwhFoqfG7ju3Fmwf3j/gT5QUCwc7rLlumMowjI/dspPjl7YXgpjoYhLwq/WU+pefQSgGSsOhvAvYAMDEUz5cVn3MAAAGFaUNDUElDQyBwcm9maWxlAAB4nH2RPUjDUBSFT1u1VisOdhBxyFCdLIiKOGoVilAh1AqtOpi89A+aNCQpLo6Ca8HBn8Wqg4uzrg6ugiD4A+IuOCm6SIn3JYUWMV54vI/z7jm8dx/gr5eZanaMA6pmGalEXMhkV4XgK3zoRQhdCEnM1OdEMQnP+rqnbqq7GM/y7vuz+pScyQCfQDzLdMMi3iCe3rR0zvvEEVaUFOJz4jGDLkj8yHXZ5TfOBYf9PDNipFPzxBFiodDGchuzoqESTxFHFVWjfH/GZYXzFme1XGXNe/IXhnPayjLXaQ0jgUUsQYQAGVWUUIaFGO0aKSZSdB738A85fpFcMrlKYORYQAUqJMcP/ge/Z2vmJyfcpHAc6Hyx7Y8RILgLNGq2/X1s240TIPAMXGktf6UOzHySXmtp0SOgfxu4uG5p8h5wuQMMPumSITlSgJY/nwfez+ibssDALdCz5s6teY7TByBNs0reAAeHwGiBstc93t3dPrd/e5rz+wHQwXJms3/+vgAAD8NpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDQuNC4wLUV4aXYyIj4KIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIKICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgIHhtbG5zOkdJTVA9Imh0dHA6Ly93d3cuZ2ltcC5vcmcveG1wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIgogICB4bXBNTTpEb2N1bWVudElEPSJnaW1wOmRvY2lkOmdpbXA6NDliOGQ3ODctNzUwMy00OTc3LWIwYTItMGEyZWUwZmRjNjdhIgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmU3MGU2OThlLTZjOWMtNDIzMS04OTExLTE2OTQ1MmUxNWQyMiIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOmIzMWI2YzU3LTY0YTItNGE0Yi04M2U2LTIwYjY0ZmQ1Y2NkYSIKICAgZGM6Rm9ybWF0PSJpbWFnZS9wbmciCiAgIEdJTVA6QVBJPSIyLjAiCiAgIEdJTVA6UGxhdGZvcm09IkxpbnV4IgogICBHSU1QOlRpbWVTdGFtcD0iMTczNjU4NjYzMDc4NzQwNiIKICAgR0lNUDpWZXJzaW9uPSIyLjEwLjMwIgogICB0aWZmOk9yaWVudGF0aW9uPSIxIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCI+CiAgIDx4bXBNTTpIaXN0b3J5PgogICAgPHJkZjpTZXE+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjRjNmY5MTE5LTE2Y2YtNDgyNC1iMWY5LWYxZmNjMDgwNTgzZSIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTAtMzFUMTU6MTE6NDQrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6M2E5MmI5NTQtMGE1Zi00NDI1LWFkMGEtOTRkOGFhMjBjMTU1IgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNTozMTo0MiswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo4OTI1MjY2OS01M2JkLTRlNTktOGE2My1lN2M5ZTgxYzZmNjQiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTExLTAzVDEyOjIwOjQ4KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjA1YjNjZDZjLWUwZGYtNGYzNy04ZTg5LTVmMDFiOTNiZTM2NCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjUtMDEtMTFUMTQ6NDA6MzArMDU6MzAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIAo8P3hwYWNrZXQgZW5kPSJ3Ij8+T3zvpgAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+kBCwkKHhjPoD0AAATqSURBVHja7ZtbbBVFGMd/p0VLSxGIIIIXEChiDAaMl2ii4C3Cg/ogEJqIxngJeGlCUB7UmII+mHglpmrigzFRDAEUJAIx4ZJoA0IUSqq2WFACjUBBQFKL2J7jw3wnDuvZs+cye5bu+X7JJGfPzs7O/vebmW++mQVFURRFURRFURRFURRF6TckYvAMFwBDgKHAKGAm0A6cBvYA+4CUCngu1wH1wFxgbEDeLuA7STuAncCJcmwt44GXgFaxqEJTH7ASmFQuwlUBX/mIsQt4DVgMzAe+l/87gWnAcyLWwQzX/gN8CFwRdwGv9jz4L8ASHwv6UvJ0ZDh3OTBLBE1a5fUArwMXx1nEp4BG4IaAfKtElJ8C8l0PbPC8mJPAfeXuVdwjfeRjOea/A9jmadZPqnOWvyfyCHDGEnJDrh5KKdyYacAiYISDsn4GXgYOhVDP+4EvgAo5bgKeOR/e8DdFuh3e1BhCHYeJf+i912y1wNzYKvUEaAamAIOAP4Ebgb3a0/kzEOgWi9sox/WWFbYA1X4XV6p+9MrIvRtYKINJK3CJWN9ImVc3q1T5z4A6xAq7gFq1wPzoE8t7AKiR39+6HkQqxNTDfpCuiEQcALRJIOM4cJUI6YTJMhqmSpBagMERifioVY96lwXPKZF4KenoJ0Yk4CAJOKSAT1w24QpgOjA1ZH+yV/y03RH2hxuBe4FjwKXSrfR7qoH10rGnrbNWXA/XoakGqzXcEpdR8hrroQ6LhfbKcVI6/7sc3Wuida9FcXI13iU4fD/P0WicfjlvxUnASuCoJdhOYAGwTsRLyfmhDu7VKeWt8CqbicuAGdnmgCWgRzrvzix5rrWCFCswq3QA70u/tUzOzwQ+K2CQnAGMswYzgDFBF9Z43mqU6ajUxw970n+359xo69wrBbzA2T51+surspf0ZPp8oFXq40e39dsbLhvhky9XDvhc1x3UhJPAndKMo27CnQF5WsQqEsATwGbgiLgzb3ry5csOseL0VHU9UIdZSo0Vy63mdQZYi9l5kP7vrKNZzO9S3vK4CTgaswcmW196EJhQpBtzVspaFsfQUzXwKmb95Q/MDoUm4CNHIt5qlbOAMiIBvOdAxEarjAmuggkXAS9iVvnDpA/YhNl+UaiITZblHMIsqHfkUUazWOF+TGzQCY+X2CecGpElDsfsWEgBH2TqHAtlDXBbCS2wpYgyUsDTIuR8zEajLZhw3L6AaxdaOq2jzEnINC9tiasC8g8DTknePcRjR68TEd8G/pY+PBtLLLHnqHTnUhVwfgxmy1sK+NFn2qsIS2UGUyfHFwLbyWOPTNgMkPlpsSmMPmigNGd7dH7HEq8pavEarI642HRA/DHXvGHd47j1ewvmM4pI+dqxP7g4pIHFuzzwq/iAgU0rbB6WEczF9rY2YHVI9TzlOZ6LWcYsO0blmX8kZjnADok9X66jaYPflCsDlZL/pCXeD5jPKmIXqlqLWUBvkNmBH9m+E0lTAzwkYqWFS4pzXRVHq6rj/4s6H2M+aRiSo4DVwO2YL5O8HsFhzOpbrHlWQkneETmJ+XJppUy72ixXZKn8385/i+J26gBeyGWkjdMcdjomyny6QBeoB/gUs2iWcFWp/kgt8CBwE3CllewdCMeA36zUDnyOCfkrPgwGbsZnP7OiKIqiKIqiKIqiKIqilDn/AkkxNGAuRZ+BAAAAAElFTkSuQmCC" width="24" height="24" alt="2x speed">'},jm="X-Jewel-Studio",qm="69d2c1660df6540944e25eb708fb252724ab27fb";class Ri extends HTMLElement{progressBarStyle=Ut.None;_hls;_videoPlayer;background="dark";_autoPlay=!1;_streamLoaded=!1;_startLevel=-1;_hideControlsTimer;_pointerOverControls=!1;controlsHideDelay=3e3;static defaultSpeeds=[.25,.5,.75,1,1.25,1.5,2];static minSpeed=.0625;static maxSpeed=16;_failed=!1;_manifestParsed=!1;_networkRetried=!1;_mediaRecoveries=0;_listenersStarted=!1;isValidProgressBarStyle(e){return Object.values(Ut).includes(e)}svgIcons=Wm;constructor(){super(),this.attachShadow({mode:"open"}),this.setupAutoHide()}static booleanProperties=["autoPlay","showTimeDisplay","showSpeedControl","autoHideControls","debug"];get autoPlay(){return this.hasAttribute("auto-play")}set autoPlay(e){this.toggleAttribute("auto-play",!!e)}get showTimeDisplay(){return this.hasAttribute("show-time-display")}set showTimeDisplay(e){this.toggleAttribute("show-time-display",!!e)}get showSpeedControl(){return this.hasAttribute("show-speed-control")}set showSpeedControl(e){this.toggleAttribute("show-speed-control",!!e)}get autoHideControls(){return this.hasAttribute("auto-hide-controls")}set autoHideControls(e){this.toggleAttribute("auto-hide-controls",!!e)}get debug(){return this.hasAttribute("debug")}set debug(e){this.toggleAttribute("debug",!!e)}log(...e){this.debug&&console.debug("[v360-player]",...e)}fail(e){if(this._failed)return;this._failed=!0,this._hls&&(this._hls.destroy(),this._hls=void 0),window.clearTimeout(this._hideControlsTimer),this.shadowRoot?.querySelector(".video-container")?.classList.add("has-error");const t=this.shadowRoot?.querySelector(".error-message");t&&(t.textContent="Video unavailable"),console.error("[v360-player] Playback failed:",e)}upgradeProperties(){const e=this;for(const t of Ri.booleanProperties)if(Object.prototype.hasOwnProperty.call(this,t)){const i=e[t];delete e[t],this[t]=!!i}}setupAutoHide(){const e=this.shadowRoot;e&&(e.addEventListener("pointermove",t=>{!(t instanceof PointerEvent)||t.pointerType==="touch"||(this._pointerOverControls=!!t.target?.closest?.("#control-bar"),this.showControls())}),e.addEventListener("pointerout",t=>{if(!(t instanceof PointerEvent)||t.pointerType==="touch")return;const i=e.querySelector(".video-container");i&&!i.contains(t.relatedTarget)&&(this._pointerOverControls=!1,this.hideControls())}),e.addEventListener("pointerdown",t=>{!(t instanceof PointerEvent)||t.pointerType!=="touch"||(this._pointerOverControls=!1,this.showControls())}))}showControls(){this.autoHideControls&&(this.shadowRoot?.querySelector(".video-container")?.classList.add("controls-visible"),this.scheduleControlsHide())}scheduleControlsHide(){window.clearTimeout(this._hideControlsTimer),!(this._videoPlayer?.paused||this._pointerOverControls)&&(this._hideControlsTimer=window.setTimeout(()=>this.hideControls(),this.controlsHideDelay))}hideControls(){window.clearTimeout(this._hideControlsTimer),this.shadowRoot?.querySelector(".video-container")?.classList.remove("controls-visible")}static get observedAttributes(){return["video-src","poster-src","auto-play","width","playback-speeds","default-speed","default-quality","show-time-display","show-speed-control","progress-bar-style","background"]}attributeChangedCallback(e,t,i){e==="progress-bar-style"?(this.progressBarStyle=this.isValidProgressBarStyle(i)?i:Ut.None,this.render()):e==="background"&&(this.background=i==="light"?"light":"dark",this.updateControlsColor())}async connectedCallback(){this.upgradeProperties(),this.background=this.getAttribute("background")==="light"?"light":"dark",this._autoPlay=this.autoPlay,this._streamLoaded=this._autoPlay,this._startLevel=parseInt(this.getAttribute("default-quality")||"-1"),this.render(),await this.initializePlayer(),this.updateControlsColor()}renderProgressBar(){switch(this.progressBarStyle){case Ut.DualLayer:return`
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
`;case Ut.Segments:return`
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
</div>
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
display: block;
|
|
208
|
-
}
|
|
209
|
-
.video-container {
|
|
210
|
-
position: relative;
|
|
211
|
-
width: 100%;
|
|
212
|
-
background: var(--player-bg, #000);
|
|
213
|
-
overflow: hidden;
|
|
214
|
-
margin: 0 auto;
|
|
215
|
-
}
|
|
216
|
-
/* Always in the accessibility tree (no display: none) so the role="alert" text
|
|
217
|
-
set by fail() is announced. Empty and transparent until then. */
|
|
218
|
-
.error-message {
|
|
219
|
-
position: absolute;
|
|
220
|
-
inset: 0;
|
|
221
|
-
display: flex;
|
|
222
|
-
align-items: center;
|
|
223
|
-
justify-content: center;
|
|
224
|
-
padding: 16px;
|
|
225
|
-
text-align: center;
|
|
226
|
-
color: #fff;
|
|
227
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
228
|
-
font-size: 16px;
|
|
229
|
-
z-index: 2;
|
|
230
|
-
pointer-events: none;
|
|
231
|
-
}
|
|
232
|
-
.video-container.has-error .error-message {
|
|
233
|
-
background: rgba(0, 0, 0, 0.6);
|
|
234
|
-
}
|
|
235
|
-
.video-container.has-error #control-bar {
|
|
236
|
-
display: none;
|
|
237
|
-
}
|
|
238
|
-
.video-container svg {
|
|
239
|
-
fill: #fff;
|
|
240
|
-
}
|
|
241
|
-
.video-container img {
|
|
242
|
-
filter: invert(1) brightness(100);
|
|
243
|
-
}
|
|
244
|
-
.video-container.light-theme {
|
|
245
|
-
--player-bg: #fff;
|
|
246
|
-
background: var(--player-bg);
|
|
247
|
-
}
|
|
248
|
-
.video-container.light-theme svg {
|
|
249
|
-
fill: #000;
|
|
250
|
-
}
|
|
251
|
-
.video-container.light-theme img {
|
|
252
|
-
filter: none;
|
|
253
|
-
}
|
|
254
|
-
.video-container.light-theme #control-bar {
|
|
255
|
-
background: linear-gradient(transparent, rgba(255, 255, 255, 0.7));
|
|
256
|
-
}
|
|
257
|
-
.video-container:not(.light-theme) #control-bar {
|
|
258
|
-
background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
|
|
259
|
-
}
|
|
260
|
-
video {
|
|
261
|
-
width: 100%;
|
|
262
|
-
height: 100%;
|
|
263
|
-
object-fit: contain;
|
|
264
|
-
}
|
|
265
|
-
#control-bar {
|
|
266
|
-
position: absolute;
|
|
267
|
-
bottom: 0;
|
|
268
|
-
left: 0;
|
|
269
|
-
right: 0;
|
|
270
|
-
display: flex;
|
|
271
|
-
flex-direction: column;
|
|
272
|
-
padding: 10px;
|
|
273
|
-
background: linear-gradient(transparent, var(--control-bg));
|
|
274
|
-
gap: 10px;
|
|
275
|
-
z-index: 1;
|
|
276
|
-
transition: opacity 0.3s ease, transform 0.3s ease;
|
|
277
|
-
}
|
|
278
|
-
/* opacity + pointer-events (not visibility: hidden) so the buttons stay
|
|
279
|
-
keyboard-focusable and :focus-visible can reveal the bar. */
|
|
280
|
-
:host([auto-hide-controls]) #control-bar {
|
|
281
|
-
opacity: 0;
|
|
282
|
-
pointer-events: none;
|
|
283
|
-
transform: translateY(8px);
|
|
284
|
-
}
|
|
285
|
-
/* .controls-visible is toggled by setupAutoHide() for mouse movement and taps. */
|
|
286
|
-
:host([auto-hide-controls]) .video-container.controls-visible #control-bar {
|
|
287
|
-
opacity: 1;
|
|
288
|
-
pointer-events: auto;
|
|
289
|
-
transform: none;
|
|
290
|
-
}
|
|
291
|
-
/* Kept in its own rule: browsers without :has() drop the whole selector list,
|
|
292
|
-
which would also disable the rule above.
|
|
293
|
-
:focus-visible (not :focus-within) so a mouse click on a button doesn't pin the bar open. */
|
|
294
|
-
:host([auto-hide-controls]) .video-container:has(:focus-visible) #control-bar {
|
|
295
|
-
opacity: 1;
|
|
296
|
-
pointer-events: auto;
|
|
297
|
-
transform: none;
|
|
298
|
-
}
|
|
299
|
-
@media (prefers-reduced-motion: reduce) {
|
|
300
|
-
#control-bar {
|
|
301
|
-
transform: none !important;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
#progress-row {
|
|
305
|
-
display: flex;
|
|
306
|
-
align-items: center;
|
|
307
|
-
gap: 10px;
|
|
308
|
-
width: 100%;
|
|
309
|
-
color: var(--control-color);
|
|
310
|
-
font-size: 14px;
|
|
311
|
-
}
|
|
312
|
-
#controls-row {
|
|
313
|
-
display: flex;
|
|
314
|
-
justify-content: space-between;
|
|
315
|
-
align-items: center;
|
|
316
|
-
width: 100%;
|
|
317
|
-
}
|
|
318
|
-
.button {
|
|
319
|
-
background: transparent;
|
|
320
|
-
border: none;
|
|
321
|
-
cursor: pointer;
|
|
322
|
-
padding: 5px;
|
|
323
|
-
display: flex;
|
|
324
|
-
align-items: center;
|
|
325
|
-
}
|
|
326
|
-
.button svg {
|
|
327
|
-
width: 24px;
|
|
328
|
-
height: 24px;
|
|
329
|
-
display: block;
|
|
330
|
-
}
|
|
331
|
-
.button:hover {
|
|
332
|
-
opacity: 0.8;
|
|
333
|
-
}
|
|
334
|
-
.time-display {
|
|
335
|
-
color: #fff;
|
|
336
|
-
font-size: 14px;
|
|
337
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
338
|
-
opacity: 0.9;
|
|
339
|
-
}
|
|
340
|
-
.light-theme .time-display {
|
|
341
|
-
color: #000;
|
|
342
|
-
}
|
|
343
|
-
${Ym[this.progressBarStyle]}
|
|
344
|
-
.video-controls {
|
|
345
|
-
display: flex;
|
|
346
|
-
align-items: center;
|
|
347
|
-
gap: 8px;
|
|
348
|
-
}
|
|
349
|
-
.speed-control {
|
|
350
|
-
justify-content: center;
|
|
351
|
-
min-width: 34px;
|
|
352
|
-
min-height: 34px;
|
|
353
|
-
border-radius: 4px;
|
|
354
|
-
color: #fff;
|
|
355
|
-
font-size: 14px;
|
|
356
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
357
|
-
}
|
|
358
|
-
.light-theme .speed-control {
|
|
359
|
-
color: #000;
|
|
360
|
-
}
|
|
361
|
-
.speed-control img,
|
|
362
|
-
.speed-control svg {
|
|
363
|
-
width: 24px;
|
|
364
|
-
height: 24px;
|
|
365
|
-
display: block;
|
|
366
|
-
transition: opacity 0.2s;
|
|
367
|
-
}
|
|
368
|
-
.speed-control:hover img,
|
|
369
|
-
.speed-control:hover svg {
|
|
370
|
-
opacity: 0.7;
|
|
371
|
-
}
|
|
372
|
-
`,t=`
|
|
373
|
-
<div class="video-container">
|
|
374
|
-
<video id="player"
|
|
375
|
-
muted
|
|
376
|
-
loop
|
|
377
|
-
playsinline
|
|
378
|
-
style="width: 100%; height: 100%;">
|
|
379
|
-
</video>
|
|
144
|
+
</svg>`,exitFullscreen:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
145
|
+
<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>
|
|
146
|
+
</svg>`,volume:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
147
|
+
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
|
|
148
|
+
</svg>`,volumeMuted:`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24" fill="black">
|
|
149
|
+
<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/>
|
|
150
|
+
</svg>`,"speed-0.50":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUADXo0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7KrC+8P9nTvYJgEtZyvka/xNzvdBc6qomVfhKJdHftjR9FLP56ErolkesRo9EuoXELCZwddAvVc1pZL+Ncl7MdZ99tK4nzSLEbjsta/n33P7+qIXjfMI8yHkGwoRS4HZD6WpKJBKEkQDpSKti7LJn55goC8itM9Ydo0pqv6ctADlXuLXtvTMy3la4g8BTnf65f2RPaaygr9l5k1rhY/2l1OqbQ9RX8Ff/QYa81YRdWMUOdrUbelrBbGAYfOqSNBL2+OxyDhKxfkwK5u2Ap9a9uO3KgQA9cgpU6VBh2rbtTgovKR2NFgbizLGOJcuMnJD5kGuxTpEoDcFnYVvvtCa9qytbRmC8zcCUOZIEb45O2c3v1gjHkUiLa4xwp+Mc9gw41JbpYYBiI0rqDaCvAtP6fJVUDQZpTnESkI7H5K7EZ/bgJZoAUDDfV5Bsn7JYAQYWqDMzgTSqBGYpRpc2YnQiADgCpcZ1HeQYDMuMNJVpEMNsFzanzitIayMcwJdlxmIGGSxcGmSAUsVcP+cQ3soWpiambZ3MKK1SxZs+WcPc9Lsbq4JjfP7h5evIaEhkUOj4gStXARXJpWcvESpZRaMWeFcsXXFQNq3XmXXXdLe959j73stWH7NG3WcvMWrbTauUvH/dFz9x699HrQga106GFHPvyIoxx1YKsNSUOHjTx8xCij3qldWL/lN6jRRY0XqTnQ79Rgdb9J0LxObDIDME5KIO4TATY0T2ZbkCpPcpPZVhinwhhO2mTWaRIDQT2IbdCNXeKT6CT3v7gl1wdu/F/JpYnuTXLfub2i1ufPUFvEzlM4g7oJTh/6j6gcdf7YfavT3zrerT9CH6GP0EfoI/QR+gj9Q0IDfzzM/wJ/AwtlqMgGWC/6AAAAYXpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHjaPYk7DoAwDEP3nIIj5GPUch2Sha0D9xemUuunWLGePONNOWbgEh2OC6UgO1aW6tH49vBQ3sm2n2mS5uYCMZomXmuqygcwfhTVhYB0sAAAAYVpQ0NQSUNDIHByb2ZpbGUAAHicfZE9SMNQFIVPW7VWKw52EHHIUJ0siIo4ahWKUCHUCq06mLz0D5o0JCkujoJrwcGfxaqDi7OuDq6CIPgD4i44KbpIifclhRYxXni8j/PuObx3H+Cvl5lqdowDqmYZqURcyGRXheArfOhFCF0ISczU50QxCc/6uqduqrsYz/Lu+7P6lJzJAJ9APMt0wyLeIJ7etHTO+8QRVpQU4nPiMYMuSPzIddnlN84Fh/08M2KkU/PEEWKh0MZyG7OioRJPEUcVVaN8f8ZlhfMWZ7VcZc178heGc9rKMtdpDSOBRSxBhAAZVZRQhoUY7RopJlJ0HvfwDzl+kVwyuUpg5FhABSokxw/+B79na+YnJ9ykcBzofLHtjxEguAs0arb9fWzbjRMg8AxcaS1/pQ7MfJJea2nRI6B/G7i4bmnyHnC5Aww+6ZIhOVKAlj+fB97P6JuywMAt0LPmzq15jtMHIE2zSt4AB4fAaIGy1z3e3d0+t397mvP7AdDBcmazf/6+AAAPw2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImdpbXA6ZG9jaWQ6Z2ltcDpmNzU5ZmE3Zi1mYWYzLTRiYjUtOTU2OC01ZWZmOTQ5MzhmOWEiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MmE1YTUxZWQtMjFkNi00MzY2LWJmY2ItZDcyNzJjNzdhN2U3IgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6MGI4NjEwY2EtMDU3Ni00MTJlLTg2NzEtYjRjZWU1YzJkZGFiIgogICBkYzpGb3JtYXQ9ImltYWdlL3BuZyIKICAgR0lNUDpBUEk9IjIuMCIKICAgR0lNUDpQbGF0Zm9ybT0iTGludXgiCiAgIEdJTVA6VGltZVN0YW1wPSIxNzM2NTg2NjY3OTU1MTQ1IgogICBHSU1QOlZlcnNpb249IjIuMTAuMzAiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdG9yVG9vbD0iR0lNUCAyLjEwIj4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6ZTZkNDA1MzYtMmM4Mi00YmMyLTgwYzctYWM2ZjU0ZGM3YjIxIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNToxMTozNiswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDphN2IwZGUxZi1iYmFhLTQ1ZWQtOGU3Mi1mNzIxZDViMGUzZmIiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjMyOjIwKzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjZiNTdlZmMzLTdmNjMtNGE0MS1hZWYzLTc4MGQ0NzU1YmRjZiIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTEtMDNUMTI6MjE6NTUrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MzJhOTk4N2MtMWE5ZS00MjNiLWJiZGUtMWQxMmE2Njg4MDQ1IgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyNS0wMS0xMVQxNDo0MTowNyswNTozMCIvPgogICAgPC9yZGY6U2VxPgogICA8L3htcE1NOkhpc3Rvcnk+CiAgPC9yZGY6RGVzY3JpcHRpb24+CiA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz64X1WPAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6QELCQsHZb85vAAABP5JREFUeNrtm2toXEUUgL+ka0xM0lQ2YlCs1aYlaCHxnVqxUir4qLZaS7UI9odVqq2g+IT8kZaqoIjxjfgCkdbaH6Xon7RUrdhCqZWUCkbUGmwVnzE20aZu1h/3LDm5vfu4m4m79+75YODu7MyZe8+eO+fMmVkwDMMwDMMwDMMwDMMwjMhQFeF7rwYagKlS5gGnA33AEeBzYNh+4vE0ArcDHwAjQDpHOQ7sB14GVgJtETeYojkZWAJsEotKT6D8ANwFJCrlFV4CvAU0+er/ArYCXwODQBLoku+6gO+AS4BO4AL5ETRfSbstotjY8r6ynmFgM3ALUOdr16naLQ+w4E7gYZkbtUXuBRbGWYGzgGeAOwKsUHOhUspNOdqdAjwK/O5T5Bb5rmKpFiV8JJ45H6cCTwBDSom7gWbz0+E4A/hUKfFPYH5UnUhSPG19lu+/kRDGNXXAZ0CHfB4GzgO+j5o1LCwgDJmao/9c4DZgSshxVwGjvnH2ADVRU2AS2C5zUVB5J0+AfVQe/oYQY14DpJSX71FK7K6kuWymevA1IfqtU8q7WqaPA0rWskpR4Cz10PeE6NcMPA5cpuraJDhPAz9WSngzWylwtQN5q5W8+ytBgW3qge92IK9GvHBeK6wu8YNPA1oKKI0hwjEXa9sRYINctziyaudMB/4uMIsyELD+1Zyv2t7p6P5qgEMi80A5WmAzUFtg26Y8VujaAjNWuFGu58gPfgKJEirwCwlipxXQ9gjwc561cIZRh/f4IfCIXF8HvBJXJ9KuXuFVDuUmgD9E7ra4Km+FeMqMAkeBp0JMD/nYLHJ/i6Pyns7hePZxYia6GDYomXVxUt4ilQQYAl4EXgMOqwde52CcNUrezFzea7KpAm6VpEEYBoB3A5xDj2RwUnj7HplQoxZv8ygpa9yGIjzzWcD1Mge2q9DoSmBXOaxXw5YOn6yTVAy5MWCsbtX3zCLutS/LfXSVMg4cBI4V0e+4WKG/bkSuWwP6ZKw8JYoOy5dZ6g+X8hUG7+RAY8g+Q+Jl/ewCrpDrxRJmpGVu3CrGsQcv0VoMM+QVXgQ8K3WX4u3kxYK5jCVDM5vm+tX7l5D7G1lYq2TOiFsY85C8zv656hhwr6Mx1iu5DcSQi/BS/pmH3BngdCbCTpHbT4y5SilwsUO5DWLNaeD1cksm1ANvk/vEgU4mrMwRz2WC5yrHS675jO3O9ZSb1XSGjAXzxXNLHScSAF6SsVNkObVQyo31JrxzfoVa4LW4TVXl4zS8U171eBvv8zBC8aSy/htNHeFIMra1uZ8KPdk6EV5Q1nezqSM77eJd71N1yxifU4yU9dVK7BVUJuOwj57n1ktiYkA+/0pA/q+caSX3Nmc/7rNHs4Ff1Bg/MXbCf0GUVxNBJTVJa9F2Cb71WGsL7ZwoIwXuBh4j+wHLQ3hH2Fwzwvg85T7g+Up0CHUUtsesWeGzvt4CA/vYUS/z11GynCDw0QbsYHz660FKf1bIOUuBg8AbwOUFrquX52g3B3hOZVjSeEnYi+NqWe/5JvdemeBbfdaSTYFVwNl4W5N7AxzTm8Q0SapDm20EZ50H8fZFuoFXVf0mvD3ijxk7lqHLP9JmARVEi8xRvRS/NXoQeADHf6aJ4iK5Q+bGc8VhTMfLFU5RYUm/hD3f4qWkPsFLSTknLlmGBHCOKLGP/zdvaBiGYRiGYRiGYRiGYRhR4T+g4LtceW1yGQAAAABJRU5ErkJggg==" width="24" height="24" alt="0.5x speed">',"speed-1.00":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUADXo0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7KrC+8P9nTvYJgEtZyvka/xNzvdBc6qomVfhKJdHftjR9FLP56ErolkesRo9EuoXELCZwddAvVc1pZL+Ncl7MdZ99tK4nzSLEbjsta/n33P7+qIXjfMI8yHkGwoRS4HZD6WpKJBKEkQDpSKtqJr2vnyBAF5Fad7wrRpTFf15aAHKvcWvbanZ1rK1xB5CnK+1y/tiew1lRX6LzNrXC1+tLucUml7iv4K/ugx1pqxiqoZoc7Xom5LWS2MAw6dU0eCXt4cj0HCVy7IgV3dsBX61rYduVEhBq5BSp0qDTpW3ajBReUjsaPB3FiWMcS5cJOTHzINdinSJUCyLexgeveF1rRla2nNFpi5E4YyQYzwyds5vfvBGPMoEG1xjxX8Yp7BhhuT3CwxDERoXEG1FeBbfk6Tq4CgzSjPI1IQ2P2U2I3+3ASyQAsGGurzDJL3SwAhwtQGZ3AmlECNxCjT5sxOhEAGAFW4zqK8gwCZcYeTrCIZbILn1PjEaQ1lY5gT7LjMQMIki4NNkQpYqob94xrYQ9XE1MyyuYUVq1myZss5e56XYnVxTW6e3T28eA0JDYscHhElauEiuDSt5OIlSim1Ys4K5YqvKwbUuvMuu+6W9rz7HnvZa8P2adqs5eYtWmm1c5eO+6Pn7j166fWgA1vp0MOOfPgRRznqwFYbkoYOG3n4iFFGvVO7sH7Lb1CjixovUnOg36nB6n6ToHmd2GQGYJyUQNwnAmxonsy2IFWe5CazrTBOhTGctMms0yQGgnoQ26Abu8Qn0Unuf3FLrg/c+L+SSxPdm+S+c3tFrc+fobaInadwBnUTnD70H1E56vyx+1anv3W8W3+EPkIfoY/QR+gj9BH6h4QG/niY/wX+BtKUqMT2Ahu4AAAAYHpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHja48osKEnmUgADEyMuYwsTIxNLkxQDEyCEA8MUw2QDI2NzINPC2MjYAIhNgaQhCIJlkoEySUCeCRCC5bmMUmBcAwMuADBKFNK6HFPnAAABhWlDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw1AUhU9btVYrDnYQcchQnSyIijhqFYpQIdQKrTqYvPQPmjQkKS6OgmvBwZ/FqoOLs64OroIg+APiLjgpukiJ9yWFFjFeeLyP8+45vHcf4K+XmWp2jAOqZhmpRFzIZFeF4Ct86EUIXQhJzNTnRDEJz/q6p26quxjP8u77s/qUnMkAn0A8y3TDIt4gnt60dM77xBFWlBTic+Ixgy5I/Mh12eU3zgWH/TwzYqRT88QRYqHQxnIbs6KhEk8RRxVVo3x/xmWF8xZntVxlzXvyF4Zz2soy12kNI4FFLEGEABlVlFCGhRjtGikmUnQe9/APOX6RXDK5SmDkWEAFKiTHD/4Hv2dr5icn3KRwHOh8se2PESC4CzRqtv19bNuNEyDwDFxpLX+lDsx8kl5radEjoH8buLhuafIecLkDDD7pkiE5UoCWP58H3s/om7LAwC3Qs+bOrXmO0wcgTbNK3gAHh8BogbLXPd7d3T63f3ua8/sB0MFyZrN//r4AAA/DaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA0LjQuMC1FeGl2MiI+CiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiCiAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICB4bWxuczpHSU1QPSJodHRwOi8vd3d3LmdpbXAub3JnL3htcC8iCiAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyIKICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIKICAgeG1wTU06RG9jdW1lbnRJRD0iZ2ltcDpkb2NpZDpnaW1wOmIwMWJkMTBiLTY4ZTUtNDI3Yy05MjZjLWYxMmI1NGE5MDIxZSIKICAgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyYWRhMTI4OS0yMDdiLTQwYTMtYjdjNS02OTc4NGQ1Yjc3NTIiCiAgIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NDQ3MTYxMC0zYWY0LTQ0MDAtYTZiMC02NGJjZDgyNDIzMzEiCiAgIGRjOkZvcm1hdD0iaW1hZ2UvcG5nIgogICBHSU1QOkFQST0iMi4wIgogICBHSU1QOlBsYXRmb3JtPSJMaW51eCIKICAgR0lNUDpUaW1lU3RhbXA9IjE3MzY1ODY3MjI2MDkwNzgiCiAgIEdJTVA6VmVyc2lvbj0iMi4xMC4zMCIKICAgdGlmZjpPcmllbnRhdGlvbj0iMSIKICAgeG1wOkNyZWF0b3JUb29sPSJHSU1QIDIuMTAiPgogICA8eG1wTU06SGlzdG9yeT4KICAgIDxyZGY6U2VxPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDoxMTg0Y2IxMi1lMTE2LTRlNTEtYTdlYi05ZTBhY2ZhMWNmZDIiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjExOjM4KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmQ5OTdhZmU2LTAwYzQtNDhiYS05MzYxLTRmZmU3MWFlNjIwYSIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTAtMzFUMTU6MzI6MTArMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MzRlYTZjOTAtNjY0OS00ZGUwLTk3NjUtZTNiOGIyMDMxNDgxIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMS0wM1QxMjoyMToxOCswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo4MDAxYTYxNy01ZTQxLTQ2YjQtOTk3MS1mMzNhYjIyNDNmMWUiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDI1LTAxLTExVDE0OjQyOjAyKzA1OjMwIi8+CiAgICA8L3JkZjpTZXE+CiAgIDwveG1wTU06SGlzdG9yeT4KICA8L3JkZjpEZXNjcmlwdGlvbj4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/Pk8m2PUAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQfpAQsJDAJalFv0AAAFB0lEQVR42u2bfYgVVRTAf7u+LdvNNXar1azdLFoQtlIqWJCicjH72IrokyJFLaIIo5aWNiusxUAMURApsCCyyCUL2TBLihIiU4wk0z7dDDOzWrNNe7nP1x/3DHvfNO9j3sxr9s07P7jMvJn7NeedO+fcc++AoiiKoiiKoiiKoiiKopQNVWXe9zqgXtI0YAqwE/gN2Ar8oX9xJicCNwKvAUNAOkc6DuwCXgLuA6YCiUoU2higA1gNDOYRWr40CPQAtZUyhC8C+oEJrutJYAPwOXBItG253HsB2AhcArTLsc5Vfj/wtPwpx+KsfYst7RkWwcwBxrvyNVr5nnDdS8jwvR/Y7dLIb4Dbgeq4CvA0YIk8fFOOfPVASoTyaI58CWA+8KNLkB8Dp1e6gVkGbAPOKSDvSUAX8KslxO+AVrXT/hgP9FlC/FteEWVhRK4GHhcrWwhfAfNkqIZJNbAOuEF+p4DpwJbR/u/3F+GGtJWgH1cBR13tDIhhykuUjuVK4BSfGrgr5D5MAd4ExoortF4c9RbgZaBTritZuFs0LgXMleG8wdLEHhVRfmv8GHCNde1UYK9lVM5SMWXSKcM0Fx2WFq5SkY3Q68MgfSj5kkBz1G5MU4C2UsDBEPqwEHhGzg8C5wJ/5sh/BfC+nD8vEZ1IeDFgBCUNPBWwD11WXb/L3LgQHC08DJwQlQC3hCDAvgDtP2jVc0iiM4UyzyrbEZUfeBdwfYAhPAysLbLsvYyEuYbE2m71Ud5xaaqk7KY4G4ix4oI4zLYiNEPAZUXWu13q2B1Xwd0MfIYJjKYlwvKOJbwjwIwA9dsxyca4CW95nndnUoIWQZhj1XdBnIR3rcxTHSu5BngW+N564O0htDPTqm9WKY1IG3B5yELaL5N9rwn9HZZhug74SM57JJrSDFyIiVYf9tluIya8VQtMtK6XbFpXBewLwV3xStmG4Bdyf4fHvXus8lcW8TxvZ+nLG+6MYS2mODG0sEkCP2W5d0SODR5Obot1PlhEu19mub6vlFO5GlfHw2AQs8vAixXiJAMsBbplqLcAn2IWif4BxsnRL5MkWtMmrxGAO4FX42JEbnENr1/EaBy3ri0OoZ1ZVn0z4yK8yWSuqHmlt2RUBGW2Vee0KKZypaDTcmqXynGqXNspc+f1IbU1XY7HgG/jooFNwOvWO7CU7BHt2xxVMOFWzG6AIPHAJYzE5gAOALf9D31vBc6W83ej0pYdIfiC/RH1/SGrD+1RaeBK4IGA4azVEQivBlgg5z/jLwymkBlMfUTF4Y+EWFzHv6xTkfhjgaV93SqO7JwhBqqXkS0mF2MW1NMSDRo3mh+gFji5wDSmBO3PtTRtjTjijt+XtJzoUUm3a96aLw2IIMOkAbNpyWnDDsnNH+3DZ10R/mApdpBOwuyVtttZ4cfaREWXONl+trd9XYJ+DGP2B2L5fA9XokGowWxK98MMMtdQ9lLB+6S3YQKnlxaQd6IYDfurpmWYL6FiRTvmY5o+TGCzOocxcISxMEd9k4FFmEUmJ/8Bgi99jlp6XS/3PcCTwPmu93euD20mYIKiH3hY/Y389yuoWNEAvAL85WGRj2I2Lq0ic/fAJuA54D2ZhrnLDWNW3W6ivL9W9UW9+GWbffqOaZeBWETIC1/l+A+chwnStmIWz5vFl3MMQArzKdeApB+AT0QjUyieVANnYnYiJFQciqIoiqIoiqIoiqIoiuLJv3j56EqFGeTaAAAAAElFTkSuQmCC" width="24" height="24" alt="1x speed">',"speed-1.50":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC9HpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZddktsqEIXfWUWWoP6jm+UgEFXZQZafA5Kdscd58L1PqTKUAEHr0PQHeCYdv36O9AOJSuSk5pFLzhuSFi1c0YjtTHWVtOkqV7JrCO8P/ek+wOgS1HK+Rr7sb/10FziripZ9EYp2DeyPA0Uv/XgSuiaS6RGj0S+hcgkJnwN0CdRzWVsu4V+XsB9n3W8rifNJsxiNy1r/fo49v6sjet0wjzAfQrKhFLkckPlYkooGoSRBOFAq2oqhCtNyeYKAvIrTPcEujemqvjR6oHJv0ev+9ExL+TKRpyDne/2yP5G9prJC/2VmjavFj/0up1TanqK/gj96jLVmrKJqRqjztajbUlYLdsChc+pI0Mub4zFI+MoFObCrG7ZC39q2IzcqxMA1SKlTpUHHqhs1uKh8JHY0mBvL6gxxLtzk5IdMg12KdAmQbAs7mN59oTVt2VpaswVm7gRTJogRPnk7p3c/GGMeBaIt7rGCX8wz2HBjkpslzECExhVUWwG+5ec0uQoI2ozyPCIFgd1Pid3oz00gC7TA0FCfZ5C8XwIIEaY2OIMzoQRqJEaZNmd2IgQyAKjCdRblHQTIjDucZBXJYBM8p8YnTsuUjdGd0I/LDCRMsjjYFKmApWrYP66BPVRNTM0sm1tYsZola7acs+d5KVYX1+Tm2d3Di9eQ0LDI4RFRohYugkvTSi5eopRSK+asUK74usKg1p132XW3tOfd99jLXhu2T9NmLTdv0Uqrnbt03B89d+/RS68HHdhKhx525MOPOMpRB7bakDR02MjDR4wy6p3ahfVbfoMaXdR4kZqGfqeGXvebBM3rxCYzAOOkBOI+EWBD82S2BanyJDeZbYVxKozhpE1mnSYxENSD2Abd2CU+iU5y/4tbcn3gxv+VXJro3iT3ndsran3+DLVF7DyFM6ib4PRh/IjKUeeP3bc6/W3g3foj9BH6CH2EPkIfoY/QPyQ08MfD/C/wN2CdqM5T/ye5AAAAYXpUWHRSYXcgcHJvZmlsZSB0eXBlIGlwdGMAAHjaPYnBDYAwDAP/mYIRktiIdh3SD78+2F+YSuCTLVu2a95l2xLT0JjsHE7xK0aUJw7VhoTLuzJe1lN6Ti2KBNAtxzfd7QEw5hTcAducfAAAAYVpQ0NQSUNDIHByb2ZpbGUAAHicfZE9SMNQFIVPW7VWKw52EHHIUJ0siIo4ahWKUCHUCq06mLz0D5o0JCkujoJrwcGfxaqDi7OuDq6CIPgD4i44KbpIifclhRYxXni8j/PuObx3H+Cvl5lqdowDqmYZqURcyGRXheArfOhFCF0ISczU50QxCc/6uqduqrsYz/Lu+7P6lJzJAJ9APMt0wyLeIJ7etHTO+8QRVpQU4nPiMYMuSPzIddnlN84Fh/08M2KkU/PEEWKh0MZyG7OioRJPEUcVVaN8f8ZlhfMWZ7VcZc178heGc9rKMtdpDSOBRSxBhAAZVZRQhoUY7RopJlJ0HvfwDzl+kVwyuUpg5FhABSokxw/+B79na+YnJ9ykcBzofLHtjxEguAs0arb9fWzbjRMg8AxcaS1/pQ7MfJJea2nRI6B/G7i4bmnyHnC5Aww+6ZIhOVKAlj+fB97P6JuywMAt0LPmzq15jtMHIE2zSt4AB4fAaIGy1z3e3d0+t397mvP7AdDBcmazf/6+AAAPw2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNC40LjAtRXhpdjIiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iCiAgICB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIgogICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgeG1sbnM6R0lNUD0iaHR0cDovL3d3dy5naW1wLm9yZy94bXAvIgogICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iCiAgIHhtcE1NOkRvY3VtZW50SUQ9ImdpbXA6ZG9jaWQ6Z2ltcDplNDBjOGRjOC1kY2QwLTRkMTctYmJiYy03YWNlOWM1NTQ0OGIiCiAgIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6YmJhNjM3NmYtZGU4Yy00NmM3LTljZjMtZjQ3Nzc4MWJlZjJkIgogICB4bXBNTTpPcmlnaW5hbERvY3VtZW50SUQ9InhtcC5kaWQ6ODI2OWFlMzQtYThmMy00OTg2LTgyOGMtYzgwZDJkYzg5MGM2IgogICBkYzpGb3JtYXQ9ImltYWdlL3BuZyIKICAgR0lNUDpBUEk9IjIuMCIKICAgR0lNUDpQbGF0Zm9ybT0iTGludXgiCiAgIEdJTVA6VGltZVN0YW1wPSIxNzM2NTg2NzU5MzM3NjcwIgogICBHSU1QOlZlcnNpb249IjIuMTAuMzAiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiCiAgIHhtcDpDcmVhdG9yVG9vbD0iR0lNUCAyLjEwIj4KICAgPHhtcE1NOkhpc3Rvcnk+CiAgICA8cmRmOlNlcT4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6NzBiNTI5NjQtNTc0NC00NmNiLWE5NDYtYjYwMmNjMWVkOWRmIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNToxMTo0MSswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo0YmZmMjFlNy03ODE5LTQyYzgtODAwYi1lYjFlNmY2MDRiZDQiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTEwLTMxVDE1OjMxOjU5KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmQ3YWQ3ZmQ3LWY0YTItNDM2MC05ZDE1LTgwM2E0NzliZDFhMCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTEtMDNUMTI6MjA6NDQrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6YjUwZjgyM2QtYjEzNy00ODUxLTk3NGEtOGQxMDE4YmIwOThkIgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyNS0wMS0xMVQxNDo0MjozOSswNTozMCIvPgogICAgPC9yZGY6U2VxPgogICA8L3htcE1NOkhpc3Rvcnk+CiAgPC9yZGY6RGVzY3JpcHRpb24+CiA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz53lMvMAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH6QELCQwnEZCPswAABNZJREFUeNrtm2uIVVUUgD9nUhvL0Ap7EDOOlmMxPc0cGBKNkH74qLCcHxFR2EPwTxYkQQQWJo5GRIX1J9FIf/ig1IEaqIgY1LG0iIjKsdBQnCy1cnzMmX7sdbj7ns45d87cfe69c+76YMO9++579j7rrL3X2muvA4qiKIqiKIqiKIqiKIoybBgxjMdeA1xmlTlSfxg4BBwAzuojzudK4GngM6AfGIgpfUAX8DrQBkyqVqGNBR4BdgLnCgitUPkBWOhy5lX6FF4CtAN1gfpeYDvwK/AXcBPwjPz2BOABM4AWoBm4KPD/bmA50Jl17eu2tOcUsB64L0QgbVa7lsBvlwCzgBUibFsjO4HpWRbgXcAamXZ1Me0esIRye0y78cBK4B+rvQe8FfJQqopLgc+BLWKdC3Et8E5gTf0IGKN2OhlNYlh8IR4DplayERkn0yWpS+EB7wHvpzCmK4D9wHXy/ZgI9mQlPvGFRbggv6U0phUhfW0drHJVuwYuBt6VzyeAg8Cd8n0ZsFZXuXg2iMb1ArcCVwO/S905oFVFFE+jTGHbcMwEzosQ9w/zeEHZWGWthw+qOIZmmU+JAA/E+Za1KQYALhcHt9jSJ0aklJyRe7gbuAr4TvzFkvCw3PSAo3JQ9rPl0MLTMoYdUY1qUuj4ZmC0w+s1yM2Umj8wITSA2VF78TQ20K8BPTKFXbA3RSe6ELuARbJHngV0ZHXRvxgT95vi+LoTyEW+38yq4FZZfpu/5XvUYR975bpfZ014o4F9McbH1TbsAytSkylesYR1BHgVWE0uWOoBcx30s1qu1w+MdGVEJgD3A6NStoLbxCXyGQMskKDE81a7yVa7DcA34mG0AxPlc02IB+LXdWMCsj5TgXvk90lW+2tcGbROh35eXFke6PftkDabQsbXlbAfz9oP1/H/sxO/zHPlB/5Ygil6AfglUHc8pF1dhBOchCPWGndWnPcwjgYriok01Kc8hU9GCKxRDMhm4BbRnvmW0zsX+Niamg9Z//UitoVH5YHZitUo8nkKeM5auo5nxYjMlJv2p9cXwPfW9wuYs+FiWWMZkVoyxhKZcsG16jzwrKM+NpILumaSO8TyHsZkKnQA0xxev0cE+CVKYm6wtPqlUgUTmjBh8vGOrrcHeLFMApxjff60VJ2uTcEfbCqTAHdK/39GGZA0NHAj5mjQpQb+VAbhNWMSmZB1tV9XtGRssnYpt6k4knEjuTjgdhVHMkbITsbXvmkqkmhmS2CkzapbZhmvbZU46FqSH22mlbf3oaVpizGpHH7O4M+U5zArlskS+UjqxnjAuhTG0wr8a/Vxglw6cXMlat+8InzBtFyZe8k/x/YwweJBUeq84A7gcYaW3rYlpTGdkWnrn2VvrVbLO474RPSwtXipNYUHMGH9kdUovHrgb0xgdDBpIC2YY0r7FYrHsiiYpZjEnjcwKSNRLLKEMaOA4NaT/5rYHuD6rGrW7oAh+UrW0InkH0dEvWhTgwlJvUB+Nr4fYV6Z9Sk7HfNioRdilXsxIaZ2zPmIX79OSpdM6+D/TmPyratqh9EIvIw5pRuqG7QbeBKT9+d03zfc9qmtmFO4BjEe9ZgDb/9e+jDvCx/CHE/2AJ8A3+rONZpRYmQa0KRwRVEURVEURVEURVEURYniPzhn3IN1irUKAAAAAElFTkSuQmCC" width="24" height="24" alt="1.5x speed">',"speed-2.00":'<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAC83pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZdNkuQoDIX3nGKOYP0hcRwMJqJvMMefB3Z6qrKyFzmz6oiEMGCBn0AfkFXp+PvXSH8hUYmc1DxyyXlD0qKFKxqxnamukjZd5Up2deH9mz3dHQyToJbzNfI1/mGnW+CsKlr2RSja1bF/7yh66ceT0OVI5owYjX4JlUtI+OygS6Cey9pyCf+6hP046/5YSZxPmsVoXNb697Pv+V0d0esGP8J8CMmGUuSagMzHklQ0CCUJwoFS0VbY6jWUzoC8itOd4DaNOVV9OegblbtFr+3pmZbyNUSegpzv+qU9kb2mskL/xbPG1eLvdpdTKm1P0V/BHz3GWjNWUTUj1Pla1B21BWV04NDpOhL08uZ4DBK+ckEO7OqGrdC3tu3IjQoxcA1S6lRp0LHqRg1TVD4SOxrMjWUZQ5wLNzn5IdNglyJdApDbwq7C91xouS1bS8tbwHMnDGWCGOGTt3N694Mx5lEg2uKOFebFPIONaUxys8QwEKFxBdVWgB/5OU2uAoI2ozyPSEFg91NiN/r3JpAFWjDQUJ9nkLxfAggRXBsmgzOhBGokRpk2Z3YiBDIAqGLqLMo7CJAZd0ySVSSDTfB0jU+c1lA2hjnBjssMJEyyONgUqYClatg/roE9VE1MzSybW1ixmiVrtpyz53kpVhfX5ObZ3cOL15DQsMjhEVGiFi6CS9NKLl6ilFIrfFYoV3xdMaDWnXfZdbe059332MteG7ZP02YtN2/RSqudu3TcHz1379FLrwcd2EqHHnbkw484ylEHttqQNHTYyMNHjDLqTe3C+iO/QY0uarxIzYF+U4PV/SFB8zqxyQzAOCmBuE8E2NA8mW1BqjzJTWZbYZwKY0zSJrNOkxgI6kFsgx7sEp9EJ7n/xS25fuPG/5VcmujeJPeT2ytqff4MtUXsPIUzqJvg9KH/iMpR54/djzr9ruPd+iP0EfoIfYQ+Qh+hj9AfJDTwx8P8L/AfxFyow7c2uoEAAABgelRYdFJhdyBwcm9maWxlIHR5cGUgaXB0YwAAeNo9icENgFAMQu+dwhFoqfG7ju3Fmwf3j/gT5QUCwc7rLlumMowjI/dspPjl7YXgpjoYhLwq/WU+pefQSgGSsOhvAvYAMDEUz5cVn3MAAAGFaUNDUElDQyBwcm9maWxlAAB4nH2RPUjDUBSFT1u1VisOdhBxyFCdLIiKOGoVilAh1AqtOpi89A+aNCQpLo6Ca8HBn8Wqg4uzrg6ugiD4A+IuOCm6SIn3JYUWMV54vI/z7jm8dx/gr5eZanaMA6pmGalEXMhkV4XgK3zoRQhdCEnM1OdEMQnP+rqnbqq7GM/y7vuz+pScyQCfQDzLdMMi3iCe3rR0zvvEEVaUFOJz4jGDLkj8yHXZ5TfOBYf9PDNipFPzxBFiodDGchuzoqESTxFHFVWjfH/GZYXzFme1XGXNe/IXhnPayjLXaQ0jgUUsQYQAGVWUUIaFGO0aKSZSdB738A85fpFcMrlKYORYQAUqJMcP/ge/Z2vmJyfcpHAc6Hyx7Y8RILgLNGq2/X1s240TIPAMXGktf6UOzHySXmtp0SOgfxu4uG5p8h5wuQMMPumSITlSgJY/nwfez+ibssDALdCz5s6teY7TByBNs0reAAeHwGiBstc93t3dPrd/e5rz+wHQwXJms3/+vgAAD8NpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDQuNC4wLUV4aXYyIj4KIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIKICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgIHhtbG5zOkdJTVA9Imh0dHA6Ly93d3cuZ2ltcC5vcmcveG1wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIgogICB4bXBNTTpEb2N1bWVudElEPSJnaW1wOmRvY2lkOmdpbXA6NDliOGQ3ODctNzUwMy00OTc3LWIwYTItMGEyZWUwZmRjNjdhIgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmU3MGU2OThlLTZjOWMtNDIzMS04OTExLTE2OTQ1MmUxNWQyMiIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOmIzMWI2YzU3LTY0YTItNGE0Yi04M2U2LTIwYjY0ZmQ1Y2NkYSIKICAgZGM6Rm9ybWF0PSJpbWFnZS9wbmciCiAgIEdJTVA6QVBJPSIyLjAiCiAgIEdJTVA6UGxhdGZvcm09IkxpbnV4IgogICBHSU1QOlRpbWVTdGFtcD0iMTczNjU4NjYzMDc4NzQwNiIKICAgR0lNUDpWZXJzaW9uPSIyLjEwLjMwIgogICB0aWZmOk9yaWVudGF0aW9uPSIxIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCI+CiAgIDx4bXBNTTpIaXN0b3J5PgogICAgPHJkZjpTZXE+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjRjNmY5MTE5LTE2Y2YtNDgyNC1iMWY5LWYxZmNjMDgwNTgzZSIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjMtMTAtMzFUMTU6MTE6NDQrMDU6MzAiLz4KICAgICA8cmRmOmxpCiAgICAgIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiCiAgICAgIHN0RXZ0OmNoYW5nZWQ9Ii8iCiAgICAgIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6M2E5MmI5NTQtMGE1Zi00NDI1LWFkMGEtOTRkOGFhMjBjMTU1IgogICAgICBzdEV2dDpzb2Z0d2FyZUFnZW50PSJHaW1wIDIuMTAgKExpbnV4KSIKICAgICAgc3RFdnQ6d2hlbj0iMjAyMy0xMC0zMVQxNTozMTo0MiswNTozMCIvPgogICAgIDxyZGY6bGkKICAgICAgc3RFdnQ6YWN0aW9uPSJzYXZlZCIKICAgICAgc3RFdnQ6Y2hhbmdlZD0iLyIKICAgICAgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo4OTI1MjY2OS01M2JkLTRlNTktOGE2My1lN2M5ZTgxYzZmNjQiCiAgICAgIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkdpbXAgMi4xMCAoTGludXgpIgogICAgICBzdEV2dDp3aGVuPSIyMDIzLTExLTAzVDEyOjIwOjQ4KzA1OjMwIi8+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjA1YjNjZDZjLWUwZGYtNGYzNy04ZTg5LTVmMDFiOTNiZTM2NCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjUtMDEtMTFUMTQ6NDA6MzArMDU6MzAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIAo8P3hwYWNrZXQgZW5kPSJ3Ij8+T3zvpgAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+kBCwkKHhjPoD0AAATqSURBVHja7ZtbbBVFGMd/p0VLSxGIIIIXEChiDAaMl2ii4C3Cg/ogEJqIxngJeGlCUB7UmII+mHglpmrigzFRDAEUJAIx4ZJoA0IUSqq2WFACjUBBQFKL2J7jw3wnDuvZs+cye5bu+X7JJGfPzs7O/vebmW++mQVFURRFURRFURRFURRF6TckYvAMFwBDgKHAKGAm0A6cBvYA+4CUCngu1wH1wFxgbEDeLuA7STuAncCJcmwt44GXgFaxqEJTH7ASmFQuwlUBX/mIsQt4DVgMzAe+l/87gWnAcyLWwQzX/gN8CFwRdwGv9jz4L8ASHwv6UvJ0ZDh3OTBLBE1a5fUArwMXx1nEp4BG4IaAfKtElJ8C8l0PbPC8mJPAfeXuVdwjfeRjOea/A9jmadZPqnOWvyfyCHDGEnJDrh5KKdyYacAiYISDsn4GXgYOhVDP+4EvgAo5bgKeOR/e8DdFuh3e1BhCHYeJf+i912y1wNzYKvUEaAamAIOAP4Ebgb3a0/kzEOgWi9sox/WWFbYA1X4XV6p+9MrIvRtYKINJK3CJWN9ImVc3q1T5z4A6xAq7gFq1wPzoE8t7AKiR39+6HkQqxNTDfpCuiEQcALRJIOM4cJUI6YTJMhqmSpBagMERifioVY96lwXPKZF4KenoJ0Yk4CAJOKSAT1w24QpgOjA1ZH+yV/y03RH2hxuBe4FjwKXSrfR7qoH10rGnrbNWXA/XoakGqzXcEpdR8hrroQ6LhfbKcVI6/7sc3Wuida9FcXI13iU4fD/P0WicfjlvxUnASuCoJdhOYAGwTsRLyfmhDu7VKeWt8CqbicuAGdnmgCWgRzrvzix5rrWCFCswq3QA70u/tUzOzwQ+K2CQnAGMswYzgDFBF9Z43mqU6ajUxw970n+359xo69wrBbzA2T51+surspf0ZPp8oFXq40e39dsbLhvhky9XDvhc1x3UhJPAndKMo27CnQF5WsQqEsATwGbgiLgzb3ry5csOseL0VHU9UIdZSo0Vy63mdQZYi9l5kP7vrKNZzO9S3vK4CTgaswcmW196EJhQpBtzVspaFsfQUzXwKmb95Q/MDoUm4CNHIt5qlbOAMiIBvOdAxEarjAmuggkXAS9iVvnDpA/YhNl+UaiITZblHMIsqHfkUUazWOF+TGzQCY+X2CecGpElDsfsWEgBH2TqHAtlDXBbCS2wpYgyUsDTIuR8zEajLZhw3L6AaxdaOq2jzEnINC9tiasC8g8DTknePcRjR68TEd8G/pY+PBtLLLHnqHTnUhVwfgxmy1sK+NFn2qsIS2UGUyfHFwLbyWOPTNgMkPlpsSmMPmigNGd7dH7HEq8pavEarI642HRA/DHXvGHd47j1ewvmM4pI+dqxP7g4pIHFuzzwq/iAgU0rbB6WEczF9rY2YHVI9TzlOZ6LWcYsO0blmX8kZjnADok9X66jaYPflCsDlZL/pCXeD5jPKmIXqlqLWUBvkNmBH9m+E0lTAzwkYqWFS4pzXRVHq6rj/4s6H2M+aRiSo4DVwO2YL5O8HsFhzOpbrHlWQkneETmJ+XJppUy72ixXZKn8385/i+J26gBeyGWkjdMcdjomyny6QBeoB/gUs2iWcFWp/kgt8CBwE3CllewdCMeA36zUDnyOCfkrPgwGbsZnP7OiKIqiKIqiKIqiKIqilDn/AkkxNGAuRZ+BAAAAAElFTkSuQmCC" width="24" height="24" alt="2x speed">'};class ri{static hideDelay=3e3;root;options;timer;pointerOverControls=!1;constructor(e,t){this.root=e,this.options=t,e.addEventListener("pointermove",s=>{!(s instanceof PointerEvent)||s.pointerType==="touch"||(this.pointerOverControls=!!s.target?.closest?.("#control-bar"),this.show())}),e.addEventListener("pointerout",s=>{if(!(s instanceof PointerEvent)||s.pointerType==="touch")return;const i=this.container();i&&!i.contains(s.relatedTarget)&&(this.pointerOverControls=!1,this.hide())}),e.addEventListener("pointerdown",s=>{!(s instanceof PointerEvent)||s.pointerType!=="touch"||(this.pointerOverControls=!1,this.show())})}show(){this.options.enabled()&&(this.container()?.classList.add("controls-visible"),this.schedule())}schedule(){this.cancel(),!(this.options.paused()||this.pointerOverControls)&&(this.timer=window.setTimeout(()=>this.hide(),ri.hideDelay))}hide(){this.cancel(),this.container()?.classList.remove("controls-visible")}cancel(){window.clearTimeout(this.timer)}container(){return this.root.querySelector(".video-container")}}function Mr(n){if(!Number.isFinite(n))return"0:00";const e=Math.floor(n/60),t=Math.floor(n%60);return`${e}:${t.toString().padStart(2,"0")}`}function Cl(n,e){const t=document,s=n;return typeof s.requestFullscreen=="function"||typeof s.webkitRequestFullscreen=="function"?t.fullscreenEnabled??t.webkitFullscreenEnabled?"element":"none":typeof e.webkitEnterFullscreen=="function"?"video":"none"}function Or(n){const e=document;return(e.fullscreenElement??e.webkitFullscreenElement)===n}async function yl(n,e,t){const s=document,i=n;t==="video"?e.webkitEnterFullscreen?.():t==="element"&&(Or(n)?await(s.exitFullscreen?s.exitFullscreen():s.webkitExitFullscreen?.()):await(i.requestFullscreen?i.requestFullscreen():i.webkitRequestFullscreen?.()))}const Fr=[.25,.5,.75,1,1.25,1.5,2],El=.0625,vl=16;function Tl(n,e){if(!n)return Fr;const t=n.split(",").map(i=>i.trim()).filter(i=>i!=="").map(Number).filter(i=>Number.isFinite(i)&&i>=El&&i<=vl),s=[...new Set(t)];return s.length===0?(e("No valid entries in playback-speeds, using defaults:",n),Fr):s}function Sl(n,e){const t=parseFloat(e||"1");let s=n.indexOf(t);return s===-1&&(s=n.indexOf(1)),s===-1?0:s}const B=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},xl=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=bl},bl=Number.MAX_SAFE_INTEGER||9007199254740991;let W=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),b=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",n.UNKNOWN="unknown",n})({}),p=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});function Ll(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ni={exports:{}},Nr;function Rl(){return Nr||(Nr=1,(function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)m.path=f.path,d.params||(m.params=f.params,d.query||(m.query=f.query));else{var A=f.path,I=A.substring(0,A.lastIndexOf("/")+1)+d.path;m.path=o.normalizePath(I)}return m.path===null&&(m.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(m)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(ni)),ni.exports}var ai=Rl();class oi{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}let se=(function(n){return n.MANIFEST="manifest",n.LEVEL="level",n.AUDIO_TRACK="audioTrack",n.SUBTITLE_TRACK="subtitleTrack",n.MEDIA_FRAGMENT="media-fragment",n.KEY="key",n.STEERING_MANIFEST="steering-manifest",n.SERVER_CERTIFICATE="server-certificate",n.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",n})({}),H=(function(n){return n.MAIN="main",n.AUDIO="audio",n.SUBTITLE="subtitle",n})({});var de={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Br{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Pl(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[de.AUDIO]:null,[de.VIDEO]:null,[de.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new oi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=ai.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[de.AUDIO]=null,e[de.VIDEO]=null,e[de.AUDIOVIDEO]=null,this.url=null}}function Ie(n){return n.sn!=="initSegment"}function Ht(n,e){return n.sn===e?.sn&&n.level===e.level}function li(n,e){return n.sn===e?.sn&&n.level===e.level&&n.cc===e.cc}class gs extends Br{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(B(e)&&B(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=B(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!B(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ie(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}}class Dl extends Br{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,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||this.fragment.type===H.SUBTITLE&&this.stats.loading.end>0)}}function Ur(n,e){const t=Object.getPrototypeOf(n);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||Ur(t,e)}}function Pl(n,e){const t=Ur(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}function _l(n,e,t){return(e=Ml(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function ue(){return ue=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},ue.apply(null,arguments)}function $r(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function z(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?$r(Object(t),!0).forEach(function(s){_l(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):$r(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function ms(n,e){if(n==null)return{};var t,s,i=kl(n,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);for(s=0;s<r.length;s++)t=r[s],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(n,t)&&(i[t]=n[t])}return i}function kl(n,e){if(n==null)return{};var t={};for(var s in n)if({}.hasOwnProperty.call(n,s)){if(e.indexOf(s)!==-1)continue;t[s]=n[s]}return t}function wl(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Ml(n){var e=wl(n,"string");return typeof e=="symbol"?e:e+""}function ps(n){switch(n.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_TRACK_LOAD_TIMEOUT:case b.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Gr(n){return n.details.startsWith("key")}function Vr(n){return Gr(n)&&!!n.frag&&!n.frag.decryptdata}function Kr(n,e){const t=ps(e);return n.default[`${t?"timeout":"error"}Retry`]}function ci(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Hr(n){return z(z({},n),{errorRetry:null,timeoutRetry:null})}function Yt(n,e,t,s){if(!n)return!1;const i=s?.code,r=e<n.maxNumRetry&&(Ol(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function Ol(n){return Wt(n)||!!n&&(n<400||n>499)}function Wt(n){return n===0&&navigator.onLine===!1}function Yr(n,e){return e>0&&n.loadError>0&&n.loadErrorTime!==0&&self.performance.now()-n.loadErrorTime>e}class wt{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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 Fl{constructor(e,t,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 wt(e),this.fast_=new wt(t),this.defaultTTFB_=i,this.ttfb_=new wt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new wt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new wt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new wt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;const s=Math.min(this.minDelayMs_,t/1e5),i=8*t,r=Math.max(e,s)/1e3,a=i/r;this.fast_.sample(r,a),this.slow_.sample(r,a)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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(){}}class Ue{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 s=`[${e}]:`;this.trace=It,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const It=function(){},Nl={trace:It,debug:It,log:It,warn:It,info:It,error:It};function hi(){return ue({},Nl)}function Bl(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):It}function Wr(n,e,t){return e[n]?e[n].bind(e):Bl(n,t)}const ui=hi();function Ul(n,e,t){const s=hi();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Wr(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch{return hi()}i.forEach(r=>{ui[r]=Wr(r,n)})}else ue(ui,s);return s}const le=ui;function Ct(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function $l(n){return typeof self<"u"&&n===self.ManagedMediaSource}function jr(n,e){const t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Gl(n){return btoa(String.fromCharCode(...n))}function As(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}const Vl="utf-16",di="utf-16be",zr="utf-16le",Is="utf-8";function Kl(n,e={}){let t;As(n)?t=new DataView(n):t=new DataView(n.buffer,n.byteOffset,n.byteLength);let s=0,{encoding:i}=e;if(!i){const c=t.getUint8(0),h=t.getUint8(1);c==239&&h==187&&t.getUint8(2)==191?(i=Is,s=3):c==254&&h==255?(i=di,s=2):c==255&&h==254?(i=zr,s=2):i=Is}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(t);const{byteLength:r}=t,a=i!==di;let o="",l;for(;s<r;){switch(i){case Is:if(l=t.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<r){const c=t.getUint8(s+1);c>=128&&c<=191?(l=(l&31)<<6|c&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=r-1){const c=t.getUint8(s+1),h=t.getUint8(s+2);c>=128&&c<=191&&h>=128&&h<=191?(l=(l&15)<<12|(c&63)<<6|h&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=r-1){const c=t.getUint8(s+1),h=t.getUint8(s+2),u=t.getUint8(s+3);c>=128&&c<=191&&h>=128&&h<=191&&u>=128&&u<=191?(l=(l&7)<<18|(c&63)<<12|(h&63)<<6|u&63,s+=4):s++}else s++;else s++;break;case di:case Vl:case zr:l=t.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function Hl(n){const e=typeof n=="string"?new URL(n):n;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function qr(n,e){if(n<0)return-qr(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const s=Math.floor(n*t);return(s%2===0?s:s+1)/t}else return Math.round(n*t)/t}function Yl(n,e){let t;try{t=new URL(n)}catch{return n}const s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(i.length,r.length);for(let o=0;o<a&&i[o]===r[o];o++)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}function Xr(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const i=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?i:i&3|8).toString(16)})}}}function fi(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Cs(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Wl(n,e){return fi(n,e)&&Cs(n,e+6)+10<=n.length-e}function Zr(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function jt(n,e){const t=e;let s=0;for(;fi(n,e);){s+=10;const i=Cs(n,e+6);s+=i,Zr(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function jl(n){return As(n)?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function gi(n,e=0,t=1/0){return zl(n,e,t,Uint8Array)}function zl(n,e,t,s){const i=ql(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Xl(n)?n.byteOffset:0,o=(a+n.byteLength)/r,l=(a+e)/r,c=Math.floor(Math.max(0,Math.min(l,o)));return new s(i,c,Math.floor(Math.min(c+Math.max(t,0),o))-c)}function ql(n){return As(n)?n:n.buffer}function Xl(n){return n&&As(n.buffer)&&n.byteLength!==void 0&&n.byteOffset!==void 0}function $e(n,e=!1){const t=e?n.indexOf(0):n.length,s=Kl(new DataView(n.buffer,n.byteOffset,t),{encoding:Is});return e?s:s.replace(/\0/g,"")}function Zl(n){const e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=n.data.subarray(1).indexOf(0);if(s===-1)return;const i=$e(gi(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=$e(gi(n.data,3+s,a));let l;return i==="-->"?l=$e(gi(n.data,4+s+a)):l=jl(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=l,e}function Ql(n){if(n.size<2)return;const e=$e(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function Jl(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const{data:s}=n,i=$e(s.subarray(t),!0);t+=i.length+1;const r=$e(s.subarray(t));return{key:n.type,info:i,data:r}}const e=$e(n.data.subarray(1));return{key:n.type,info:"",data:e}}function ec(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=$e(n.data.subarray(t),!0);t+=s.length+1;const i=$e(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=$e(n.data);return{key:n.type,info:"",data:e}}function tc(n){return n.type==="PRIV"?Ql(n):n.type[0]==="W"?ec(n):n.type==="APIC"?Zl(n):Jl(n)}function sc(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=Cs(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}const ys=10,ic=10;function Qr(n){let e=0;const t=[];for(;fi(n,e);){const s=Cs(n,e+6);n[e+5]>>6&1&&(e+=ys),e+=ys;const i=e+s;for(;e+ic<i;){const r=sc(n.subarray(e)),a=tc(r);a&&t.push(a),e+=r.size+ys}Zr(n,e)&&(e+=ys)}return t}function Jr(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function rc(n){if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function mi(n){const e=Qr(n);for(const t of e)if(Jr(t))return rc(t)}function Ee(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function en(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function pi(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function ze(n){return String.fromCharCode.apply(null,n)}const st=Math.pow(2,32)-1,Q={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},tn={video:1,audio:2,id3:3,text:4};function sn(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function K(n,e){const t=n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3];return t<0?4294967296+t:t}function rn(n,e){let t=K(n,e);return t*=Math.pow(2,32),t+=K(n,e+4),t}function Es(n,e){let t="";for(let s=e;s<n.length;s++)if(t+=String.fromCharCode(n[s]),n[s]===0)return t;return null}function Ai(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function ye(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function nn(n,e,t){const s=e.byteOffset-n.byteOffset-8,i=8+t,r=e.byteLength+8-i;r<8||(ye(n,s,i),ye(n,s+i,r),ye(n,s+i+4,Q.free))}function Ii(n,e){return[n.byteOffset-e-8,n.byteOffset-e+n.byteLength]}function an(n,e){e.sort((o,l)=>o[0]-l[0]);const t=e.reduce((o,[l,c])=>o+c-l,0),s=new Uint8Array(n.byteLength-t);let i=0,r=0;for(let o=0;o<e.length;o++){const[l,c]=e[o];s.set(n.subarray(i,l),r),r+=l-i,i=c}return s.set(n.subarray(i),r),{result:s,dropped:t,droppedBefore:o=>e.reduce((l,[c,h])=>h<=o?l+h-c:l,0)}}function nc(n){const e=J(n,["moov"]);if(e.length!==1||J(n,["moof"]).length)return null;const t=n.byteOffset,s=[],i=[];let r=!1;const a=J(e[0],["trak"]);for(let f=0;f<a.length;f++){const g=a[f],m=J(g,["mdia","hdlr"])[0];if((m?ze(m.subarray(8,12)):"")==="vide"){r=!0;continue}const I=J(g,["tkhd"])[0];if(!I)return null;const y=I[0];i.push(K(I,y===0?12:20)),s.push(Ii(g,t))}if(!r||!s.length)return null;const o=J(e[0],["mvex"])[0];let l=0;if(o){const f=J(o,["trex"]);for(let g=0;g<f.length;g++){const m=f[g];i.indexOf(K(m,4))!==-1&&(s.push(Ii(m,t)),l+=m.byteLength+8)}}const{result:c,dropped:h,droppedBefore:u}=an(n,s),d=e[0].byteOffset-t-8;if(ye(c,d,e[0].byteLength+8-h),o&&l){const f=o.byteOffset-t-8;ye(c,f-u(f),o.byteLength+8-l)}return c}function ac(n,e,t,s,i){if(t<1)return null;const r=J(n,["moof"]);if(r.length!==1)return null;const a=r[0],o=n.byteOffset,l=[],c=[],h=J(a,["traf"]);let u=!0;for(let m=0;m<h.length;m++){const A=h[m],I=J(A,["tfhd"])[0];if(!I)return null;K(I,4)===e?(l.push(A),K(I,0)&131072||(u=!1)):c.push(Ii(A,o))}if(!l.length||c.length&&!u)return null;if(s!==void 0){let m=t;for(let I=0;I<l.length;I++){const y=l[I];let C=0;const E=J(y,["trun"]);for(let S=0;S<E.length;S++){const L=E[S],R=Math.min(m,K(L,4));if(R){ye(n,L.byteOffset-o+4,R);const x=K(L,0)&16777215,P=(x&256?4:0)+(x&512?4:0)+(x&1024?4:0)+(x&2048?4:0);nn(n,L,8+(x&1?4:0)+(x&4?4:0)+R*P)}else ye(n,L.byteOffset-o-4,Q.free);m-=R,C+=R}const v=J(y,["senc"])[0];v&&ye(n,v.byteOffset-o+4,C);const T=J(y,["saiz"])[0];if(T){const S=T[1]<<16|T[2]<<8|T[3];let L=4;S&1&&(L+=8);const R=T[L];L+=1,ye(n,T.byteOffset-o+L,C),nn(n,T,L+4+(R===0?C:0))}}const A=J(n,["mdat"]);if(A.length===1){const I=A[0].byteOffset-o-8;ye(n,I,s-I)}}let d=n,f=0,g=()=>0;if(c.length){({result:d,dropped:f,droppedBefore:g}=an(n,c)),ye(d,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){const A=l[m],I=g(A.byteOffset-o),y=J(A,["trun"]);for(let C=0;C<y.length;C++){const E=y[C];K(E,0)&1&&ye(d,E.byteOffset-o-I+8,K(E,8)-f)}if(I){const C=J(A,["saio"]);for(let E=0;E<C.length;E++){const v=C[E],T=v[0]===0?4:8;let S=K(v,0)&1?12:4,L=K(v,S);for(S+=4;L--;S+=T){const R=S+T-4;ye(d,v.byteOffset-o-I+R,K(v,R)-I)}}}}}if(i){const{durationOffset:m,value:A}=i;ye(d,m-g(m),A)}return s!==void 0?d.subarray(0,s-f):d}function oc(n,e){const t=n.byteLength;for(let s=0;s<t;){const i=K(n,s);if(i>8&&K(n,s+4)===Q[e])return!0;s=i>1?s+i:t}return!1}function J(n,e){const t=[];return e.length&&on(n,e,0,0,n.byteLength,t),t}function on(n,e,t,s,i,r){const a=e[t];if(a?.length!==4)return;const o=a.charCodeAt(0),l=a.charCodeAt(1),c=a.charCodeAt(2),h=a.charCodeAt(3),u=e.length-1;for(let d=s;d<i;){const f=d+8<=i,g=d+4<=i?n[d]*16777216+(n[d+1]<<16|n[d+2]<<8|n[d+3]):K(n,d),m=g>1?d+g:i;if(f&&n[d+4]===o&&n[d+5]===l&&n[d+6]===c&&n[d+7]===h){const A=Math.min(m,i);t===u?r.push(n.subarray(d+8,A)):on(n,e,t+1,d+8,A,r)}d=m}}function lc(n){const e=[],t=n[0];let s=8;const i=K(n,s);s+=4;let r=0,a=0;t===0?(r=K(n,s),a=K(n,s+4),s+=8):(r=rn(n,s),a=rn(n,s+8),s+=16),s+=2;let o=n.length+a;const l=sn(n,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=K(n,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return le.warn("SIDX has hierarchical references (not supported)"),null;const g=K(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function ln(n){const e=[],t=J(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=J(r,["tkhd"])[0];if(a){let o=a[0];const l=K(a,o===0?12:20),c=J(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=K(c,o===0?12:20),u=J(r,["mdia","hdlr"])[0];if(u){const d=ze(u.subarray(8,12)),f={soun:de.AUDIO,vide:de.VIDEO}[d],g=J(r,["mdia","minf","stbl","stsd"])[0],m=cc(g);f?(e[l]={timescale:h,type:f,stsd:m},e[f]=z({timescale:h,id:l},m)):e[l]={timescale:h,type:d,stsd:m}}}}}return J(n,["moov","mvex","trex"]).forEach(i=>{const r=K(i,4),a=e[r];a&&(a.default={duration:K(i,12),sampleSize:K(i,16),flags:K(i,20)})}),e}function cc(n){const e=n.subarray(8),t=e.subarray(86),s=ze(e.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const c=J(e,[s])[0].subarray(s==="enca"?28:78);J(c,["sinf"]).forEach(u=>{const d=J(u,["schm"])[0];if(d){const f=ze(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=J(u,["frma"])[0];g&&(i=ze(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const l=J(t,["avcC"])[0];l&&l.length>3&&(i+="."+Ts(l[1])+Ts(l[2])+Ts(l[3]),r=vs(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=J(e,[s])[0],c=J(l.subarray(28),["esds"])[0];if(c&&c.length>7){let h=4;if(c[h++]!==3)break;h=Ci(c,h),h+=2;const u=c[h++];if(u&128&&(h+=2),u&64&&(h+=c[h++]),c[h++]!==4)break;h=Ci(c,h);const d=c[h++];if(d===64)i+="."+Ts(d);else break;if(h+=12,c[h++]!==5)break;h=Ci(c,h);const f=c[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((c[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const l=J(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],h=["","A","B","C"][c>>6],u=c&31,d=K(l,2),f=(c&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);i+="."+h+u,i+="."+hc(d).toString(16).toUpperCase(),i+="."+f+g;let A="";for(let I=m.length;I--;){const y=m[I];(y||A)&&(A="."+y.toString(16).toUpperCase()+A)}i+=A}r=vs(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=vs(i,t)||i;break}case"vp09":{const l=J(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],h=l[5],u=l[6]>>4&15;i+="."+it(c)+"."+it(h)+"."+it(u)}break}case"av01":{const l=J(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,h=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,g=c===2&&d?f?12:10:d?10:8,m=(l[2]&16)>>4,A=(l[2]&8)>>3,I=(l[2]&4)>>2,y=l[2]&3;i+="."+c+"."+it(h)+u+"."+it(g)+"."+m+"."+A+I+y+"."+it(1)+"."+it(1)+"."+it(1)+"."+0,r=vs("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function vs(n,e){const t=J(e,["dvvC"]),s=t.length?t[0]:J(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+it(i)+"."+it(r)}}function hc(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function Ci(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Ts(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function it(n){return(n<10?"0":"")+n}function uc(n,e){if(!n||!e)return;const t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&cn(n,(s,i)=>{const r=s.subarray(8,24);r.some(a=>a!==0)||(le.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ee(r)} -> ${Ee(t)}`),s.set(t,8))})}function dc(n){const e=[];return cn(n,t=>e.push(t.subarray(8,24))),e}function cn(n,e){J(n,["moov","trak"]).forEach(s=>{const i=J(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let a=J(r,["enca"]);const o=a.length>0;o||(a=J(r,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);J(c,["sinf"]).forEach(u=>{const d=hn(u);d&&e(d,o)})})})}function hn(n){const e=J(n,["schm"])[0];if(e){const t=ze(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=J(n,["schi","tenc"])[0];if(s)return s}}}let un;function fc(n){return typeof TextDecoder>"u"?$e(n):(un||(un=new TextDecoder("utf-8"))).decode(n).replace(/\0/g,"")}function gc(n){const e=n.byteLength,t=[];for(let s=0;s<e;){const i=s+8<=e,r=s+4<=e?n[s]*16777216+(n[s+1]<<16|n[s+2]<<8|n[s+3]):K(n,s),a=r>1?s+r:e;if(i&&n[s+4]===109&&n[s+5]===111&&n[s+6]===111&&n[s+7]===102){const o=Math.min(a,e);for(let l=s+8;l<o;){const c=l+8<=o,h=l+4<=o?n[l]*16777216+(n[l+1]<<16|n[l+2]<<8|n[l+3]):K(n,l),u=h>1?l+h:o;if(c&&n[l+4]===116&&n[l+5]===114&&n[l+6]===97&&n[l+7]===102){const d=Math.min(u,o);let f,g;const m=[];for(let A=l+8;A<d;){const I=A+8<=d,y=A+4<=d?n[A]*16777216+(n[A+1]<<16|n[A+2]<<8|n[A+3]):K(n,A),C=y>1?A+y:d;if(I&&n[A+4]===116){const E=Math.min(C,d);n[A+5]===102&&n[A+6]===104&&n[A+7]===100?g||(g=n.subarray(A+8,E)):n[A+5]===102&&n[A+6]===100&&n[A+7]===116?f||(f=n.subarray(A+8,E)):n[A+5]===114&&n[A+6]===117&&n[A+7]===110&&m.push(n.subarray(A+8,E))}A=C}t.push({moofOffset:n.byteOffset+s,tfdt:f,tfhd:g,truns:m})}l=u}}s=a}return t}function mc(n,e,t,s,i=!0){return dn(n,e,s,i)}function pc(n,e,t,s,i=!1){const r=[],a=e.samples,o=dn(a,t,s,i,{isHEVCFlavor:zt(e.codec),samples:r,timeOffset:n,timescale:e.timescale,trackId:e.id});return{samples:r,sampleData:{includeSampleDetails:i,tracks:o}}}function dn(n,e,t,s,i){const r={};let a=!1;const o=gc(n),l=n.byteLength;for(let u=0;u<o.length;u++){const{moofOffset:d,tfdt:f,tfhd:g,truns:m}=o[u],A=K(g,4),I=e[A];if(!I)continue;const y=r[A]||(r[A]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:I.timescale,type:I.type});let C;if(f){const M=f[0];C=K(f,4),M===1&&(C===st?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(C*=st+1,C+=K(f,8))),B(C)&&(!B(y.start)||C<y.start)&&(y.start=C),i&&B(C)&&(i.timeOffset=C/i.timescale)}const E=i?.trackId===A&&I.type===de.VIDEO,v=I.default,T=K(g,0)&16777215;let S=v?.duration||0,L,R=v?.sampleSize||0,x=8;T&1&&(x+=8),T&2&&(x+=4),T&8&&(S=K(g,x),L=g.byteOffset-n.byteOffset+x,x+=4),T&16&&(R=K(g,x));let P=0;const _=(T&1)!==0,F=!_&&(T&131072)!==0;_?(P=K(g,8),P*=Math.pow(2,32),P+=K(g,12)):F&&(P=d);let V=C||0,U=0,k=S;for(let M=0;M<m.length;M++){const w=m[M],N=K(w,4),Y=y.sampleCount;y.sampleCount+=N;const O=w[3]&1;let G=0;const ee=w[3]&4,q=w[2]&1,ie=w[2]&2,Z=w[2]&4,ne=w[2]&8;let te=8;O&&(G=Ai(w,te),te+=4),ee&&(!(w[te+1]&1)&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=Y),te+=4);let oe=P+G;if(!s&&w[1]===0&&w[2]===6&&w[3]===1){var c,h;const ge=V,We=oe,ut=te;let j=-1,re=0,ae=0,Se=(c=i?.timeOffset)!=null?c:0;const Ce=S/((h=i?.timescale)!=null?h:1),we=i?.isHEVCFlavor===!0,et=we?2:1;for(let De=0;De<N;De++){const Me=w[te]===0?w[te+1]<<16|w[te+2]<<8|w[te+3]:K(w,te),je=j===-1&&y.keyFrameIndex===void 0&&(w[te+5]&1)===0;te+=8;const Ke=oe+Me;if(E){if(Me>0){let Pe=oe;do{const xt=n[Pe]===0?n[Pe+1]<<16|n[Pe+2]<<8|n[Pe+3]:K(n,Pe);Pe+=4;const At=n[Pe],tt=we?At>>1&63:At&31;(we?tt===39||tt===40:tt===6)&&qt(n.subarray(Pe,Pe+xt),et,Se,i.samples),Pe+=xt}while(Pe<Ke)}Se+=Ce}oe=Ke,je&&(j=De,re=oe)}if(oe<=l)ae=N;else{let De=We,Me=ut;for(let je=0;je<N;je++){const Ke=w[Me]===0?w[Me+1]<<16|w[Me+2]<<8|w[Me+3]:K(w,Me);if(De+=Ke,De>l)break;ae=je+1,Me+=8}}if(E&&(i.timeOffset=Se),j!==-1&&re<=l&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=j,y.keyFrameStart=ge+j*S),ae){(!B(y.ptsMin)||ge<y.ptsMin)&&(y.ptsMin=ge);const De=ge+ae*S;(!B(y.ptsMax)||De>y.ptsMax)&&(y.ptsMax=De)}const _t=S*N;V=ge+_t,U+=_t;continue}let Te,Be;s&&(Te=[],Be={sampleOffset:oe,samples:Te,defaultSampleDurationOffset:L},oe<=l&&y.trun.push(Be));let pt;for(let ge=0;ge<N;ge++){let We;q?(s&&(We=w.byteOffset-n.byteOffset+te),k=K(w,te),te+=4):k=S,ie?(pt=K(w,te),te+=4):pt=R;let ut,j;Z&&(j=w[te+1]&1?1:0,s&&(ut={isNonSync:j,dependsOn:(w[te]&3)===1?1:2}),te+=4);let re=0;if(ne&&(re=w[0]===0?K(w,te):Ai(w,te),te+=4),E){let ae=oe,Se=0;for(;Se<pt;){const Ce=K(n,ae);ae+=4,fn(i.isHEVCFlavor,n[ae])&&qt(n.subarray(ae,ae+Ce),i.isHEVCFlavor?2:1,i.timeOffset+re/i.timescale,i.samples),ae+=Ce,Se+=Ce+4}i.timeOffset+=k/i.timescale}if(oe+=pt,oe<=l){Be&&We!==void 0&&(Be.lastSampleDurationOffset=We),j===0&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=ge,y.keyFrameStart=V);const ae=V+re;(!B(y.ptsMin)||ae<y.ptsMin)&&(y.ptsMin=ae),(!B(y.ptsMax)||ae+k>y.ptsMax)&&(y.ptsMax=ae+k),Te&&(Te[ge]={cts:re,duration:k,flags:ut,size:pt})}V+=k,U+=k}!U&&S&&(U+=S*N)}y.duration+=U,y.duration&&(a=!0)}if(!a){let u=1/0,d=0;const f=J(n,["sidx"]);for(let g=0;g<f.length;g++){const m=lc(f[g]);if(m!=null&&m.references){u=Math.min(u,m.earliestPresentationTime/m.timescale);const A=m.references.reduce((I,y)=>I+y.info.duration||0,0);d=Math.max(d,A+m.earliestPresentationTime/m.timescale)}}d&&B(d)&&Object.keys(r).forEach(g=>{r[g].duration||(r[g].duration=d*r[g].timescale-r[g].start)})}return r}function Ac(n){const e={valid:null,remainder:null},t=J(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function Ye(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Ic(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return J(s,["moof"]).map(l=>{const c=l.byteOffset-8;J(l,["traf"]).map(u=>{const d=J(u,["tfdt"]).map(f=>{const g=f[0];let m=K(f,4);return g===1&&(m*=Math.pow(2,32),m+=K(f,8)),m/i})[0];return d!==void 0&&(n=d),J(u,["tfhd"]).map(f=>{const g=K(f,4),m=K(f,0)&16777215,A=(m&1)!==0;let I=0;const y=(m&2)!==0,C=(m&8)!==0;let E=0;const v=(m&16)!==0;let T=0;const S=(m&32)!==0,L=!A&&(m&131072)!==0;let R=8;g===r&&(A?(I=K(f,R),R+=4,I*=Math.pow(2,32),I+=K(f,R),R+=4):L&&(I=c),y&&(R+=4),C&&(E=K(f,R),R+=4),v&&(T=K(f,R),R+=4),S&&(R+=4),e.type==="video"&&(a=zt(e.codec)),J(u,["trun"]).map(x=>{const P=x[0],_=K(x,0)&16777215,F=(_&1)!==0;let V=0;const U=(_&4)!==0,k=(_&256)!==0;let M=0;const w=(_&512)!==0;let N=0;const Y=(_&1024)!==0,O=(_&2048)!==0;let G=0;const ee=K(x,4);let q=8;F&&(V=K(x,q),q+=4),U&&(q+=4);let ie=I+V;for(let Z=0;Z<ee;Z++){if(k?(M=K(x,q),q+=4):M=E,w?(N=K(x,q),q+=4):N=T,Y&&(q+=4),O&&(P===0?G=K(x,q):G=Ai(x,q),q+=4),e.type===de.VIDEO){let ne=0;for(;ne<N;){const te=K(s,ie);if(ie+=4,fn(a,s[ie])){const oe=s.subarray(ie,ie+te);qt(oe,a?2:1,n+G/i,t)}ie+=te,ne+=te+4}}n+=M/i}}))})})}),t}function zt(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function fn(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function qt(n,e,t,s){const i=gn(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);const c=i.length-r;let h=r;if(o<c)r+=o;else if(o>c){le.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(i[h++]===181){const d=sn(i,h);if(h+=2,d===49){const f=K(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const m=i[h++],A=31&m,I=64&m,y=I?2+A*3:0,C=new Uint8Array(y);if(I){C[0]=m;for(let E=1;E<y;E++)C[E]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:C})}}}}}else if(a===5&&o>16){const u=[];for(let g=0;g<16;g++){const m=i[h++].toString(16);u.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:fc(f),userDataBytes:f})}}}function gn(n){const e=n.byteLength;let t,s=n.indexOf(3,3);for(;s!==-1;)n[s-1]===0&&n[s-2]===0&&(t||(t=[])).push(s),s=n.indexOf(3,s+1);if(!t)return n;const i=e-t.length,r=new Uint8Array(i);let a=0,o=0;for(let l=0;l<i;o++,l++)o===t[a]&&(o++,a++),r[l]=n[o];return r}function Cc(n){const e=n[0];let t="",s="",i=0,r=0,a,o=0,l=0,c=4;if(e===0){const u=Es(n,c),d=u!==null?Es(n,c+u.length):null;u!==null&&d!==null?(t=u,s=d,c+=u.length+d.length,i=K(n,c),c+=4,r=K(n,c),c+=4,o=K(n,c),c+=4,l=K(n,c),c+=4):(le.warn(`Unterminated ${u===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),c=n.length)}else if(e===1){i=K(n,c),c+=4;const u=K(n,c);c+=4;const d=K(n,c);c+=4,a=2**32*u+d,xl(a)||(a=Number.MAX_SAFE_INTEGER,le.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(n,c),c+=4,l=K(n,c),c+=4;const f=Es(n,c),g=f!==null?Es(n,c+f.length):null;f!==null&&(t=f,c+=f.length),g!==null?(s=g,c+=g.length):(le.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),c=n.length)}const h=n.subarray(c,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function yc(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function Ec(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),yc([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function mn(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=Tc(i);e.push(r),s+=r.size}}return e}function vc(n){const e=[];for(let t=0;t<n.length;){const s=n[t++],i=s&7;if(i===0){for(;n[t++]&128;);continue}if(i!==2){t+=i===1?8:4;continue}let r=0;for(let a=0,o=128;o&128;a+=7)r|=((o=n[t++])&127)<<a;if(s>>3===2)if(r===32){const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(n[t+o*2],n[t+o*2+1]),16);e.push(a)}else r===16&&e.push(n.subarray(t,t+16));t+=r}return e}function Tc(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Ee(new Uint8Array(a,t+12,16));let l=null,c=null,h=0;if(r===0)h=28;else{const d=n.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};l=[];for(let f=0;f<d;f++)l.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=n.getUint32(h);return e-32<u?{offset:t,size:e}:(c=new Uint8Array(a,t+h+4,u),r===0&&(l=vc(c)),{version:r,systemId:o,kids:l,data:c,offset:t,size:e})}const Mt=pn("userAgent"),Sc=pn("vendor");let yi,Ei,vi;function pn(n){try{return navigator[n]||""}catch{}return""}function xc(){if(vi===void 0){const n=Mt.match(/Safari\/(\d+)/i);vi=n?parseInt(n[1]):0}return vi}function Xt(){if(yi===void 0){const n=Mt.match(/Chrome\/(\d+)/i);yi=n?parseInt(n[1]):0}return yi}function bc(){if(Ei===void 0){const n=Mt.match(/Firefox\/(\d+)/i);Ei=n?parseInt(n[1]):0}return Ei}function An(){return/\(Windows.+Firefox\//i.test(Mt)}function Lc(){return Sc.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Mt)}function Rc(){return/Android/.test(Mt)}const Ot={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function Ti(n,e){const t=Ot[e];return!!t&&!!t[n.slice(0,4)]}function Zt(n,e,t=!0){return!n.split(",").some(s=>!Si(s,e,t))}function Si(n,e,t=!0){var s;const i=Ct(t);return(s=i?.isTypeSupported(Qt(n,e)))!=null?s:!1}function Qt(n,e){return`${e}/mp4;codecs=${n}`}function In(n){if(n){const e=n.substring(0,4);return Ot.video[e]}return 2}function Ss(n){const e=An();return n.split(",").reduce((t,s)=>{const r=e&&zt(s)?9:Ot.video[s];return r?(r*2+t)/(t?3:2):(Ot.audio[s]+t)/(t?2:1)},0)}const xi={};function Dc(n,e=!0){if(xi[n])return xi[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(Si(t[i],"audio",e))return xi[n]=t[i],t[i];if(t[i]==="mp3"&&(s=Ct(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const Pc=/flac|opus|mp4a\.40\.34/i;function xs(n,e=!0){return n.replace(Pc,t=>Dc(t.toLowerCase(),e))}function _c(n,e){const t=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)Ti(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function bs(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Cn(n,"audio")||Cn(n,"video")))return n;if(e){const t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function Cn(n,e){return Ti(n,e)&&Si(n,e)}function kc(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function wc(n){if(n.startsWith("av01.")){const e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function yn(n){const e=Ct(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function bi(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Mc={supported:!0,powerEfficient:!0,smooth:!0},Oc={supported:!1,smooth:!1,powerEfficient:!1},En={supported:!0,configurations:[],decodingInfoResults:[Mc]};function vn(n,e){return{supported:!1,configurations:e,decodingInfoResults:[Oc],error:n}}function Fc(n,e,t,s,i,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,l=r?.audioCodec,c=r?.channels,h=c?parseInt(c):l?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{d[m]=(d[m]||0)+g.channels[m]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>zt(d))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!u&&B(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function Tn(n,e,t,s={}){const i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve(En);const r=[],a=Nc(n),o=a.length,l=Bc(n,e,o>0),c=l.length;for(let h=o||1*c||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),c){u.audio=l[h%c];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>zt(u))&&An())return Promise.resolve(vn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=Uc(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Nc(n){var e;const t=(e=n.videoCodec)==null?void 0:e.split(","),s=xn(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:Qt(wc(l),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function Bc(n,e,t){var s;const i=(s=n.audioCodec)==null?void 0:s.split(","),r=xn(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:Qt(f,"audio"),bitrate:t?Sn(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},a):a},[]):[]}function Sn(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function xn(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function Uc(n){let e="";const{audio:t,video:s}=n;if(s){const i=bi(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=bi(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}function yt(n,e,t){const s=encodeURIComponent(e),i=`${s}=${encodeURIComponent(t)}`;let r=!1;const a=[];n.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?r||(a.push(i),r=!0):o&&a.push(o)}),r||a.push(i),n.search=a.join("&")}const Li=["NONE","TYPE-0","TYPE-1",null];function $c(n){return Li.indexOf(n)>-1}const Ls=["SDR","PQ","HLG"];function Gc(n){return!!n&&Ls.indexOf(n)>-1}var Rs={No:"",Yes:"YES",v2:"v2"};function bn(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?Rs.v2:Rs.Yes:Rs.No}class Ln{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&yt(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&yt(t,"_HLS_part",this.part.toString()),this.skip&&yt(t,"_HLS_skip",this.skip),t.href}}class Jt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Rn(this._audioGroups,e)}hasSubtitleGroup(e){return Rn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Rn(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function Vc(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function Kc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||Ls.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Vc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Hc=n=>{const e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},fe=(n,e)=>JSON.stringify(n,Hc(e));function Yc(n,e,t,s,i){const r=Object.keys(n),a=s?.channels,o=s?.audioCodec,l=i?.videoCodec,c=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,m=1/0,A=0,I=[];const{preferHDR:y,allowedVideoRanges:C}=Kc(e,i);for(let L=r.length;L--;){const R=n[r[L]];h||(h=R.channels[2]>0),d=Math.min(d,R.minHeight),f=Math.min(f,R.minFramerate),g=Math.min(g,R.minBitrate),C.filter(P=>R.videoRanges[P]>0).length>0&&(u=!0)}d=B(d)?d:0,f=B(f)?f:0;const E=Math.max(1080,d),v=Math.max(30,f);g=B(g)?g:t,t=Math.max(g,t),u||(e=void 0);const T=r.length>1;return{codecSet:r.reduce((L,R)=>{const x=n[R];if(R===L)return L;if(I=u?C.filter(P=>x.videoRanges[P]>0):[],T){if(x.minBitrate>t)return rt(R,`min bitrate of ${x.minBitrate} > current estimate of ${t}`),L;if(!x.hasDefaultAudio)return rt(R,"no renditions with default or auto-select sound found"),L;if(o&&R.indexOf(o.substring(0,4))%5!==0)return rt(R,`audio codec preference "${o}" not found`),L;if(a&&!c){if(!x.channels[a])return rt(R,`no renditions with ${a} channel sound found (channels options: ${Object.keys(x.channels)})`),L}else if((!o||c)&&h&&x.channels[2]===0)return rt(R,"no renditions with stereo sound found"),L;if(x.minHeight>E)return rt(R,`min resolution of ${x.minHeight} > maximum of ${E}`),L;if(x.minFramerate>v)return rt(R,`min framerate of ${x.minFramerate} > maximum of ${v}`),L;if(!I.some(P=>x.videoRanges[P]>0))return rt(R,`no variants with VIDEO-RANGE of ${fe(I)} found`),L;if(l&&R.indexOf(l.substring(0,4))%5!==0)return rt(R,`video codec preference "${l}" not found`),L;if(x.maxScore<A)return rt(R,`max score of ${x.maxScore} < selected max of ${A}`),L}return L&&(Ss(R)>=Ss(L)||x.fragmentError>n[L].fragmentError)?L:(m=x.minIndex,A=x.maxScore,R)},void 0),videoRanges:I,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}function rt(n,e){le.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Dn(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Wc(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;const o=r.audioGroups;let l=i[r.codecSet];l||(i[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const c=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),i},{})}function Pn(n){if(!n)return n;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function nt(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(bt(n,i,t))return s}return-1}function bt(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,l=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||jc(r,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in n)||zc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function jc(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function zc(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Lt(n,e){const{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function qc(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const m=f.uri;return(d[m]||(d[m]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=_n(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(m=>es(m.groupId,f));return nt(n,g,i)>-1});return u>-1?u:_n(e,s,d=>{const f=d.audioGroups,g=t.filter(m=>es(m.groupId,f));return nt(n,g,i)>-1})}function _n(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function Ds(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}function es(n,e){return e?e.indexOf(n)!==-1:!0}function kn(n,e){if(e||n){const t=ue({},e);return n&&(n.videoCodec&&(t.videoCodec=n.videoCodec),n.videoRange&&(t.allowedVideoRanges=[n.videoRange])),t}}class Xc extends Ue{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;const c=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=c-h.loading.start,f=a.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const A=m>-1&&m!==g,I=!!t||A;if(!I&&(l.paused||!l.playbackRate||!l.readyState))return;const y=a.mainForwardBufferInfo;if(!I&&y===null)return;const C=this.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(d<=Math.max(C,1e3*(u/(E*2))))return;const v=y?y.len/E:0,T=h.loading.first?h.loading.first-h.loading.start:-1,S=h.loaded&&T>-1,L=this.getBwEstimate(),R=a.levels,x=R[g],P=Math.max(h.loaded,Math.round(u*(i.bitrate||x.averageBitrate)/8));let _=S?d-T:d;_<1&&S&&(_=Math.min(d,h.loaded*8/L));const F=S?h.loaded*1e3/_:0,V=C/1e3,U=F?(P-h.loaded)/F:P*8/L+V;if(U<=v)return;const k=F?F*8:L,M=((s=t?.details||a.latestLevelDetails)==null?void 0:s.live)===!0,w=a.config.abrBandWidthUpFactor;let N=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){const q=R[Y].maxBitrate,ie=!R[Y].details||M;if(N=this.getTimeToLoadFrag(V,k,u*q,ie),N<Math.min(v,u+V))break}if(N>=U||N>u*10)return;S?this.bwEstimator.sample(d-Math.min(C,T),h.loaded):this.bwEstimator.sampleTTFB(d);const O=R[Y].maxBitrate;this.getBwEstimate()*w>O&&(this.firstAutoFloor=Math.min(Y,a.firstLevel),this.resetEstimator(O));const G=this.findBestLevel(O,f,Y,0,v,1,1);G>-1&&(Y=G),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
|
|
151
|
+
Fragment duration: ${i.duration.toFixed(3)}
|
|
152
|
+
Time to underbuffer: ${v.toFixed(3)} s
|
|
153
|
+
Estimated load time for current fragment: ${U.toFixed(3)} s
|
|
154
|
+
Estimated load time for down switch fragment: ${N.toFixed(3)} s
|
|
155
|
+
TTFB estimate: ${T|0} ms
|
|
156
|
+
Current BW estimate: ${B(L)?L|0:"Unknown"} bps
|
|
157
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
158
|
+
Switching to level ${Y} @ ${O|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Y,this.clearTimer();const ee=()=>{this.clearTimer();const q=this.hls;if(this.fragCurrent===i&&q.loadLevel===Y&&Y>0){const ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
|
|
159
|
+
Fragment duration: ${i.duration.toFixed(3)} s
|
|
160
|
+
Time to underbuffer: ${ie.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>f){let Z=this.findBestLevel(q.levels[f].bitrate,f,Y,0,ie,1,1);Z===-1&&(Z=f),q.nextLoadLevel=q.nextAutoLevel=Z,this.firstAutoFloor=Math.min(Z,q.firstLevel),this.resetEstimator(q.levels[Z].bitrate)}}};A||U>N*2?ee():this.timer=self.setInterval(ee,N*1e3),a.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new Fl(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i: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 b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case b.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&li(s,i)){const a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;B(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;const{frag:i,part:r}=t,a=r?r.stats:i.stats;if(i.type===H.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){const o=r?r.duration:i.duration,l=this.hls.levels[i.level],c=(l.loaded?l.loaded.bytes:0)+a.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:c,duration:h},l.realBitrate=Math.round(8*c/h)}if(i.bitrateTest){const o={stats:a,frag:i,part:r,id:i.type};this.onFragBuffered(p.FRAG_BUFFERED,o),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const o=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==H.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:s}=e,i=this.getBwEstimate(),r=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(i,s,t,r/2,a,1,1);if(o>-1)return o;const l=e.firstLevel,c=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,h=Math.min(Math.max(l,s),t,c);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const A=this.findBestLevel(l,a,i,c,0,h,u);if(A>=0)return this.rebufferNotice=-1,A}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const A=this.bitrateTestDelay;A&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-A,this.info(`bitrate test took ${Math.round(1e3*A)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(l,a,i,c,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],m=s.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e?.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,i,r,a,o){const{hls:l,lastLoadedFragLevel:c,fragCurrent:h,partCurrent:u}=this;if(!l)return-1;const d=i+r,f=c===-1?l.firstLevel:c,{levels:g,allAudioTracks:m,loadLevel:A,latestLevelDetails:I,config:y}=l;if(g.length===1)return 0;const C=g[f],E=!!(I!=null&&I.live),v=A===-1||c===-1;let T,S="SDR",L=C?.frameRate||0;const{audioPreference:R,videoPreference:x}=y,P=this.audioTracksByGroup||(this.audioTracksByGroup=Dn(m));let _=-1;if(v){if(this.firstSelection!==-1)return this.firstSelection;const M=this.codecTiers||(this.codecTiers=Wc(g,P,t,s)),w=Yc(M,S,e,R,x),{codecSet:N,videoRanges:Y,minFramerate:O,minBitrate:G,minIndex:ee,preferHDR:q}=w;_=ee,T=N,S=q?Y[Y.length-1]:Y[0],L=O,e=Math.max(e,G),this.log(`picked start tier ${fe(w)}`)}else T=C?.codecSet,S=C?.videoRange;const F=u?u.duration:h?h.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,U=[];for(let M=s;M>=t;M--){var k;const w=g[M],N=M>f;if(!w)continue;if(y.useMediaCapabilities&&!w.supportedResult&&!w.supportedPromise){const Z=navigator.mediaCapabilities;typeof Z?.decodingInfo=="function"&&Fc(w,P,S,L,e,R)?(w.supportedPromise=Tn(w,P,Z,this.supportedCache),w.supportedPromise.then(ne=>{if(!this.hls)return;w.supportedResult=ne;const te=this.hls.levels,oe=te.indexOf(w);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${oe} ${fe(ne)}`):ne.supported?ne.decodingInfoResults.some(Te=>Te.smooth===!1||Te.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${oe} not smooth or powerEfficient: ${fe(ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${oe} ${fe(ne)}`),oe>-1&&te.length>1&&(this.log(`Removing unsupported level ${oe}`),this.hls.removeLevel(oe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ne}`)})):w.supportedResult=En}if((T&&w.codecSet!==T||S&&w.videoRange!==S||N&&L>w.frameRate||!N&&L>0&&L<w.frameRate||(k=w.supportedResult)!=null&&(k=k.decodingInfoResults)!=null&&k.some(Z=>Z.smooth===!1))&&(!v||M!==_)){U.push(M);continue}const Y=w.details,O=(u?Y?.partTarget:Y?.averagetargetduration)||F||1;let G;N?G=o*e:G=a*e;const ee=F&&i>=F*2&&r===0?w.averageBitrate:w.maxBitrate,q=this.getTimeToLoadFrag(V,G,ee*O,!Y||Y.live);if(G>=ee&&(M===c||w.loadError===0&&w.fragmentError===0||Yr(w,y.errorPenaltyExpireMs))&&(q<=V||!B(q)||E&&!this.bitrateTestDelay||q<d)){const Z=this.forcedAutoLevel;return M!==A&&(Z===-1||Z!==A)&&(U.length&&this.trace(`Skipped level(s) ${U.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[U[0]].codecs}" ${g[U[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${f}->${M} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-ee)} ttfb:${V.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${q.toFixed(1)} firstSelection:${v} codecSet:${w.codecSet} videoRange:${w.videoRange} hls.loadLevel:${A}`)),v&&(this.firstSelection=M),M}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const wn={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function Zc(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!B(e))return null;const s=n[0].programDateTime;if(e<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Jc(e,t,a))return a}return null}function Ft(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&Mn(t,s,r)===0||Qc(r,n,Math.min(i,s))))return r;const a=wn.search(e,Mn.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Qc(n,e,t){if(e?.start===0&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function Mn(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function Jc(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function On(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments;const{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return wn.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function Fn(n,e){return e===n.endSN&&n.fragmentHint?n.fragmentHint:n.fragments[1+e-n.startSN]||null}var be={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},xe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class eh extends Ue{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case b.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ts();return}case b.FRAG_GAP:case b.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=be.SendAlternateToPenaltyBox;return}case b.PLAYLIST_UNCHANGED_ERROR:case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:{var a;const o=t.parent===H.MAIN?t.level:i.loadLevel;t.details===b.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=i.loadLevelObj;if(o&&(r.type===se.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===se.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=be.SendAlternateToPenaltyBox,t.errorAction.flags=xe.MoveAllAlternatesMatchingHost;return}}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:be.SendAlternateToPenaltyBox,flags:xe.MoveAllAlternatesMatchingHDCP};return;case b.KEY_SYSTEM_SESSION_UPDATE_FAILED:case b.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case b.KEY_SYSTEM_NO_SESSION:t.errorAction={action:be.SendAlternateToPenaltyBox,flags:xe.MoveAllAlternatesMatchingKey};return;case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:case b.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case b.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=xe.ResetMediaSource|xe.SwitchToSDR;return;case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_APPEND_NO_PROGRESS:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:t.errorAction=ts();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ts())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Kr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Yt(i,r,ps(e),e.response))return{action:be.RetryRequest,flags:xe.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Kr(Gr(e)?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==b.FRAG_GAP&&i.fragmentError++,!Vr(e)&&Yt(o,l,ps(e),e.response)))return{action:be.RetryRequest,flags:xe.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const c=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),c===b.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,I=(m===H.AUDIO&&c===b.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Nn(e))&&u.some(({audioCodec:T})=>i.audioCodec!==T),C=e.sourceBufferName==="video"&&Nn(e)&&u.some(({codecSet:T,audioCodec:S})=>i.codecSet!==T&&i.audioCodec===S),{type:E,groupId:v}=(a=e.context)!=null?a:{};for(let T=u.length;T--;){const S=(T+d)%u.length;if(S!==d&&S>=f&&S<=g&&(u[S].loadError===0||Yr(u[S],s.config.errorPenaltyExpireMs))){var o,l;const L=u[S];if(c===b.FRAG_GAP&&m===H.MAIN&&e.frag){const R=u[S].details;if(R){const x=Ft(e.frag,R.fragments,e.frag.start);if(x!=null&&x.gap)continue}}else{if(E===se.AUDIO_TRACK&&L.hasAudioGroup(v)||E===se.SUBTITLE_TRACK&&L.hasSubtitleGroup(v))continue;if(m===H.AUDIO&&(o=i.audioGroups)!=null&&o.some(R=>L.hasAudioGroup(R))||m===H.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(R=>L.hasSubtitleGroup(R))||I&&i.audioCodec===L.audioCodec||C&&i.codecSet===L.codecSet||!I&&i.audioCodec!==L.audioCodec)continue}h=S;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:be.SendAlternateToPenaltyBox,flags:xe.None,nextAutoLevel:h}}return{action:be.SendAlternateToPenaltyBox,flags:xe.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,i;switch((s=t.errorAction)==null?void 0:s.action){case be.DoNothing:break;case be.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==b.FRAG_GAP&&t.details!==b.PLAYLIST_UNCHANGED_ERROR&&!Bn(t)&&(t.fatal=!0);break}if((((i=t.errorAction)==null?void 0:i.flags)||0)&xe.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===xe.None)this.switchLevel(e,i);else if(s.flags&xe.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let c=l;c--;)o[c].videoRange!=="SDR"?(o[c].fragmentError++,o[c].loadError++):i===void 0&&(i=c)}else if(s.flags&xe.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],c=l?.attrs["HDCP-LEVEL"];s.hdcpLevel=c;const h=c==="NONE";c&&!h?(t.maxHdcpLevel=Li[Li.indexOf(c)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(h&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=xe.MoveAllAlternatesMatchingKey)}if(s.flags&xe.MoveAllAlternatesMatchingKey){const o=e.decryptdata;if(o){const l=this.hls.levels,c=l.length;for(let u=c;u--;)if(this.variantHasKey(l[u],o)){var r,a;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(r=l[u].audioGroups)==null?void 0:r.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ee(o.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}const h=e.frag;if(this.hls.levels.length<c)s.resolved=!0;else if(h&&h.type!==H.MAIN){const u=h.decryptdata;u&&!o.matches(u)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===b.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=bi(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Nn(n){const e=n.details;return e===b.BUFFER_ADD_CODEC_ERROR||e===b.MEDIA_SOURCE_REQUIRES_RESET||e===b.BUFFER_APPEND_ERROR&&!Bn(n)}function Bn(n){return n.details===b.BUFFER_APPEND_ERROR&&(n.error.name==="QuotaExceededError"||n.error.name==="InvalidStateError")}function ts(n){const e={action:be.DoNothing,flags:xe.None};return n&&(e.resolved=!0),e}var pe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class th{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){const o=i[r[a]];if(o?.body.type===t&&(!s||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,i,r,a){this.timeRanges&&(this.timeRanges[e]=t);const o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{const c=this.fragments[l];if(!c||!this.hls)return;const h=c.body;if(o>=h.sn)return;if(!c.buffered&&(!c.loaded||a)){h.type===s&&this.removeFragment(h);return}const u=c.range[e];if(u){if(u.time.length===0){this.removeFragment(h);return}if(u.time.some(d=>{const f=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return f&&this.removeFragment(h),f}),i&&i!==h&&Xt()){const d=i.endPTS,f=h.startPTS;if(d&&f&&c.range.video){const g=f-d;g<0&&g>-.1&&(this.removeFragment(h),this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i,id:r}=e;if(!t||!Ie(s))return;const a=Nt(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;const l=!s.relurl;Object.keys(t).forEach(h=>{const u=s.elementaryStreams[h];if(!u)return;const d=t[h],f=l||u.partial===!0;o.range[h]=this.getBufferedTimes(s,i,f,d),this.detectEvictedFragments(h,d,r,s,i)}),o.loaded=null;const c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,s),Ps(o)||this.removeParts(s.sn-1,s.type),!i){const h=Math.min(.004,s.duration);c.some(u=>{var d;const f=(d=o.range[u])==null?void 0:d.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<h;return g&&this.addAsGap(s),g})}}else this.removeFragment(s)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Un(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Nt(e);let i=this.fragments[s];return!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&Ps(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Ps(t))}getState(e){const t=Nt(e),s=this.fragments[t];return s?s.buffered?Ps(s)?pe.PARTIAL:pe.OK:pe.APPENDING:pe.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Ie(t.frag)||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Nt(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(!Ie(s))return;const a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Nt(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,s){const{fragments:i}=this;let r=0,a=0;const o=Object.keys(i);for(let l=0;l<o.length;l++){const c=i[o[l]];if(!c||!c.buffered||c.body.type!==t)continue;const h=c.body;if(h.gap)return 0;const u=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&h.bitrate*8*h.duration;if(h.end<=e&&u&&(r+=u,a=Math.max(a,h.end),r>=s))return a}return a>0?a:0}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Nt(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Un(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function Ps(n){var e,t,s,i;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial||(i=n.range.subs)!=null&&i.partial)}function Nt(n){return`${n.type}_${n.level}_${n.sn}`}function Un(n,e){return n.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Et={cbc:0,ctr:1};class sh{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Et.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Et.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function ih(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class rh{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),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let g=0,m=0,A=0;for(A=0;A<256;A++)A<128?f[A]=A<<1:f[A]=A<<1^283;for(A=0;A<256;A++){let I=m^m<<1^m<<2^m<<3^m<<4;I=I>>>8^I&255^99,e[g]=I,t[I]=g;const y=f[g],C=f[y],E=f[C];let v=f[I]*257^I*16843008;i[g]=v<<24|v>>>8,r[g]=v<<16|v>>>16,a[g]=v<<8|v>>>24,o[g]=v,v=E*16843009^C*65537^y*257^g*16843008,c[I]=v<<24|v>>>8,h[I]=v<<16|v>>>16,u[I]=v<<8|v>>>24,d[I]=v,g?(g=y^f[f[f[E^y]]],m^=f[f[m]]):g=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],m=f[1],A=f[2],I=f[3];let y,C;for(o=0;o<a;o++){if(o<r){y=c[o]=t[o];continue}C=y,o%r===0?(C=C<<8|C>>>24,C=u[C>>>24]<<24|u[C>>>16&255]<<16|u[C>>>8&255]<<8|u[C&255],C^=d[o/r|0]<<24):r>6&&o%r===4&&(C=u[C>>>24]<<24|u[C>>>16&255]<<16|u[C>>>8&255]<<8|u[C&255]),c[o]=y=(c[o-r]^C)>>>0}for(l=0;l<a;l++)o=a-l,l&3?C=c[o]:C=c[o-4],l<4||o<=4?h[l]=C:h[l]=g[u[C>>>24]]^m[u[C>>>16&255]]^A[u[C>>>8&255]]^I[u[C&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],m=d[2],A=d[3];const I=new Int32Array(e),y=new Int32Array(I.length);let C,E,v,T,S,L,R,x,P,_,F,V,U,k;const M=this.networkToHostOrderSwap;for(;t<I.length;){for(P=M(I[t]),_=M(I[t+1]),F=M(I[t+2]),V=M(I[t+3]),S=P^r[0],L=V^r[1],R=F^r[2],x=_^r[3],U=4,k=1;k<i;k++)C=l[S>>>24]^c[L>>16&255]^h[R>>8&255]^u[x&255]^r[U],E=l[L>>>24]^c[R>>16&255]^h[x>>8&255]^u[S&255]^r[U+1],v=l[R>>>24]^c[x>>16&255]^h[S>>8&255]^u[L&255]^r[U+2],T=l[x>>>24]^c[S>>16&255]^h[L>>8&255]^u[R&255]^r[U+3],S=C,L=E,R=v,x=T,U=U+4;C=a[S>>>24]<<24^a[L>>16&255]<<16^a[R>>8&255]<<8^a[x&255]^r[U],E=a[L>>>24]<<24^a[R>>16&255]<<16^a[x>>8&255]<<8^a[S&255]^r[U+1],v=a[R>>>24]<<24^a[x>>16&255]<<16^a[S>>8&255]<<8^a[L&255]^r[U+2],T=a[x>>>24]<<24^a[S>>16&255]<<16^a[L>>8&255]<<8^a[R&255]^r[U+3],y[t]=M(C^f),y[t+1]=M(T^g),y[t+2]=M(v^m),y[t+3]=M(E^A),f=P,g=_,m=F,A=V,t=t+4}return y.buffer}}class nh{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=ah(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function ah(n){switch(n){case Et.cbc:return"AES-CBC";case Et.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const oh=16;class Ri{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);this.reset();const i=this.decryptRange;return i?i.start===0&&i.end>=s.length?s:s.slice(i.start,i.end):ih(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((a,o)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,s,i);const c=this.flush();c?a(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==Et.cbc||t.byteLength!==16)return le.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ye(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;r&&(s=r);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new rh),c.expandKey(t);const h=a;return this.currentResult=c.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new nh(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new sh(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(le.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%oh;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(le.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const $n=Math.pow(2,17);class Gn{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,s,i){const r=e.url;if(!r)return Promise.reject(new at({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,o=a.fLoader,l=a.loader;return new Promise((c,h)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(A=>A[0]==="GAP")){h(Kn(e));return}else e.gap=!1;const u=this.loader=o?new o(a):new l(a),d=Vn(e,null,t);e.loader=u;const f=Hr(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:$n};u.stats.retry=e.stats.retry,e.stats=u.stats;const m={onSuccess:(A,I,y,C)=>{this.resetLoader(e,u);let E=A.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),c({frag:e,part:null,payload:E,networkDetails:C})},onError:(A,I,y,C)=>{this.resetLoader(e,u),h(new at({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:z({url:r,data:void 0},A),error:new Error(`HTTP Error ${A.code} ${A.text}`),networkDetails:y,stats:C}))},onAbort:(A,I,y)=>{this.resetLoader(e,u),h(new at({type:W.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:A}))},onTimeout:(A,I,y)=>{this.resetLoader(e,u),h(new at({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:y,stats:A}))}};if(s){const A=this.gateProgress(s,i);m.onProgress=(I,y,C,E)=>A({frag:e,part:null,payload:C,networkDetails:E})}u.load(d,g,m)})}gateProgress(e,t){let s=e;if(t){const i=[];let r=!1;t.then(()=>{r=!0,i.forEach(a=>e(a)),i.length=0}).catch(()=>{}),s=a=>{r?e(a):i.push(a)}}return s}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Kn(e,t));return}const c=this.loader=r?new r(i):new a(i),h=Vn(e,t);e.loader=c;const u=Hr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$n};t.stats=c.stats,c.load(h,d,{onSuccess:(f,g,m,A)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const I={frag:e,part:t,payload:f.data,networkDetails:A};s(I),o(I)},onError:(f,g,m,A)=>{this.resetLoader(e,c),l(new at({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:z({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:A}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new at({type:W.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,c),l(new at({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Vn(n,e=null,t){const s=e||n,i={type:se.MEDIA_FRAGMENT,frag:n,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=_s(n,e,t);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function _s(n,e=null,t){const s={},i=e||n,r=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(B(r)&&B(a)){var o;if((n.sn==="initSegment"||t)&&lh((o=n.decryptdata)==null?void 0:o.method)){let l=Math.floor(r/16)*16;const c=Math.ceil(a/16)*16;s.decryptRange={start:r-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:c}}else s.byteRange={start:r,end:a}}return s}function Kn(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:b.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new at(s)}function lh(n){return n==="AES-128"||n==="AES-256"}class at extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Hn extends Ue{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Di{constructor(e,t,s,i=0,r=-1,a=!1,o,l,c){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=ks(),this.buffering={audio:ks(),video:ks(),audiovideo:ks()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=l||!1}}function ks(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Yn={length:0,start:()=>0,end:()=>0};class X{static isBuffered(e,t){if(e){const s=X.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=X.getBuffered(e);return X.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=X.bufferedRanges(e);if(i.length)return X.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,c=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)l=u,c=d,a=c-t;else if(t+s<u){o=u;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Yn}catch(t){return le.log("failed to get media.buffered",t),Yn}}}const Pi=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wn(n){return Pi.lastIndex=0,Pi.test(n)}function _i(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(Pi,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function jn(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function ch(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const hh=/^(\d+)x(\d+)$/,zn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ae{constructor(e,t){typeof e=="string"&&(e=Ae.parseAttrList(e,t)),ue(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=hh.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(zn.lastIndex=0;(s=zn.exec(e))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=_i(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":le.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const uh="com.apple.hls.interstitial";function dh(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function fh(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class qn{constructor(e,t,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=t?.tagAnchor||null,this.tagOrder=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){le.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ue(new Ae({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const r=t?.endDate||new Date(e["END-DATE"]);B(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(le.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(B(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===uh}get isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:B(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}const Xn=10;class gh{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Xn}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ws(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function Zn(n,e){return!n&&!e?!0:!n||!e?!1:ws(n,e)}function Bt(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function ki(n){switch(n){case"AES-128":case"AES-256":return Et.cbc;case"AES-256-CTR":return Et.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function wi(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function mh(n){const e=wi(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Qn(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Jn(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=pi(a)):t=mh(a)}}return t}const Ms=typeof self<"u"?self:void 0;var me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Le={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Os(n){switch(n){case Le.FAIRPLAY:return me.FAIRPLAY;case Le.PLAYREADY:return me.PLAYREADY;case Le.WIDEVINE:return me.WIDEVINE;case Le.CLEARKEY:return me.CLEARKEY}}var ea={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Mi(n){switch(n){case me.FAIRPLAY:return Le.FAIRPLAY;case me.PLAYREADY:return Le.PLAYREADY;case me.WIDEVINE:return Le.WIDEVINE;case me.CLEARKEY:return Le.CLEARKEY}}function ss(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[me.FAIRPLAY,me.WIDEVINE,me.PLAYREADY,me.CLEARKEY].filter(i=>!!e[i]):[];return!s[me.WIDEVINE]&&t&&s.push(me.WIDEVINE),s}const ta=(function(n){return Ms!=null&&(n=Ms.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function ph(n,e,t,s){let i;switch(n){case me.FAIRPLAY:i=["cenc","sinf"];break;case me.WIDEVINE:case me.PLAYREADY:i=["cenc"];break;case me.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return Ah(i,e,t,s)}function Ah(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Ih(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Oi(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=ze(e),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=pi(o).subarray(0,16);return Qn(l),l}}return null}let Ut={};class dt{static clearKeyUriToKeyIdMap(){Ut={}}static setKeyIdForUri(e,t){Ut[e]=t}static addKeyIdForUri(e){const t=Object.keys(Ut).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Ut[e]=s,s}constructor(e,t,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Bt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(en(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ws(e.keyFormatVersions,this.keyFormatVersions)&&Zn(e.iv,this.iv)&&Zn(e.keyId,this.keyId)}isSupported(){if(this.method){if(Bt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Le.FAIRPLAY:case Le.WIDEVINE:case Le.PLAYREADY:case Le.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var s;if(!this.encrypted||!this.uri)return null;if(Bt(this.method)){let a=this.iv;return a||(typeof e!="number"&&(le.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=yh(e)),new dt(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=Ut[this.uri];if(a&&!ws(this.keyId,a)&&dt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Jn(this.uri);if(i)switch(this.keyFormat){case Le.WIDEVINE:if(this.pssh=i,!this.keyId){const a=mn(i.buffer).filter(o=>o.systemId===ea.WIDEVINE);if(a.length){var r;const o=a[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=sa(t));break;case Le.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ec(a,null,i),this.keyId=Oi(i);break}default:{let a=i.subarray(0,16);if(a.length!==16){const o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=Ch(t),a||(a=sa(t),a||(a=Ut[this.uri])),a&&(this.keyId=a,dt.setKeyIdForUri(this.uri,a))}return this}}function Ch(n){const e=n?.[Le.WIDEVINE];return e?e.keyId:null}function sa(n){const e=n?.[Le.PLAYREADY];if(e){const t=Jn(e.uri);if(t)return Oi(t)}return null}function yh(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const ia=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,ra=/#EXT-X-MEDIA:(.*)/g,Eh=/^#EXT(?:INF|-X-TARGETDURATION):/m,Fi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),vh=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ot{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return ai.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Eh.test(e)}static parseMasterPlaylist(e,t){const s=Wn(e),i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(ia.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=ia.exec(e))!=null;)if(a[1]){const l=new Ae(a[1],i),c=na(l,a[2],t,i,r);c&&i.levels.push(c)}else if(a[3]){const l=a[3],c=a[4];switch(l){case"I-FRAME-STREAM-INF":{const h=new Ae(c,i),u=na(h,h.URI,t,i,r,!0);u&&i.iframeVariants.push(u)}break;case"SESSION-DATA":{const h=new Ae(c,i),u=h["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=h);break}case"SESSION-KEY":{const h=oa(c,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):le.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const h=new Ae(c,i);jn(i,h,t)}break}case"CONTENT-STEERING":{const h=new Ae(c,i);i.contentSteering={uri:ot.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=la(c);break}}}const o=r.length>0&&r.length<i.levels.length;return i.levels=o?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(ra.lastIndex=0;(i=ra.exec(e))!==null;){const c=new Ae(i[1],s),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=c.LANGUAGE,g=c["ASSOC-LANGUAGE"],m=c.CHANNELS,A=c.CHARACTERISTICS,I=c["INSTREAM-ID"],y={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?ot.resolve(c.URI,t):""};if(g&&(y.assocLang=g),m&&(y.channels=m),A&&(y.characteristics=A),I&&(y.instreamId=I),u!=null&&u.length){const C=ot.findGroup(u,y.groupId)||u[0];ha(y,C,"audioCodec"),ha(y,C,"textCodec")}d.push(y)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;const l={url:t},c=new gh(t),h=c.fragments,u=[];let d=null,f=0,g=0,m=0,A=0,I=0,y=null,C=new gs(i,l),E,v,T,S=-1,L=!1,R=null,x;if(Fi.lastIndex=0,c.m3u8=e,c.hasVariableRefs=Wn(e),((o=Fi.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(E=Fi.exec(e))!==null;){L&&(L=!1,C=new gs(i,l),C.playlistOffset=m,C.setStart(m),C.sn=f,C.cc=A,I&&(C.bitrate=I),C.level=s,d&&(C.initSegment=d,d.rawProgramDateTime&&(C.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),R&&(C.setByteRange(R),R=null)));const U=E[1];if(U){C.duration=parseFloat(U);const k=(" "+E[2]).slice(1);C.title=k||null,C.tagList.push(k?["INF",U,k]:["INF",U])}else if(E[3]){if(B(C.duration)){var P;C.playlistOffset=m,C.setStart(m),T&&da(C,T,c),C.sn=f,C.level=s,C.cc=A;const k=(" "+E[3]).slice(1);C.relurl=_i(c,k),Ni(C,y,u),y=C,m+=C.duration,f++,g=0;const M=C.byteRange;if(M.length===2&&(C.bitrate=(M[1]-M[0])*8/C.duration|0),c.iframesOnly&&M[0]&&((P=d)==null?void 0:P.cc)!==A){const w=new gs(i,l);w.relurl=C.relurl,w.setByteRange(`${Math.min(M[0],1316)}@0`),w.level=s,w.sn="initSegment",T&&(w.levelkeys=T,T.identity&&(w._decryptdata=T.identity.getDecryptData(0))),d=w,C.initSegment=d}h.push(C),L=!0}}else{if(E=E[0].match(vh),!E){le.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<E.length&&E[v]===void 0;v++);const k=(" "+E[v]).slice(1),M=(" "+E[v+1]).slice(1),w=E[v+2]?(" "+E[v+2]).slice(1):null;switch(k){case"BYTERANGE":y?C.setByteRange(M,y):C.setByteRange(M);break;case"PROGRAM-DATE-TIME":C.rawProgramDateTime=M,C.tagList.push(["PROGRAM-DATE-TIME",M]),S===-1&&(S=h.length);break;case"PLAYLIST-TYPE":c.type&&ft(c,k,E),c.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?ft(c,k,E):y!==null&&xh(c,k,E),c.startSN=parseInt(M),f=c.startSN+c.skippedSegments;break;case"SKIP":{c.skippedSegments&&ft(c,k,E);const N=new Ae(M,c),Y=N.decimalInteger("SKIPPED-SEGMENTS");if(B(Y)){c.skippedSegments+=Y;for(let G=Y;G--;)h.push(null);f+=Y}const O=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&ft(c,k,E),c.targetduration=Math.max(parseInt(M),1);break;case"VERSION":c.version!==null&&ft(c,k,E),c.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":c.live||ft(c,k,E),c.live=!1;break;case"#":(M||w)&&C.tagList.push(w?[M,w]:[M]);break;case"DISCONTINUITY":A++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([k]);break;case"BITRATE":C.tagList.push([k,M]),I=parseInt(M)*1e3,B(I)?C.bitrate=I:I=0;break;case"DATERANGE":{const N=new Ae(M,c),Y=new qn(N,c.dateRanges[N.ID],c.dateRangeTagCount);c.dateRangeTagCount++,Y.isValid||c.skippedSegments?c.dateRanges[Y.id]=Y:le.log(`Ignoring invalid DATERANGE tag: ${Y.invalidReason}: ${M}`),C.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{{const N=new Ae(M,c);"IMPORT"in N?ch(c,N,a):jn(c,N,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0&&ft(c,k,E),c.startCC=A=parseInt(M),h.forEach(N=>N&&(N.cc=A));break;case"KEY":{const N=oa(M,t,c);if(N.isSupported()){if(N.method==="NONE"){T=void 0;break}T||(T={});const Y=T[N.keyFormat];Y!=null&&Y.matches(N)||(Y&&(T=ue({},T)),T[N.keyFormat]=N)}else le.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":c.startTimeOffset=la(M);break;case"MAP":{const N=new Ae(M,c);if(C.duration){const Y=new gs(i,l);ua(Y,N,s,T),d=Y,C.initSegment=d,d.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=d.rawProgramDateTime)}else{const Y=C.byteRangeEndOffset;if(Y){const O=C.byteRangeStartOffset;R=`${Y-O}@${O}`}else R=null;ua(C,N,s,T),d=C,L=!0}d.cc=A;break}case"SERVER-CONTROL":{x&&ft(c,k,E),x=new Ae(M),c.canBlockReload=x.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=x.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&x.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=x.optionalFloat("PART-HOLD-BACK",0),c.holdBack=x.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&ft(c,k,E);const N=new Ae(M);c.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=c.partList;N||(N=c.partList=[]);const Y=g>0?N[N.length-1]:void 0,O=g++,G=new Ae(M,c),ee=new Dl(G,C,l,O,Y);N.push(ee),C.duration+=ee.duration;break}case"PRELOAD-HINT":{const N=new Ae(M,c);c.preloadHint=N;break}case"RENDITION-REPORT":{const N=new Ae(M,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(N);break}default:le.warn(`line parsed but not handled: ${E}`);break}}}y&&!y.relurl?(h.pop(),m-=y.duration,c.partList&&(c.fragmentHint=y)):c.partList&&(Ni(C,y,u),C.cc=A,c.fragmentHint=C,T&&da(C,T,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const _=h.length,F=h[0],V=h[_-1];if(m+=c.skippedSegments*c.targetduration,m>0&&_&&V){c.averagetargetduration=m/_;const U=V.sn;c.endSN=U!=="initSegment"?U:0,c.live||(V.endList=!0),S>0&&(Sh(h,S,S>_-1?C:null),F&&u.unshift(F))}return c.fragmentHint&&(m+=c.fragmentHint.duration),c.totalduration=m,u.length&&c.dateRangeTagCount&&F&&aa(u,c),c.endCC=A,c}}function na(n,e,t,s,i,r){var a;if(e===void 0)return null;const o=_i(s,e),l={attrs:n,bitrate:n.decimalInteger("BANDWIDTH")||n.decimalInteger("AVERAGE-BANDWIDTH"),name:n.NAME,url:ot.resolve(o,t)},c=n.decimalResolution("RESOLUTION");c&&(l.width=c.width,l.height=c.height),ca(n.CODECS,l);const h=n["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},ca(h,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||i.push(l),r&&(l.iframes=!0),l}function aa(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;const s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],c=l.startDate.getTime();l.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;const u=Th(e,c,n,h,i);if(u){l.tagAnchor=u.ref;break}}}}function Th(n,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var a;const l=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+l*1e3){const c=r.sn-n.startSN,h=n.fragments;if(c>=0&&c<h.length){if(h.length>t.length){const u=t[s+1]||h[h.length-1],d=Math.min(u.sn-n.startSN,h.length-1);for(let f=d;f>c;f--){const g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return h[f]}}return h[c]}}}}return null}function oa(n,e,t){var s,i;const r=new Ae(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&le.error(`Invalid IV: ${r.IV}`);const u=o?ot.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new dt(a,u,h,d,l,r.KEYID)}function la(n){const t=new Ae(n).decimalFloatingPoint("TIME-OFFSET");return B(t)?t:null}function ca(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{const i=t.filter(r=>Ti(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function ha(n,e,t){const s=e[t];s&&(n[t]=s)}function Sh(n,e,t){if(t||(t=n[e]),!!t)for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ni(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function ua(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function da(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function ft(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function xh(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Bi(n,e){const t=e.startPTS;if(B(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function fa(n,e,t,s,i,r,a,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,h=s;const u=e.startPTS,d=e.endPTS;if(B(u)){const y=Math.abs(u-t);n&&y>n.totalduration?o.warn(`media timestamps and playlist times differ by ${y}s for level ${e.level} ${n.url}`):B(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,c=Math.max(t,u),t=Math.min(t,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,h=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=h,e.endDTS=r;const g=e.sn;if(!n||g<n.startSN||g>n.endSN)return 0;let m;const A=g-n.startSN,I=n.fragments;for(I[A]=e,m=A;m>0;m--)Bi(I[m],I[m-1]);for(m=A;m<I.length-1;m++)Bi(I[m],I[m+1]);return n.fragmentHint&&Bi(I[I.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,f}function bh(n,e,t){if(n===e)return;let s=null;const i=n.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;Dh(n,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const g=h.cc-u.cc;for(let m=d;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}B(h.startPTS)&&B(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Lh(n.dateRanges,e,t));const h=n.fragments.filter(u=>u.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ni(o[u],o[u-1],h);aa(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const h=Aa(n,e.startSN-1);e.startCC=(l=h?.cc)!=null?l:a[0].cc}if(Rh(n.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats,u.gap=h.gap||u.gap}),r){const h=e.iframesOnly&&r.type===H.MAIN;fa(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,h,t)}else ma(n,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const h=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=h),e.driftEndTime=c,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function Lh(n,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ue({},n);i&&i.forEach(l=>{delete r[l]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(l=>{const c=r[l],h=new qn(s[l].attr,c);h.isValid?(r[l]=h,c||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fe(s[l].attr)}"`)}),r):s}function Rh(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function Dh(n,e,t){var s;const i=e.skippedSegments,r=Math.max(n.startSN,e.startSN)-e.startSN,a=(n.fragmentHint?1:0)+(i?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,o=e.startSN-n.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=(s=n.fragmentHint)!=null&&s.duration?n.fragments.concat(n.fragmentHint):n.fragments;for(let h=r;h<=a;h++){const u=c[o+h];let d=l[h];if(i&&!d&&u&&(d=e.fragments[h]=u),u&&d){t(u,d,h,l);const f=u.relurl,g=d.relurl;if(f&&_h(f,g)){e.playlistParsingError=ga(`media sequence mismatch ${d.sn}:`,n,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=ga(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,n,e,u,d);return}}}}function ga(n,e,t,s,i){return new Error(`${n} ${i.url}
|
|
161
|
+
Playlist starting @${e.startSN}
|
|
162
|
+
${e.m3u8}
|
|
380
163
|
|
|
381
|
-
|
|
164
|
+
Playlist starting @${t.startSN}
|
|
165
|
+
${t.m3u8}`)}function ma(n,e,t=!0,s){const i=e.startSN+e.skippedSegments-n.startSN,r=n.fragments,a=i>=0;let o=0;if(a&&i<r.length)o=r[i].start,s?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===n.endSN+1)o=n.fragmentEnd,s?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=n.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=n.fragmentStart,s?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Ph(e,o),o}function Ph(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function pa(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r>0&&r<t&&(t=r)}}else t/=2;return Math.round(t)}function Aa(n,e,t){var s;if(!n)return null;let i=n.fragments[e-n.startSN];return i||(i=n.fragmentHint,((s=i)==null?void 0:s.sn)===e)?i:t&&e<n.startSN&&t.sn===e?t:null}function Ia(n,e,t){return n?Ca(n.partList,e,t):null}function Ca(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function ya(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function _h(n,e){return n!==e&&e?Ea(n)!==Ea(e):!1}function Ea(n){return n.replace(/\?[^?]*$/,"")}function is(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function kh(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function va(n,e){const t=n.start+e;n.setStart(t)}function Ta(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)va(t[s],n);e.fragmentHint&&va(e.fragmentHint,n),e.alignedSliding=!0}function Fs(n,e,t){n&&(wh(e,n,t),e.alignedSliding||Mh(e,n,t),!e.alignedSliding&&!e.skippedSegments&&ma(n,e,!1,t))}function wh(n,e,t){if(!kh(e,n))return;const s=Math.min(e.endCC,n.endCC),i=is(e.fragments,s),r=is(n.fragments,s);if(!i||!r)return;const a=i.start-r.start;t.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),Ta(a,n)}function Mh(n,e,t){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const s=n.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,a;const o=Math.min(e.endCC,n.endCC);e.startCC<o&&n.startCC<o&&(r=is(i,o),a=is(s,o)),(!r||!a)&&(r=i[Math.floor(i.length/2)]||i.filter(d=>!!d)[0],a=is(s,r.cc)||s[Math.floor(s.length/2)]);const l=r.programDateTime,c=a.programDateTime;if(!l||!c)return;const h=(c-l)/1e3;if(Math.abs(h)>Math.max(60,n.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${n.totalduration})`);return}const u=h-(a.start-r.start);t.log(`Aligning playlists using PDT (diff: ${u})`),Ta(u,n)}function he(n,e,t){ce(n,e,t),n.addEventListener(e,t)}function ce(n,e,t){n.removeEventListener(e,t)}function Ns(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}const D={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Ui extends Hn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=D.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,u=l?l.currentTime:0,d=X.bufferInfo(c||l,u,a.maxBufferHole),f=d.len;if(this.log(`Media seeking to ${u}, state: ${h}, ${f?"in":"out of"} buffer`),this.state===D.ENDED)this.resetLoadingState();else if(o){const m=a.maxFragLookUpTolerance,A=o.start-m,I=o.start+o.duration+m;if(!f||I<d.start||A>d.end){const y=u<A,C=u>I;(y||C)&&(o.loader&&(C||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${y?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){const A=Math.max(d.end,u),I=this.shouldLoadParts(this.getLevelDetails(),A);I&&(this.log(`LL-Part loading ON after seeking to ${u} with buffer @${A}`),this.loadingParts=I)}}const g=!X.isBuffered(l,u);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),f<1&&this.state===D.IDLE&&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 Gn(e.config),this.initFragmentLoader=new Gn(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ri(e.config)}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===D.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=D.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){const s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=X.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const h=l[l.length-1];return X.isBuffered(this.media,h.start+h.duration/2)}const c=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(c.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;he(s,"seeking",this.onMediaSeeking),he(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===D.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ce(i,"seeking",this.onMediaSeeking),ce(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=D.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}const o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} chunk: ${o}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===D.FRAG_LOADING||!this.fragCurrent&&a===D.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=D.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===D.STOPPED||this.state===D.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===pe.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===pe.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){const i=t.getPartialFragment(s.end);i&&(t.removeFragment(i),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(p.BUFFER_FLUSHING,i)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(s=>{var i;const r=s.frag;if(!this.levels||!li(r,(i=this.fragCurrent)==null?void 0:i.initSegment))throw new at({type:W.NETWORK_ERROR,details:b.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return s}).then(s=>{const{frag:i,payload:r}=s,a=i.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&Bt(a.method)){const o=self.performance.now(),{decryptRange:l}=_s(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,ki(a.method),l).catch(c=>{throw t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:i}),this.fragmentLoader.abort(),c}).then(c=>{const h=self.performance.now();return t.trigger(p.FRAG_DECRYPTED,{frag:i,part:null,payload:c,stats:{tstart:o,tdecrypt:h}}),s.payload=c,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;if(!this.bitrateTest&&Ie(e)&&t&&!t.data){var s;return(t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(r=>{throw this.state===D.STOPPED||this.state===D.ERROR||("data"in r&&(r.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(r)),this.resetFragmentLoading(e)),r})}}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!li(e,t)}fragBufferedComplete(e,t){const s=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:${s?Ns(X.getBuffered(s)):"(detached)"})`),Ie(e)){var i;if(e.type!==H.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=D.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(t||this.fragmentTracker.getState(e)!==pe.PARTIAL)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,e.stats.retry=0)}this.state=D.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const s=e.frag,{part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),{decryptRange:o}=_s(s,i),l=new Di(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){var i;let r=null;return e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=D.KEY_LOADING,r=this.keyLoader.load(e,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(p.KEY_LOADED,a),this.state===D.KEY_LOADING&&(this.state=D.IDLE),a}),this.hls.trigger(p.KEY_LOADING,{frag:e})):e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),r}_doFragLoad(e,t,s=null,i){this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const a=this.fragPrevious;if(!Ht(e,a)){const f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=f)}if(s=Math.max(e.start,s||0),this.loadingParts){const f=r.partList;if(f&&i){s>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const g=this.getNextPart(f,e,s);if(g>-1){const m=f[g];if(e=this.fragCurrent=m.fragment,!Ht(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);const A=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${s}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=D.FRAG_LOADING;let I;const y=this.loadInitSegmentIfNeeded(e);if(A||y){const C=!!A;I=Promise.all([A,y]).then(([E])=>C&&(!E||this.fragContextChanged(E.frag))?null:this.doFragPartsLoad(e,m,t,i)).catch(E=>this.handleFragLoadError(E))}else I=this.doFragPartsLoad(e,m,t,i).catch(C=>this.handleFragLoadError(C));return this.hls.trigger(p.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):I}else if(!e.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${e.sn} loaded parts: ${(o=r.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(e),c=this.loadKeyFor(e,r,l);if(this.fragContextChanged(e)){var h;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(h=this.fragCurrent)==null?void 0:h.relurl}`),l?.catch(()=>null),c?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=D.FRAG_LOADING;const u=this.config.progressive&&e.type!==H.SUBTITLE;let d;return u&&c?d=c.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,l)).catch(f=>this.handleFragLoadError(f)):d=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,u?i:void 0,u?l:void 0),c,l]).then(([f])=>(!u&&i&&i(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([d,l]).then(([f])=>f)}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const l=[],c=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(p.FRAG_LOADED,d);const g=Ia(s.details,e.sn,u.index+1)||Ca(c,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===b.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==D.PARSING){!this.fragCurrent&&this.state!==D.STOPPED&&this.state!==D.ERROR&&(this.state=D.IDLE);return}const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=c),this.updateLevelTiming(s,i,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;const i=e.partList[0],r=i.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=r&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[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 o=t[i],l=o.details,c=a>-1?Ia(l,r,a):null,h=c?c.fragment:Aa(l,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:c,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==D.PARSING)return;Ie(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:a,data2:o}=e;let l=a;if(o&&(l=Ye(a,o)),!l.length)return;const c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:l};if(this.hls.trigger(p.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=X.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.playhead,a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){const r=X.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,i);return X.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){const i=e.nextStart;if(i&&s.start>i){const r=e.buffered;if(r){let a=e.len;const o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<s.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t/2),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;l=this.getInitialLiveFragment(t);const d=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((c=l)==null?void 0:c.start)||0;let A,I;if(f!==-1&&f>=a?(A=f,I=f===d?"config":"next load start"):g?(A=g,I="live edge"):(A=e,I="buffer pos"),A<m&&(A=m,I="live frag start"),A<a&&(A=a,I="playlist start"),this.startPosition!=A||this.nextLoadPosition!=A){const C=t.live&&!this.filterReplacedPrimary(l,t)?-1:A;this.log(`Setting startPosition to ${C} next load ${A} ${f===-1?"":`(from ${d}) `}based on ${I}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=C,this.nextLoadPosition=A}}}else e<=a&&(l=s[0]);if(!l){const u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(l,t);return!h&&l&&(h=Fn(t,l.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const s=this.fragmentTracker.getState(e);return!!(s===pe.OK||s===pe.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Bs(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Bs(this.config)&&("type"in e?e:e.fragment).type!==H.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const r=i.event;if(r){if(!r.appendInPlace&&(Math.abs(e.start-i.start)>1||i.start===0))return null}else if(e.end<=i.start&&t?.live===!1||e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}if(Sa(e,s?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let l=0,c=e.length;l<c;l++){const h=e[l];if(a=a&&!h.independent,i>-1&&s<h.start)break;const u=h.loaded||h.gap;u?i=-1:(r||(h.independent||a)&&h.fragment===t)&&(i=l),r=u&&!h.gap}const o=e[i];return o&&o.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(i=Zc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=On(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&l);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),r&&this.fragmentTracker.getState(r)===pe.NOT_LOADED&&(r=null);let d;if(e<t){var f;const m=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=Ft(r,a,e,m)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,m=this.fragmentTracker.getState(d);if((m===pe.OK||m===pe.PARTIAL&&d.gap)&&(r=d),Ht(d,r)&&(!u||h[0].fragment.sn>d.sn||!s.live)){const A=a[g+1];d.sn<o&&this.fragmentTracker.getState(A)!==pe.OK?d=A:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&B(r);if(a||!o&&!r){Fs(s,e,this);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;if(a!==null&&B(a))s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){const o=this.hls.liveSyncPosition;s=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;const s=(t=this.media)==null?void 0:t.currentTime;return B(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==H.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ie(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==D.FRAG_LOADING_WAITING_RETRY)&&(this.state=D.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const y=this.getCurrentContext(t.chunkMeta);y&&(t.frag=y.frag)}const{frag:s,part:i}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}const a=t.details===b.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);const o=t.errorAction;if(!o){this.state=D.ERROR;return}const{action:l,flags:c,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&l===be.RetryRequest,g=d&&!o.resolved&&c&xe.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,A=m?.live;if(!f&&g&&Ie(s)&&A&&s.sn<m.endSN&&!Vr(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var I;const y=Wt((I=t.response)==null?void 0:I.code),C=ci(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+C,this.state=D.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${C}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&l!==be.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===be.SendAlternateToPenaltyBox?this.state=D.WAITING_LEVEL:this.state=D.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Wt(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=D.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===D.PARSING||this.state===D.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const a=!r;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===H.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==D.STOPPED&&(this.state=D.IDLE)}afterBufferFlushed(e,t){if(!e)return;const s=X.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===D.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==D.STOPPED&&(this.state=D.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((u,d)=>{const f=e.elementaryStreams[d];if(f){const g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),u||!1;const m=i.partial?0:fa(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:r,level:s,drift:m,type:d,frag:e,start:f.startPTS,end:f.endPTS}),!0}return u},!1)){var o,l,c,h;const u=((o=this.transmuxer)==null?void 0:o.error)===null,d=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((c=(h=this.levels)==null?void 0:h.length)!=null?c:0)>1;if((s.fragmentError===0||u&&(s.fragmentError<2||e.endList)||d&&f)&&this.treatAsGap(e,s),u){const g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=D.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN}-${(r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;const s=(t=e.loader)==null?void 0:t.stats;if(!s)return!1;const i=s.loading.first>0,a=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let s=0;const{hls:i,media:r,config:a,levels:o,playlistType:l}=this,c=this.getLevelDetails();if(r&&!r.paused&&o){var h;const f=l===H.AUDIO?Sn(e.audioCodec,128e3):e.maxBitrate,g=1+i.ttfbEstimate/1e3,m=i.bandwidthEstimate*a.abrBandWidthUpFactor,A=c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||((h=this.fragCurrent)==null?void 0:h.duration)||6;s=g+f*A/m,e.details||(s+=g)}const u=this.playhead,d=!(c!=null&&c.live)||t.end-u>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:d}}scheduleTrackSwitch(e,t,s){const{media:i,playlistType:r}=this;if(!i||!e)return;const a=s?this.getBufferedFrag(this.playhead+t):null;if(a){const l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();const c=l.maxStartPTS?l.maxStartPTS:l.start,h=l.duration,u=Math.max(a.end,c+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>u)return;const f=r===H.MAIN?null:"audio";this.flushMainBuffer(u,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const i=t===H.AUDIO;this.flushMainBuffer(0,s.start-(i?0:1),i?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case D.KEY_LOADING:case D.FRAG_LOADING:case D.FRAG_LOADING_WAITING_RETRY:case D.PARSING:case D.PARSED:this.state=D.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(X.isBuffered(e,s)?t=this.getAppendedFrag(s):X.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!Ht(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:s,config:i,playlistType:r}=this;if(t!=null&&t.readyState&&e&&s&&i){const a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,r);if(!o)return;const l=r===H.AUDIO?s.nextAudioTrack:s.nextLoadLevel,c=e[l],{fetchdelay:h,okToFlushForwardBuffer:u}=this.calculateOptimalSwitchPoint(c,o);this.scheduleTrackSwitch(o,h,u)}this.tickImmediate()}}function Sa(n,e,t){if(e)for(let s=e.length;s--;){const i=e[s].interstitial,r=i.startTime,a=Math.min(r+i.duration,i.resumeTime);if(i.appendInPlace&&(n.start>=r&&n.end<=a||t>n.start&&n.end>r&&n.start<a))return!0}return!1}function Bs(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class xa{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Oh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Oh(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}var $i={exports:{}},ba;function Fh(){return ba||(ba=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||l,d),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,g){var m=t?t+c:c;if(!this._events[m])return!1;var A=this._events[m],I=arguments.length,y,C;if(A.fn){switch(A.once&&this.removeListener(c,A.fn,void 0,!0),I){case 1:return A.fn.call(A.context),!0;case 2:return A.fn.call(A.context,h),!0;case 3:return A.fn.call(A.context,h,u),!0;case 4:return A.fn.call(A.context,h,u,d),!0;case 5:return A.fn.call(A.context,h,u,d,f),!0;case 6:return A.fn.call(A.context,h,u,d,f,g),!0}for(C=1,y=new Array(I-1);C<I;C++)y[C-1]=arguments[C];A.fn.apply(A.context,y)}else{var E=A.length,v;for(C=0;C<E;C++)switch(A[C].once&&this.removeListener(c,A[C].fn,void 0,!0),I){case 1:A[C].fn.call(A[C].context);break;case 2:A[C].fn.call(A[C].context,h);break;case 3:A[C].fn.call(A[C].context,h,u);break;case 4:A[C].fn.call(A[C].context,h,u,d);break;default:if(!y)for(v=1,y=new Array(I-1);v<I;v++)y[v-1]=arguments[v];A[C].fn.apply(A[C].context,y)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var m=0,A=[],I=g.length;m<I;m++)(g[m].fn!==h||d&&!g[m].once||u&&g[m].context!==u)&&A.push(g[m]);A.length?this._events[f]=A.length===1?A[0]:A:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})($i)),$i.exports}var Nh=Fh(),Gi=Ll(Nh);const rs="1.7.3",$t={};function Bh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Uh(){const n=$t[rs];if(n)return n.clientCount++,n;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return $t[rs]=i,i}function $h(n){const e=$t[n];if(e)return e.clientCount++,e;const t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return $t[n]=i,i}function Gh(n){const e=$t[n||rs];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete $t[n||rs],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Vh(n,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const A=new Error(`invalid ADTS sampling index:${a}`);n.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!0,error:A,reason:A.message});return}const o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,c=i[a];let h=a;(o===5||o===29)&&(h-=3);let u;const d=(h&14)>>1,f=(h&1)<<7|l<<3;let g=0;if(o===1&&a>=6){g=5;const A=a-3;u=[g<<3|d,f|(A&14)>>1,(A&1)<<7|8,0]}else u=[o<<3|d,f];const m="mp4a.40."+(g||o);return le.log(`manifest codec:${s}, parsed codec:${m}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:l,codec:m,parsedCodec:m,manifestCodec:s}}function La(n,e){return n[e]===255&&(n[e+1]&246)===240}function Ra(n,e){return n[e+1]&1?7:9}function Vi(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Kh(n,e){return e+5<n.length}function Us(n,e){return e+1<n.length&&La(n,e)}function Hh(n,e){return Kh(n,e)&&La(n,e)&&Vi(n,e)<=n.length-e}function Yh(n,e){if(Us(n,e)){const t=Ra(n,e);if(e+t>=n.length)return!1;const s=Vi(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Us(n,i)}return!1}function Da(n,e,t,s,i){if(!n.samplerate){const r=Vh(e,t,s,i);if(!r)return;ue(n,r)}}function Pa(n){return 1024*9e4/n}function Wh(n,e){const t=Ra(n,e);if(e+t<=n.length){const s=Vi(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function _a(n,e,t,s,i){const r=Pa(n.samplerate),a=s+i*r,o=Wh(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const m={unit:l,pts:a};return g||n.samples.push(m),{sample:m,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let _e=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function lt(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ki{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,s,i){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,s){}demux(e,t){this.cachedData&&(e=Ye(this.cachedData,e),this.cachedData=null);let s=jt(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,l=s?mi(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&B(l))&&(this.basePTS=jh(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:_e.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else Wl(e,i)?(s=jt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:_e.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const h=e.slice(r);this.cachedData?this.cachedData=Ye(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:lt(),id3Track:o,textTrack:lt()}}demuxSampleAes(e,t,s){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:lt(),id3Track:this._id3Track,textTrack:lt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const jh=(n,e,t)=>{if(B(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},zh=[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],qh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Zh=[0,1,1,4];function ka(n,e,t,s,i){if(t+24>e.length)return;const r=wa(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function wa(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-s:s===3?3:4,c=zh[l*14+i-1]*1e3,u=qh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Xh[t][s],g=Zh[s],m=f*8*g,A=Math.floor(f*c/u+a)*g,I=Xt();return I&&I<=87&&s===2&&c>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:A,samplesPerFrame:m}}}function Hi(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function Ma(n,e){return e+1<n.length&&Hi(n,e)}function Qh(n,e){return Hi(n,e)&&4<=n.length-e}function Oa(n,e){if(e+1<n.length&&Hi(n,e)){const s=wa(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||Ma(n,r)}return!1}class Fa{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ri(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Et.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=gn(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}class Jh extends Ki{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=jt(e,0);let i=s?.length||0;if(Oa(e,i))return!1;for(let r=e.length;i<r;i++)if(Yh(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Hh(e,t)}appendFrame(e,t,s){Da(e,this.observer,t,s,e.manifestCodec);const i=_a(e,t,s,this.basePTS,this.frameIndex);if(i?.missing===0)return i}demuxSampleAes(e,t,s){const i=this.demux(e,s),r=this.sampleAes=new Fa(this.observer,this.config,t);return new Promise(a=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{a(i)})})}}const Na=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class eu extends Ki{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=Ba(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=jt(e,0);if(!t)return!1;const s=t.length;if(e[s]===11&&e[s+1]===119&&mi(t)!==void 0){if(Na(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Ba(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][u]+f,A=e[t+5]>>3,I=e[t+5]&7,y=new Uint8Array([r<<6|A<<1|I>>2,(I&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),C=1536/o*9e4,E=s+i*C,v=e.subarray(t,t+h);return n.config=y,n.channelCount=m,n.samplerate=o,n.samples.push({unit:v,pts:E}),h}class tu extends Ki{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=jt(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&mi(t)!==void 0&&Na(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Oa(e,s))return le.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Qh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ka(e,t,s,this.basePTS,this.frameIndex)}}const su=/\/emsg[-/]ID3/i;class iu{constructor(e,t,s,i=le){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=i}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=lt("video",1),a=this.audioTrack=lt("audio",1),o=this.txtTrack=lt("text",1);if(this.id3Track=lt("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=this.initData=ln(e);if(l.video){const{id:c,timescale:h,codec:u,supplemental:d}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=tn.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return oc(e,"moof")}demux(e,t,s){this.timeOffset=t;let i=e;const r=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Ye(this.remainderData,e));const c=Ac(i);this.remainderData=c.remainder,r.samples=c.valid||new Uint8Array}else r.samples=i;const o=this.extractID3Track(r,t),l=this.parseFragment(r,a,t,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const a=this.extractID3Track(i,this.timeOffset),o=this.parseFragment(i,r,s,t);return{videoTrack:i,audioTrack:lt(),id3Track:a,textTrack:lt(),initData:this.initData,sampleData:o}}parseFragment(e,t,s,i){const r=this.initData;if(r&&i){const{samples:a,sampleData:o}=pc(s,e,r,this.logger,i.iframe);return t.samples=a,o}t.samples=Ic(s,e)}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=J(e.samples,["emsg"]);i&&i.forEach(r=>{const a=Cc(r);if(su.test(a.schemeIdUri)){const o=Ua(a,t);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:_e.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||_e.misbklv;if(a.schemeIdUri.startsWith(o)){const l=Ua(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:_e.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,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,this.initData=void 0}}function Ua(n,e){return B(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}const ru=1,nu=2,ns=-1;class $a{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;if(i===0)return[];const r=e.naluState||0,a=r===ns?0:r,o=[];let l=0,c=0,h=-1,u=0;for(r===ns&&(h=0,u=this.getNALuType(t,0),c=1);c<i;){const d=t.indexOf(ru,c);if(d===-1)break;c=d+1;let f=d;for(;f>0&&t[f-1]===0;)f--;if(!(d-f+(f===0?a:0)<nu)){if(h>=0)o.push({data:t.subarray(h,f),type:u});else{const m=this.getLastNalUnit(e.samples);m&&(f>0?m.data=Ye(m.data,t.subarray(0,f)):a>0&&(m.data=m.data.subarray(0,m.data.byteLength-a)),m.state=0)}if(c<i)h=c,u=this.getNALuType(t,c);else{l=ns,h=-1;break}}}if(l!==ns){let d=i;for(;d>0&&t[d-1]===0;)d--;l=i-d+(d===0?a:0)}if(h>=0)o.push({data:t.subarray(h),type:u,state:l});else if(o.length===0&&l!==ns){const d=this.getLastNalUnit(e.samples);d&&(d.data=Ye(d.data,t),d.state=l)}return e.naluState=l,o}}class as{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,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&le.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class au extends $a{parsePES(e,t,s,i,r){const a=r.iframe,o=this.parseNALu(e,s.data,i);let l=this.VideoSample,c,h=!1;s.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(u=>{var d,f;switch(u.type){case 1:{if(a)break;let I=!1;c=!0;const y=u.data;if(h&&y.length>4){const C=this.readSliceType(y);(C===2||C===4||C===7||C===9)&&(I=!0)}if(I){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=I;break}case 5:c=!0,(d=l)!=null&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;c=!0,qt(u.data,1,s.pts,t.samples);break}case 7:{var m,A;c=!0,h=!0;const I=u.data,y=this.readSPS(I);if(!e.sps||e.width!==y.width||e.height!==y.height||((m=e.pixelRatio)==null?void 0:m[0])!==y.pixelRatio[0]||((A=e.pixelRatio)==null?void 0:A[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[I];const C=I.subarray(1,4);let E="avc1.";for(let v=0;v<3;v++){let T=C[v].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break}case 8:c=!0,e.pps=[u.data];break;case 9:c=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:c=!0;break;default:c=!1;break}l&&c&&l.units.push(u)}),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new as(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new as(e);let s=0,i=0,r=0,a=0,o,l,c;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),A=t.skipUEG.bind(t),I=this.skipScalingList.bind(this);h();const y=h();if(u(5),g(3),h(),A(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const L=d();if(L===3&&g(1),A(),A(),g(1),f())for(l=L!==3?8:12,c=0;c<l;c++)f()&&(c<6?I(16,t):I(64,t))}A();const C=d();if(C===0)d();else if(C===1)for(g(1),m(),m(),o=d(),c=0;c<o;c++)m();A(),g(1);const E=d(),v=d(),T=u(1);T===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let S=[1,1];if(f()&&f())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()];break}}return{width:Math.ceil((E+1)*16-s*2-i*2),height:(2-T)*(v+1)*16-(T?2:4)*(r+a),pixelRatio:S}}}class ou extends $a{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,l=!1;s.data=null;const c=h=>(a=this.VideoSample=this.createVideoSample(h,s.pts,s.dts),a);r.forEach((h,u)=>{var d,f;if(this.startsNewAccessUnit(a,e,h,u)){this.pushAccessUnit(a,e);const m=h.type>=16&&h.type<=23;a=c(m),l=!1}switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=c(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,qt(h.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ue(e.params,this.readVPS(h.data)),this.initVPS=h.data),e.vps=[h.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],h.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const m=this.readSPS(h.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const A in m.params)e.params[A]=m.params[A]}this.pushParameterSet(e.sps,h.data,e.vps),a||(a=c(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const m=this.readPPS(h.data);for(const A in m)e.params[A]=m[A]}this.pushParameterSet(e.pps,h.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=c(!1));break;default:o=!1;break}a&&o&&a.units.push(h)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,i){if(!e)return!1;if(!t.audFound&&i===0)return!0;if(!e.frame)return!1;const{type:r,data:a}=s;return r>=32&&r<=35||r===39||r>=41&&r<=44||r>=48&&r<=55?!0:r<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new as(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new as(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),A=t.readUByte(),I=t.readUByte(),y=[],C=[];for(let j=0;j<s;j++)y.push(t.readBoolean()),C.push(t.readBoolean());if(s>0)for(let j=s;j<8;j++)t.readBits(2);for(let j=0;j<s;j++)y[j]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),C[j]&&t.readUByte();t.readUEG();const E=t.readUEG();E==3&&t.skipBits(1);const v=t.readUEG(),T=t.readUEG(),S=t.readBoolean();let L=0,R=0,x=0,P=0;S&&(L+=t.readUEG(),R+=t.readUEG(),x+=t.readUEG(),P+=t.readUEG());const _=t.readUEG(),F=t.readUEG(),V=t.readUEG(),U=t.readBoolean();for(let j=U?0:s;j<=s;j++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let re=0;re<4;re++)for(let ae=0;ae<(re===3?2:6);ae++)if(!t.readBoolean())t.readUEG();else{const Ce=Math.min(64,1<<4+(re<<1));re>1&&t.readEG();for(let we=0;we<Ce;we++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const w=t.readUEG();let N=0;for(let j=0;j<w;j++){let re=!1;if(j!==0&&(re=t.readBoolean()),re){j===w&&t.readUEG(),t.readBoolean(),t.readUEG();let ae=0;for(let Se=0;Se<=N;Se++){const Ce=t.readBoolean();let we=!1;Ce||(we=t.readBoolean()),(Ce||we)&&ae++}N=ae}else{const ae=t.readUEG(),Se=t.readUEG();N=ae+Se;for(let Ce=0;Ce<ae;Ce++)t.readUEG(),t.readBoolean();for(let Ce=0;Ce<Se;Ce++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const j=t.readUEG();for(let re=0;re<j;re++){for(let ae=0;ae<V+4;ae++)t.readBits(1);t.readBits(1)}}let O=0,G=1,ee=1,q=!0,ie=1,Z=0;t.readBoolean(),t.readBoolean();let ne=!1;if(t.readBoolean()){if(t.readBoolean()){const et=t.readUByte(),_t=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],De=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];et>0&&et<16?(G=_t[et-1],ee=De[et-1]):et===255&&(G=t.readBits(16),ee=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ne=t.readBoolean(),ne&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const De=t.readBoolean(),Me=t.readBoolean();let je=!1;(De||Me)&&(je=t.readBoolean(),je&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),je&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Ke=0;Ke<=s;Ke++){q=t.readBoolean();const Pe=q||t.readBoolean();let xt=!1;Pe?t.readEG():xt=t.readBoolean();const At=xt?1:t.readUEG()+1;if(De)for(let tt=0;tt<At;tt++)t.readUEG(),t.readUEG(),je&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Me)for(let tt=0;tt<At;tt++)t.readUEG(),t.readUEG(),je&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),O=t.readUEG())}let oe=v,Te=T;if(S){let j=1,re=1;E===1?j=re=2:E==2&&(j=2),oe=v-j*R-j*L,Te=T-re*P-re*x}const Be=i?["A","B","C"][i]:"",pt=o<<24|l<<16|c<<8|h;let ge=0;for(let j=0;j<32;j++)ge=(ge|(pt>>j&1)<<31-j)>>>0;let We=ge.toString(16);return a===1&&We==="2"&&(We="6"),{codecString:`hvc1.${Be}${a}.${We}.${r?"H":"L"}${I}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[u,d,f,g,m,A],general_level_idc:I,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:F,min_spatial_segmentation_idc:O,chroma_format_idc:E,frame_rate:{fixed:q,fps:Z/ie}},width:oe,height:Te,pixelRatio:[G,ee]}}readPPS(e){const t=new as(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(),r=t.readBoolean();let a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return ze(e).substring(3)===ze(t).substring(3)}}const ve=188;class gt{constructor(e,t,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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=gt.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(ve*5,t-ve)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<t;l+=ve)if(e[l]===71&&(t-l===ve||e[l+ve]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+ve*99,e.length-ve)+1)),r||(r=$s(e,l)===0),r&&o>1&&(a===0&&o>2||l+ve>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:tn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=gt.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new hu(this.logger):null,this._audioTrack=gt.createTrack("audio",i),this._id3Track=gt.createTrack("id3"),this._txtTrack=gt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,e&&this.demux(e,0,a,r?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s,i=!1,r=!1){i||(this.sampleAes=null);let a;const o=this._videoTrack,l=this.videoIntegrityChecker,c=this._audioTrack,h=this._id3Track,u=this._txtTrack,d=s.iframe;let f=o.pid,g=o.pesData,m=c.pid,A=h.pid,I=this._klvPid,y=c.pesData,C=h.pesData,E=null,v=null,T=this.pmtParsed,S=this._pmtId,L=e.length;if(this.remainderData&&(e=Ye(this.remainderData,e),L=e.length,this.remainderData=null),L<ve&&!r)return this.remainderData=e,{audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};const R=Math.max(0,gt.syncOffset(e));L-=(L-R)%ve,L<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,L,e.buffer.byteLength-L));let x=0;for(let _=R;_<L;_+=ve)if(e[_]===71){const F=!!(e[_+1]&64),V=$s(e,_),U=(e[_+3]&48)>>4;let k;if(U>1){if(k=_+5+e[_+4],k===_+ve)continue}else k=_+4;switch(V){case f:F&&(g&&!(l!=null&&l.isCorrupted)&&(a=Rt(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,u,a,!1,s)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(e.subarray(_)),g&&(g.data.push(e.subarray(k,_+ve)),g.size+=_+ve-k);break;case m:if(d)break;if(F){if(y&&(a=Rt(y,this.logger)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,a,s);break;case"mp3":this.parseMPEGPES(c,a);break;case"ac3":this.parseAC3PES(c,a);break}y={data:[],size:0}}y&&(y.data.push(e.subarray(k,_+ve)),y.size+=_+ve-k);break;case A:if(d)break;F&&(C&&(a=Rt(C,this.logger))&&this.parseID3PES(h,a),C={data:[],size:0}),C&&(C.data.push(e.subarray(k,_+ve)),C.size+=_+ve-k);break;case I:if(d)break;F&&(E&&(a=Rt(E,this.logger))&&this.parseKlvPES(h,a),E={data:[],size:0}),E&&(E.data.push(e.subarray(k,_+ve)),E.size+=_+ve-k);break;case 0:F&&(k+=e[k]+1),S=this._pmtId=lu(e,k);break;case S:{F&&(k+=e[k]+1);const M=cu(e,k,this.typeSupported,i,this.observer,this.logger,this.config,s);f=M.videoPid,f>0&&(o.pid=f,o.segmentCodec=M.segmentVideoCodec),m=M.audioPid,m>0&&(c.pid=m,c.segmentCodec=M.segmentAudioCodec),A=M.id3Pid,A>0&&(h.pid=A),I=M.klvPid,I>0&&(this._klvPid=I),v!==null&&!T&&(this.logger.warn(`MPEG-TS PMT found at ${_} after unknown PID '${v}'. Backtracking to sync byte @${R} to parse all TS packets.`),v=null,_=R-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=V;break}}else x++;x>0&&Yi(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=g,c.pesData=y,h.pesData=C;const P={audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};return r&&this.extractRemainingSamples(P,s),P}flush(e,t){const{remainderData:s}=this;this.remainderData=null;let i;return s?i=this.demux(s,0,t,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:a}=e,o=i.pesData,l=s.pesData,c=r.pesData,h=this.videoIntegrityChecker;let u;if(o&&!(h!=null&&h.isCorrupted)&&(u=Rt(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,a,u,!0,t),i.pesData=null)):i.pesData=o,l&&(u=Rt(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,u,t);break;case"mp3":this.parseMPEGPES(s,u);break;case"ac3":this.parseAC3PES(s,u);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;c&&(u=Rt(c,this.logger))?(this.parseID3PES(r,u),r.pesData=null):r.pesData=c}demuxSampleAes(e,t,s,i){const r=this.demux(e,s,i,!0,!this.config.progressive),a=this.sampleAes=new Fa(this.observer,this.config,t);return this.decrypt(r,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new au:e==="hevc"&&(this.videoParser=new ou))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){let i=0;const r=this.aacOverFlow;let a=t.data;if(r){this.aacOverFlow=null;const d=r.missing,f=r.sample.unit.byteLength;if(d===-1)a=Ye(r.sample.unit,a);else{const g=f-d;r.sample.unit.set(a.subarray(0,d),g),e.samples.push(r.sample),i=r.missing}}let o,l;for(o=i,l=a.length;o<l-1&&!Us(a,o);o++);if(o!==i){let d;const f=o<l-1;if(f?d=`AAC PES did not start with ADTS header,offset:${o}`:d="No ADTS header found in AAC PES",Yi(this.observer,new Error(d),s,f,this.logger),!f)return}Da(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(r){const d=Pa(e.samplerate);c=r.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,u;for(;o<l;)if(u=_a(e,a,o,c,h),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(h++;o<l-1&&!Us(a,o);o++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Ma(s,a)){const l=ka(e,s,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,l;for(;o<r&&(l=Ba(e,s,o,i,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ue({},t,{type:this._videoTrack?_e.emsg:_e.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;const i=(s=t.pts)!=null?s:t.dts;if(i===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const r=t.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<r.length;){var o;if(a+16>r.length)break;const l=a;if(a+=16,a>=r.length)break;const c=r[a];a+=1;let h=0;if(c&128){const g=c&127;if(g===0||g>4||a+g>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)h=h<<8|r[a+m];a+=g}else h=c;if(a+h>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const u=a+h,d=r.subarray(l,u),f={data:d,len:d.byteLength,pts:i,dts:(o=t.dts)!=null?o:i,type:_e.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=u}}}function $s(n,e){return((n[e+1]&31)<<8)+n[e+2]}function lu(n,e){return(n[e+10]&31)<<8|n[e+11]}function cu(n,e,t,s,i,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},c=(n[e+1]&15)<<8|n[e+2],h=e+3+c-4,u=(n[e+10]&15)<<8|n[e+11];for(e+=12+u;e<h;){const d=$s(n,e),f=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){Wi("ADTS AAC",r);break}case 15:l.audioPid===-1&&(l.audioPid=d);break;case 21:l.id3Pid===-1&&(l.id3Pid=d);break;case 219:if(!s){Wi("H.264",r);break}case 27:l.videoPid===-1&&(l.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="mp3");break;case 193:if(!s){Wi("AC-3",r);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(n[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=d,r.log(`KLV metadata PID found: ${d}`));break}const I=n[g+1]+2;g+=I,m-=I}}break;case 194:case 135:return Yi(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:l.videoPid===-1&&(l.videoPid=d,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=f+5}return l}function Yi(n,e,t,s,i){i.warn(`parsing error: ${e.message}`),n.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:t,error:e,reason:e.message})}function Wi(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Rt(n,e){let t=0,s,i,r,a,o;const l=n.data;if(!n||n.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ye(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;const h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let u=r+9;if(n.size<=u)return null;n.size-=u;const d=new Uint8Array(n.size);for(let f=0,g=l.length;f<g;f++){s=l[f];let m=s.byteLength;if(u)if(u>m){u-=m;continue}else s=s.subarray(u),m-=u,u=0;d.set(s,t),t+=m}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}class hu{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=$s(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}const s=(e[3]&48)>>4;if(s===0)return;const i=e[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=i;const a=(s&1)!=0;if((s&2)!=0&&e[4]!=0&&(e[5]&128)!=0||r<0)return;const c=a?r+1&15:r;if(i!==c){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${i}, Expected-CC=${c} Last-CC=${r}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class uu{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}var Gs;const du={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},ji=new Uint8Array([0,0,0,0,0,0,0,0]),fu=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),gu=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),mu=new Uint8Array([0,0,0,0,0,0,0,0]),os=new Uint8Array([0,0,0,0,0,0,0,1]),Ga=new Uint8Array([105,115,111,109]),pu=new Uint8Array([97,118,99,49]),Au=new Uint8Array([0,0,0,1]);class ${static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(ye(a,0,s),ye(a,4,e),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return $.box(Q.hdlr,du[e])}static mdat(e){return $.box(Q.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(st+1)),i=Math.floor(t%(st+1));return $.box(Q.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return $.box(Q.mdia,$.mdhd(e.timescale||0,e.duration||0),$.hdlr(e.type),$.minf(e))}static mfhd(e){return $.box(Q.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?$.box(Q.minf,$.box(Q.smhd,mu),$.DINF,$.stbl(e)):$.box(Q.minf,$.box(Q.vmhd,gu),$.DINF,$.stbl(e))}static moof(e,t,s){return $.box(Q.moof,$.mfhd(e),$.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=$.trak(e[t]);return $.box.apply(null,[Q.moov,$.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat($.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=$.trex(e[t]);return $.box.apply(null,[Q.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(st+1)),i=Math.floor(t%(st+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,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return $.box(Q.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return $.box(Q.sdtp,s)}static stbl(e){return $.box(Q.stbl,$.stsd(e),$.box(Q.stts,ji),$.box(Q.stsc,ji),$.box(Q.stsz,fu),$.box(Q.stco,ji))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=$.box(Q.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return $.box(Q.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,$.box(Q.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),$.box(Q.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return $.box(Q.mp4a,$.audioStsd(e),$.box(Q.esds,$.esds(e)))}static mp3(e){return $.box(Q[".mp3"],$.audioStsd(e))}static ac3(e){return $.box(Q["ac-3"],$.audioStsd(e),$.box(Q.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return $.box(Q.stsd,os,$.mp4a(e));if(t==="ac3"&&e.config)return $.box(Q.stsd,os,$.ac3(e));if(t==="mp3"&&e.codec==="mp3")return $.box(Q.stsd,os,$.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return $.box(Q.stsd,os,$.avc1(e));if(t==="hevc"&&e.vps)return $.box(Q.stsd,os,$.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(st+1)),o=Math.floor(s%(st+1));return $.box(Q.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=$.sdtp(e),i=e.id,r=Math.floor(t/(st+1)),a=Math.floor(t%(st+1));return $.box(Q.traf,$.box(Q.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),$.box(Q.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),$.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,$.box(Q.trak,$.tkhd(e),$.mdia(e))}static trex(e){const t=e.id;return $.box(Q.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)l=s[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return $.box(Q.trun,a)}static initSegment(e){const t=$.moov(e);return Ye($.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=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),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let m=0;m<s[g].length;m+=1)a+=2+s[g][m].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,s[g].length]),a),a+=3;for(let m=0;m<s[g].length;m+=1)o.set(new Uint8Array([s[g][m].length>>8,s[g][m].length&255]),a),a+=2,o.set(s[g][m],a),a+=s[g][m].length}const c=$.box(Q.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return $.box(Q.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,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,$.box(Q.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),$.box(Q.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}Gs=$,$.FTYP=Gs.box(Q.ftyp,Ga,Au,Ga,pu),$.DINF=Gs.box(Q.dinf,Gs.box(Q.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const Va=9e4;function zi(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function Iu(n,e,t=1,s=!1){return zi(n,e,1/t,s)}function ls(n,e=!1){return zi(n,1e3,1/Va,e)}function Cu(n,e=1){return zi(n,Va,1/e)}function Ka(n){const{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}const yu=10*1e3,Eu=1024,vu=1152,Tu=1536,qi=8589934592;function Ha(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1,paddingValue:0}}}class Vs extends Ue{constructor(e,t,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Ka(t)} > ${e&&Ka(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=Ge(o,s),l=o-r),l>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,l,c){let h,u,d,f,g,m,A=r,I=r;const C=!c.iframe&&e.pid>-1,E=t.pid>-1,v=t.samples.length,T=e.samples.length>0,S=o&&v>0||v>1;if((!C||T)&&(!E||S)||this.ISGenerated||o){if(this.ISGenerated){var R,x,P,_;const k=this.videoTrackConfig;(k&&(t.width!==k.width||t.height!==k.height||((R=t.pixelRatio)==null?void 0:R[0])!==((x=k.pixelRatio)==null?void 0:x[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((_=k.pixelRatio)==null?void 0:_[1]))||!k&&S||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,a));const F=this.isVideoContiguous;let V=-1,U;if(S&&(V=Su(t.samples),!F&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,V>0){this.warn(`Dropped ${V} out of ${v} video samples due to a missing keyframe`);const k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(V),t.dropped+=V,I+=(t.samples[0].pts-k)/t.inputTimeScale,U=I}else V===-1&&(this.warn(`No keyframe found out of ${v} video samples`),m=!1);if(this.ISGenerated){if(T&&S&&r){const k=this.getVideoStartPts(t.samples),w=(Ge(e.samples[0].pts,k)-k)/t.inputTimeScale;A+=Math.max(0,w),I+=Math.max(0,-w)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,A,this.isAudioContiguous,a,E||S||l===H.AUDIO?I:void 0,c),S){const k=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,a)),h=this.remuxVideo(t,I,F,k,c)}}else S&&(h=this.remuxVideo(t,I,F,0,c));h&&(h.firstKeyFrame=V,h.independent=V!==-1,h.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=Ya(s,r,this._initPTS,this._initDTS)),i.samples.length&&(f=Wa(i,r,this._initPTS))),{audio:u,video:h,initSegment:d,independent:m,text:f,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let a=Ge(e,r);if(a<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r;)a+=qi;return a-r}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS,h=!c||i;let u="audio/mp4",d,f,g,m=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):$.initSegment([e]),metadata:{channelCount:e.channelCount}},h){m=e.id,g=e.inputTimeScale;const A=this.computeInitPts(r[0].pts,g,s,"audio");(!c||g!==c.timescale||s===0&&A<c.baseTime)&&(d=f=A)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:$.initSegment([t]),metadata:{width:t.width,height:t.height}},h){m=t.id,g=t.inputTimeScale;const A=this.getVideoStartPts(a),I=Ge(a[0].dts,A),y=this.computeInitPts(I,g,s,"video"),C=this.computeInitPts(A,g,s,"video");(!c||g!==c.timescale||B(d)||s===0&&C<c.baseTime)&&(f=Math.min(f,y),d=Math.min(d,y))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&B(d)?(c&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):d=g=void 0,{tracks:l,initPTS:d,timescale:g,trackId:m}}remuxVideo(e,t,s,i,r){const a=e.inputTimeScale,o=e.samples,l=[],c=o.length,h=this._initPTS,u=h.baseTime*a/h.timescale;let d=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,A,I=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,C=!1;if(!s||d===null){const O=u+t*a,G=o[0].pts-Ge(o[0].dts,o[0].pts);Xt()&&d!==null&&Math.abs(O-G-(d+u))<15e3?s=!0:d=O-G-u}const E=d+u;for(let O=0;O<c;O++){const G=o[O];G.pts=Ge(G.pts,E),G.dts=Ge(G.dts,E),G.dts<o[O>0?O-1:O].dts&&(C=!0)}C&&o.sort(function(O,G){const ee=O.dts-G.dts,q=O.pts-G.pts;return ee||q}),m=o[0].dts,A=o[o.length-1].dts;const v=A-m,T=v?Math.round(v/(c-1)):g||e.inputTimeScale/30;if(s){const O=m-E,G=O>T,ee=O<-1;if((G||ee)&&(G?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ls(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ls(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||E>=o[0].pts||Xt())){m=E;const q=o[0].pts-O;if(G)o[0].dts=m,o[0].pts=q;else{let ie=!0;for(let Z=0;Z<o.length&&!(o[Z].dts>q&&ie);Z++){const ne=o[Z].pts;if(o[Z].dts-=O,o[Z].pts-=O,Z<o.length-1){const te=o[Z+1].pts,oe=o[Z].pts,Te=te<=oe,Be=te<=ne;ie=Te==Be}}}this.log(`Video: Initial PTS/DTS adjusted: ${ls(q,!0)}/${ls(m,!0)}, delta: ${ls(O,!0)} ms`)}}m=Math.max(0,m);let S=0,L=0,R=m;for(let O=0;O<c;O++){const G=o[O],ee=G.units,q=ee.length;let ie=0;for(let Z=0;Z<q;Z++)ie+=ee[Z].data.length;L+=ie,S+=q,G.length=ie,G.dts<R?(G.dts=R,R+=T/4|0||1):R=G.dts,I=Math.min(G.pts,I),y=Math.max(G.pts,y)}A=o[c-1].dts;const x=L+4*S+8;let P;try{P=new Uint8Array(x)}catch(O){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:O,bytes:x,reason:`fail allocating video mdat ${x}`});return}ye(P,0,x),ye(P,4,Q.mdat);let _=!1,F=Number.POSITIVE_INFINITY,V=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let O=0;O<c;O++){const G=o[O],ee=G.units;let q=0;for(let ne=0,te=ee.length;ne<te;ne++){const oe=ee[ne],Te=oe.data,Be=oe.data.byteLength;ye(P,f,Be),f+=4,P.set(Te,f),f+=Be,q+=4+Be}let ie;if(O<c-1)g=o[O+1].dts-G.dts,ie=o[O+1].pts-G.pts;else{const ne=this.config,te=O>0?G.dts-o[O-1].dts:T;if(ie=O>0?G.pts-o[O-1].pts:T,ne.stretchShortVideoTrack&&this.nextAudioTs!==null){const oe=Math.floor(ne.maxBufferHole*a),Te=(i?I+i*a:this.nextAudioTs+u)-G.pts;Te>oe?(g=Te-te,g<0?g=te:_=!0,this.log(`It is approximately ${Te/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=te}else g=te}let Z=Math.round(G.pts-G.dts);if(F=Math.min(F,g),U=Math.max(U,g),V=Math.min(V,ie),k=Math.max(k,ie),!s&&O===0&&Z>g){const ne=Math.round(Z/T)*T;ne-Z===1&&(this.log(`pad first CTS ${Z} -> ${ne} of sn: ${r.sn}`),Z=ne)}l.push(Ha(G.key,g,q,Z))}if(l.length){const O=Xt();if(O){if(O<70){const G=l[0].flags;G.dependsOn=2,G.isNonSync=0}}else if(xc()&&k-V<U-F&&T/U<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let G=m;for(let ee=0,q=l.length;ee<q;ee++){const ie=G+l[ee].duration,Z=G+l[ee].cts;if(ee<q-1){const ne=ie+l[ee+1].cts;l[ee].duration=ne-Z}else l[ee].duration=ee?l[ee-1].duration:T;l[ee].cts=0,G=ie}}}g=_||!g?T:g;const M=A+g;this.nextVideoTs=d=M-u,this.videoSampleDuration=g,this.isVideoContiguous=!0,r.iframe&&(l.length===1?(l[0].duration=g=r.duration*a,this.nextVideoTs=d=m+g-u):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));const Y={data1:$.moof(r.sn,m,ue(e,{samples:l})),data2:P,startPTS:(I-u)/a,endPTS:(y+g-u)/a,startDTS:(m-u)/a,endDTS:d/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return vu;case"ac3":return Tu;default:return Eu}}remuxAudio(e,t,s,i,r,a){const o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,c=o/l,h=this.getSamplesPerFrame(e),u=h*c,d=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=r!==void 0;let A=e.samples,I=f?0:8,y=this.nextAudioTs||-1;const C=d.baseTime*o/d.timescale,E=C+t*o;if(this.isAudioContiguous=s=s||A.length&&y>0&&(i&&Math.abs(E-(y+C))<9e3||Math.abs(Ge(A[0].pts,E)-(y+C))<20*u),A.forEach(function(M){M.pts=Ge(M.pts,E)}),!s||y<0){const M=A.length;if(A=A.filter(w=>w.pts>=0),M!==A.length&&this.warn(`Removed ${A.length-M} of ${M} samples (initPTS ${C} / ${o})`),!A.length)return;r===0?y=0:i&&!m?y=Math.max(0,E-C):y=A[0].pts-C}if(e.segmentCodec==="aac"){const M=this.config.maxAudioFramesDrift;for(let w=0,N=y+C;w<A.length;w++){const Y=A[w],O=Y.pts,G=O-N,ee=Math.abs(1e3*G/o);if(G<=-M*u&&m)w===0&&(this.warn(`Audio frame @ ${(O/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*G/o)} ms.`),this.nextAudioTs=y=O-C,N=O);else if(G>=M*u&&ee<yu&&m){let q=Math.round(G/u);for(N=O-q*u;N<0&&q&&u;)q--,N+=u;w===0&&(this.nextAudioTs=y=N-C),this.warn(`Injecting ${q} audio frames @ ${((N-C)/o).toFixed(3)}s due to ${Math.round(1e3*G/o)} ms gap.`);for(let ie=0;ie<q;ie++){let Z=uu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);Z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Z=Y.unit.subarray()),A.splice(w,0,{unit:Z,pts:N}),N+=u,w++}}Y.pts=N,N+=u}}let v=null,T=null,S,L=0,R=A.length;for(;R--;)L+=A[R].unit.byteLength;for(let M=0,w=A.length;M<w;M++){const N=A[M],Y=N.unit;let O=N.pts;if(T!==null){const ee=g[M-1];ee.duration=Math.round((O-T)/c)}else if(s&&e.segmentCodec==="aac"&&(O=y+C),v=O,L>0){L+=I;try{S=new Uint8Array(L)}catch(ee){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:ee,bytes:L,reason:`fail allocating audio mdat ${L}`});return}f||(ye(S,0,L),ye(S,4,Q.mdat))}else return;S&&S.set(Y,I);const G=Y.byteLength;I+=G,g.push(Ha(!0,h,G,0)),T=O}const x=g.length;if(!x)return;const P=g[g.length-1];y=T-C,this.nextAudioTs=y+c*P.duration;const _=f?new Uint8Array(0):$.moof(e.sequenceNumber++,v/c,ue({},e,{samples:g}));e.samples=[];const F=(v-C)/o,V=this.nextAudioTs/o,k={data1:_,data2:S,startPTS:F,endPTS:V,startDTS:F,endDTS:V,type:"audio",hasAudio:!0,hasVideo:!1,nb:x};return this.isAudioContiguous=!0,k}}function Ge(n,e){let t;if(e===null)return n;for(e<n?t=-qi:t=qi;Math.abs(n-e)>4294967296;)n+=t;return n}function Su(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Ya(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const l=n.samples[o];l.pts=Ge(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=Ge(l.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function Wa(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=Ge(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class xu extends Ue{constructor(e,t,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:o}=this.initData=s||ln(e);if(t)uc(e,t);else{const c=a||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}a&&(i=ja(a,de.AUDIO,this)),o&&(r=ja(o,de.VIDEO,this));const l={};a&&o?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,s,i,r,a,o,l,c,h,u){var d,f;let{initPTS:g,lastEndTime:m}=this;const A={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};B(m)||(m=this.lastEndTime=r||0);const I=t.samples;if(!I.length)return A;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,h));const C={initPTS:void 0,timescale:void 0,trackId:void 0};let E=this.initData;if((d=E)!=null&&d.length||(this.generateInitSegment(I),E=this.initData),!((f=E)!=null&&f.length))return this.warn("Failed to generate initSegment."),A;if(c.iframe&&E.audio&&E.video){var v;const j=(v=this.initTracks)==null||(v=v.audiovideo)==null?void 0:v.initSegment,re=j?nc(j):null;if(re){var T;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(re,this.decryptdata),(T=this.initData)!=null&&T.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(C.tracks=this.initTracks,A.initSegment=C,this.emitInitSegment=!1);const S=c.iframe,L=u&&(!S||u.includeSampleDetails)?u.tracks:mc(I,E,c,this,S),R=E.audio?L[E.audio.id]:null,x=E.video?L[E.video.id]:null,P=!!E.audio,_=!!E.video;let F="";P&&(F+="audio"),_&&(F+="video");const V=Ks(x,1/0),U=Ks(R,1/0),k=Ks(x,0,!0),M=Ks(R,0,!0);let w=r,N=0;x&&R&&E.audio&&(U>k||V>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${V}-${k} a: ${U}-${M}}`,x,R);const Y=!!R&&(!x||!g&&U<V||!!g&&g.trackId===E.audio.id),O=Y?R:x;if(!O)return this.log(`No media samples found in ${l} ${c.level} ${c.part===-1?"":`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${r}`),A;let G=I,ee,q;if(x&&x.sampleCount>=1&&E.video&&c.iframe){const{trun:j,start:re}=x,ae=j.length===1,Se=j.length?ae?j[0].samples:j[0].samples.concat(...j.slice(1).map(Ce=>Ce.samples)):[];if(Se.length){const Ce=j[0];let we=Ce;for(let Ke=j.length;Ke--;)if(j[Ke].samples.length){we=j[Ke];break}const et=we.lastSampleDurationOffset,{defaultSampleDurationOffset:_t}=Ce,De=Math.abs(c.duration-(k-V))>.05,Me=Se.length<x.sampleCount;if(!(De||Me||this.videoOnlyRemux||!ae))N=k-V;else{const Ke=Me?we.sampleOffset+we.samples.reduce((tt,Al)=>tt+Al.size,0):void 0,Pe=De?c.duration:k-V,xt=Lu(Se,Pe*E.video.timescale,et,_t),At=ac(I,E.video.id,Se.length,Ke,xt);At?(G=At,q=bu(re,Se)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),N=At&&xt?Pe:k-V}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${j.length})`),N=k-V}else N=Y?M-U:k-V;if(this.videoOnlyRemux&&G===I)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),A;const ie=O.timescale,Z=O.start-r*ie,ne=Y?E.audio.id:E.video.id;if(w=O.start/ie,(a||!g)&&(Ru(g,w,r,N)||ie!==g.timescale)){let j=!1;const re=Y?"audio":"video";if(g){const ae=r!==0?w/r:1+w/1;j=w>=0&&Math.abs(1-ae)<.001,this.log(`${re} timestamps in track ${ne} at playlist time: ${a?"":"~"}${r} maps to ${w} with initPTS: ${g.baseTime/g.timescale} (${Z/ie-g.baseTime/g.timescale}s diff) (${F}) drift estimate: ${ae} ${j?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}j||(this.log(`Found initPTS in ${re} track ${ne} at playlist time: ${r} offset: ${w-r} (${Z}/${ie})`),g=null,C.initPTS=Z,C.timescale=ie,C.trackId=ne)}g?(C.initPTS=g.baseTime,C.timescale=g.timescale,C.trackId=g.trackId):((!C.timescale||C.trackId===void 0||C.initPTS===void 0)&&(this.warn("Could not set initPTS"),C.initPTS=w,C.timescale=1,C.trackId=-1),this.initPTS=g={baseTime:C.initPTS,timescale:C.timescale,trackId:C.trackId});const te=w-g.baseTime/g.timescale,oe=te+N,Te=_&&O?.ptsMin!==void 0?O.ptsMin/O.timescale-g.baseTime/g.timescale:te,Be=q!==void 0&&x?q/x.timescale-g.baseTime/g.timescale:_&&O!=null&&O.ptsMax?O.ptsMax/O.timescale-g.baseTime/g.timescale:oe;N>0?this.lastEndTime=oe:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const pt=(E.audio?E.audio.encrypted:!1)||(E.video?E.video.encrypted:!1),ge={data1:G,data2:ee,startPTS:Te,startDTS:te,endPTS:Be,endDTS:oe,type:F,hasAudio:P,hasVideo:_,nb:1,dropped:0,encrypted:pt};A.audio=P&&!_?ge:void 0,A.video=_?ge:void 0;const We=this.isVideoContiguous,ut=x?.sampleCount;if(ut){const j=x.keyFrameIndex,re=j!==-1;ge.nb=ut,ge.dropped=j===0||We?0:re?j:ut,ge.independent=re,ge.firstKeyFrame=j,re&&x.keyFrameStart&&(ge.firstKeyFramePTS=(x.keyFrameStart-g.baseTime)/g.timescale),We||(A.independent=re),this.isVideoContiguous||(this.isVideoContiguous=re),ge.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${j}/${ut} dropped: ${ge.dropped} start: ${ge.firstKeyFramePTS||"NA"}`)}return A.initSegment=C,A.id3=Ya(s,r,g,g),i.samples.length&&(A.text=Wa(i,r,g)),A}}function Ks(n,e,t=!1){return n?.start!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function bu(n,e){let t=n,s=n;for(let i=0;i<e.length;i++){const{cts:r,duration:a}=e[i];s=Math.max(s,t+(r||0)+a),t+=a}return s}function Lu(n,e,t,s){if(t!==void 0){const r=n[n.length-1];let a=e;for(let o=0;o<n.length-1;o++)a-=n[o].duration;return a<=0&&(a=r.duration),r.duration=a,{durationOffset:t,value:a}}if(s===void 0)return;const i=Math.round(e/n.length);for(let r=0;r<n.length;r++)n[r].duration=i;return{durationOffset:s,value:i}}function Ru(n,e,t,s){if(n===null)return!0;const i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>=i}function ja(n,e,t){const s=n.codec;return s&&s.length>4?s:e===de.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?xs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let vt;try{vt=self.performance.now.bind(self.performance)}catch{vt=Date.now}const Hs=[{demux:iu,remux:xu},{demux:gt,remux:Vs},{demux:Jh,remux:Vs},{demux:tu,remux:Vs}];Hs.splice(2,0,{demux:eu,remux:Vs});class za{constructor(e,t,s,i,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){if(!this.observer)return Ys(s);const r=s.transmuxing;r.executeStart=vt();const a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:m,videoCodec:A,defaultInitPts:I,duration:y,initSegmentData:C}=l,E=Du(a,t);if(E&&Bt(E.method)){const L=this.getDecrypter(),R=ki(E.method);return this.asyncResult=!0,this.decryptionPromise=L.decrypt(a,E.key.buffer,E.iv.buffer,R,s.decryptRange).then(x=>{const P=this.push(x,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const v=this.needsProbing(h,u);if(v){const L=s.iframe&&C&>.probe(C,this.logger)?C:a,R=this.configureTransmuxer(L);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),r.executeEnd=vt(),Ys(s)}(h||u||g||v)&&this.resetInitSegment(C,m,A,y,t,s),(h||g||v)&&this.resetInitialTimestamp(I),c||this.resetContiguity();const T=this.transmux(a,E,f,d,s);this.asyncResult=cs(T);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,r.executeEnd=vt(),T}flush(e){const t=e.transmuxing;t.executeStart=vt();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=vt();const u=[Ys(e)];return this.asyncResult?Promise.resolve(u):u}const h=l.flush(o,e);return cs(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const h=this.remuxer.remux(i,r,a,o,c,l,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=vt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r,a){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,s,i,r,a),l.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,s,i,r){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{demuxer:r,remuxer:a}=this;if(!r||!a)return Ys(i);const o=r.demux(e,t,i,!1,!this.config.progressive),{audioTrack:l,videoTrack:c,id3Track:h,textTrack:u}=o;return{remuxResult:a.remux(l,c,h,u,t,s,!1,this.id,i,o.initData,o.sampleData),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id,r,a.initData,a.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let u=0,d=Hs.length;u<d;u++){var a;if((a=Hs[u].demux)!=null&&a.probe(e,this.logger)){r=Hs[u];break}}}catch(u){return u}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=r.demux,h=r.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(s,t,i,this.logger),this.probe=c.probe),(!l||!(l instanceof h))&&(this.logger.log(`Using ${h.name}`),this.remuxer=new h(s,t,i,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ri(this.config)),e}}function Du(n,e){let t=null;return n.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ys=n=>({remuxResult:{},chunkMeta:n});function cs(n){return"then"in n&&n.then instanceof Function}class Pu{constructor(e,t,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=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class _u{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}let qa=0;class Xa{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=qa++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,h=this.hls;if(!(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{h.logger[c.data.logType]&&h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===p.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new Gi,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=yn(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||Bh()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=$h(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Uh());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:fe(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new za(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new za(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=qa++;const t=this.hls.config,s=yn(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:fe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Gh(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,m=a?a.start:r.start,A=r.decryptdata,I=this.frag,y=I?r.cc!==I.cc:!0,C=I?c.level!==I.level:!0,E=I?c.sn-I.sn:-1,v=this.part?c.part-this.part.index:-1,T=E===0&&c.id>1&&c.id===I?.stats.chunkCount,S=!C&&(E===1||E===0&&(v===1||T&&v<=0)),L=self.performance.now();(C||E||r.stats.parsing.start===0)&&(r.stats.parsing.start=L),a&&(v||!S)&&(a.stats.parsing.start=L);const R=!(I&&((u=r.initSegment)==null?void 0:u.url)===((d=I.initSegment)==null?void 0:d.url)),x=new _u(y,S,l,C,m,R);if(!S||y||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id} playlist: ${c.level} id: ${c.id}
|
|
166
|
+
discontinuity: ${y}
|
|
167
|
+
trackSwitch: ${C}
|
|
168
|
+
contiguous: ${S}
|
|
169
|
+
accurateTimeOffset: ${l}
|
|
170
|
+
timeOffset: ${m}
|
|
171
|
+
initSegmentChange: ${R}`);const P=new Pu(s,i,t,o,h);this.configureTransmuxer(P)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:A,chunkMeta:c,state:x},e instanceof ArrayBuffer?[e]:[]);else if(g){const P=g.push(e,A,c,x);cs(P)?P.then(_=>{this.handleTransmuxComplete(_)}).catch(_=>{this.transmuxerError(_,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);cs(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Za=100;class ku extends Ui{constructor(e,t,s){super(e,t,s,"audio-stream-controller",H.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:s,id:i,initPTS:r,timescale:a,trackId:o,timestampOffsets:l}=t;if(i===H.MAIN){const c=s.cc,h=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${c} found from main: ${r/a} (${r}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===D.WAITING_INIT_PTS){const u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==c)&&this.syncWithAnchor(s,u?.frag)}else!this.hls.hasEnoughToStart&&h&&h.cc!==c?(h.abortRequests(),this.syncWithAnchor(s,h)):this.state===D.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=On(a,r,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===D.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=D.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Za),s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=D.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case D.IDLE:this.doTickIdle();break;case D.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=D.WAITING_INIT_PTS}break}case D.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case D.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=D.FRAG_LOADING;const o=i.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=D.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=D.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.getBufferOutput();this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,de.AUDIO));const h=this.getFwdBufferInfo();if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=D.ENDED;return}const u=h.len,d=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),A=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:h.end;if(this.switchingTrack&&i){const C=m;l.PTSKnown&&C<g&&C>=this.timelineOffset&&(h.end>g||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${C} -> ${g} + 0.05`),i.currentTime=g+.05)}if(u>=d&&!this.switchingTrack&&A<f[f.length-1].start)return;let I=this.getNextFragment(A,l);if(I&&this.isLoopLoading(I,A)&&(I=this.getNextFragmentLoopLoading(I,l,h,H.MAIN,d)),!I){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,d,I))return;let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Ie(I)&&!I.endList&&(!l.live||!this.loadingParts&&A<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===pe.OK&&(this.mainFragLoading=y=null),y&&Ie(y))){if(I.start>y.end){const E=this.fragmentTracker.getFragAtPos(A,H.MAIN);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(I.start>y.end)return}this.loadFragment(I,o,A)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Jt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==D.STOPPED&&(this.setInterval(Za),this.state=D.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:a,groupId:o,track:l}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||r.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==D.STOPPED&&(this.state=D.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[a];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(Fs(c,r,this),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===D.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=D.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Xa(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const A=i?i.index:-1,I=A!==-1,y=new Di(s.level,s.sn,s.stats.chunkCount,r.byteLength,A,I,s.duration);d.push(r,g,u,"",s,i,h.totalduration,!1,y,f)}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 ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new xa,complete:!1};m.push(new Uint8Array(r)),this.state!==D.STOPPED&&(this.state=D.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&Ie(t.frag)&&(this.mainFragLoading=t,this.state===D.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==H.AUDIO){!this.audioOnly&&s.type===H.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}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"}`);return}if(Ie(s)){const r=this.switchingTrack;r&&(this.bufferedTrack=r)}this.fragBufferedComplete(s,i),this.media&&this.tick()}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,H.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const s=this.fragPlaying,i=e?.level;return(!s||s.level!==i)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===se.AUDIO_TRACK&&(this.state=D.IDLE);break;case b.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==de.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==de.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===D.ENDED&&(this.state=D.IDLE);const s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,t),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:g,initSegment:m}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=D.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:A}=this,I=A.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+I,l.start);super.flushMainBuffer(y,Number.POSITIVE_INFINITY,H.AUDIO)}if(m!=null&&m.tracks){const A=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,A,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:s,tracks:m.tracks})}if(d){const{startPTS:A,endPTS:I,startDTS:y,endDTS:C}=d;c&&(c.elementaryStreams[de.AUDIO]={startPTS:A,endPTS:I,startDTS:y,endDTS:C}),l.setElementaryStreamInfo(de.AUDIO,A,I,y,C),this.bufferFragmentData(d,l,c,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const A=ue({id:s,frag:l,details:u},g);i.trigger(p.FRAG_PARSING_METADATA,A)}if(f){const A=ue({id:s,frag:l,details:u},f);i.trigger(p.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=H.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a?.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===pe.NOT_LOADED||i===pe.PARTIAL){var r;if((r=t.details)!=null&&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=D.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Fs(a,t.details,this)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;bt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,Lt)||(Ds(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,z({},e))}get nextAudioTrack(){return this.nextTrackId}}class Xi extends Ue{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=s&&bn(s);return new Ln(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=i.fragments,o=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(o-r.loading.first)):0;i.advancedDateTime=Date.now()-l;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const u=Math.max(c||0,0);i.appliedTimelineOffset=u,a.forEach(d=>{d?.setStart(d.playlistOffset+u)})}if(i.live||s!=null&&s.live){var h;const u="levelInfo"in t?t.levelInfo:t.track;i.reloaded(s);const d=(h=a[a.length-1])==null?void 0:h.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const v=new Error(`${d} playlist ${u.id} hit max allowed unchanged reloads.`);this.warn(v);const{networkDetails:T,context:S}=t;this.hls.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level,parent:d,context:S,networkDetails:T,stats:r});return}if(s){bh(s,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){const{networkDetails:S}=t;T.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:t.level,parent:d,networkDetails:S,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(i.edge-g)*1e3,A=pa(i,m);i.requestScheduled+A<o?i.requestScheduled=o:i.requestScheduled<=o&&(i.requestScheduled+=A);const I=t.deliveryDirectives;if(this.log(`live playlist ${e} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${I?` | requested ${I.msn} - ${I.part}`:""})`}`),!this.canLoad||!i.live)return;let y,C,E;if(i.canBlockReload&&i.advanced){const v=this.hls.config.lowLatencyMode,T=i.lastPartSn,S=i.endSN,L=i.lastPartIndex,R=L!==-1,x=T===S;R?x?(C=S+1,E=v?0:L):(C=T,E=v?L+1:i.maxPartIndex):C=S+1;const P=i.age,_=P+i.ageHeader;let F=Math.min(_-i.partTarget,i.targetduration*1.5);if(F>0){if(_>i.targetduration*3)this.log(`Playlist last advanced ${P.toFixed(2)}s ago. Omitting segment and part directives.`),C=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&_-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${F} with playlist age: ${i.age}`),F=0;else{const V=Math.floor(F/i.targetduration);if(C+=V,E!==void 0){const U=Math.round(F%i.targetduration/i.partTarget);E+=U}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${P.toFixed(2)}s goal: ${F} skip sn ${V} to part ${E}`)}i.tuneInGoal=F}if(y=this.getDeliveryDirectives(i,t.deliveryDirectives,C,E),v||!x){i.requestScheduled=o,this.loadingPlaylist(u,y);return}}else(i.canBlockReload||i.canSkipUntil)&&(y=this.getDeliveryDirectives(i,t.deliveryDirectives,C,E));y&&C!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(A-l*2,A/2)),this.scheduleLoading(u,y,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=i.requestScheduled;if(r>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}const o=Math.max(a-r,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=bn(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Rs.No),new Ln(s,i,r)}checkRetry(e){const t=e.details,s=ps(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===be.RetryRequest||!i.resolved&&r===be.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;const u=Wt((h=e.response)==null?void 0:h.code);if(this.clearTimer(),u)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const d=ci(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),d)}}e.levelRetry=!0,i.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),Wt(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function Qa(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!hs(n[t].attrs,e[t].attrs))return!1;return!0}function hs(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}class wu extends Xi{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>es(d.groupId,s));if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=nt(l,o,Lt);if(d>-1)r=o[d];else{const f=nt(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===se.AUDIO_TRACK&&t.context.id===this.trackId&&es(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&bt(e,i,Lt))return i;const r=nt(e,this.tracksInGroup,Lt);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=qc(e,t.levels,s,a,Lt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=nt(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e,t=!0){const s=this.tracksInGroup;if(e<0||e>=s.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[e],a=r.details&&!r.details.live;if(e===this.trackId&&r===i&&a||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,z(z({},r),{},{flushImmediate:t})),a))return;const o=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||bt(e,i,Lt)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(bt({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,Lt))return c}for(let c=0;c<t.length;c++){const h=t[c];if(hs(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(hs(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ds(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Mu{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;s==="async-blocker"||s==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):s==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
172
|
+
${this.list("video")}
|
|
173
|
+
${this.list("audio")}
|
|
174
|
+
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Ja=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,eo="HlsJsTrackRemovedError",Ou=.25,Fu=.001;class Nu extends Error{constructor(e){super(e),this.name=eo}}class Bu extends Ue{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(ce(r,"sourceopen",this._onMediaSourceOpen),ce(i,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const s=this.media.error,{appendError:i,appendErrors:r}=this;let a=!1;!i&&s&&(a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${so(a,s)}`);this.warn(o),this.hls.trigger(p.ERROR,ue({fatal:a},i,{type:W.MEDIA_ERROR,details:b.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this._onMediaError=()=>{const{media:s}=this;if(s){var i,r;this.log(`Media error (code: ${(i=s.error)==null?void 0:i.code}): ${(r=s.error)==null?void 0:r.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=$l(Ct(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===t?ue(s,i.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(s[a]=ue({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=Ct(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,to(s),Uu(s,o),s.load()}catch{s.src=o}else s.src=o}he(s,"emptied",this._onMediaEmptied),he(s,"error",this._onMediaError),this.appendSource&&he(s,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),he(e,"sourceopen",this._onMediaSourceOpen),he(e,"sourceended",this._onMediaSourceEnded),he(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(he(e,"startstreaming",this._onStartStreaming),he(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
175
|
+
required tracks: ${fe(s,(l,c)=>l==="initSegment"?void 0:c)};
|
|
176
|
+
transfer tracks: ${fe(i,(l,c)=>l==="initSegment"?void 0:c)}}`),!jr(i,s)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,h=Math.max(l,c?.fragments[0].start||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{const c=l,h=i[c];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const A=X.getBuffered(u);d.detectEvictedFragments(c,A,f,null,null,!0)}const g=Zi(c),m=[c,u];this.sourceBuffers[g]=m,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),r.removeSourceBuffer(l[c]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}ce(r,"sourceopen",this._onMediaSourceOpen),ce(r,"sourceended",this._onMediaSourceEnded),ce(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ce(r,"startstreaming",this._onStartStreaming),ce(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(ce(i,"emptied",this._onMediaEmptied),ce(i,"error",this._onMediaError),ce(i,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&to(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Zi(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Mu(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!i[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var c,h;const u=t[l],{id:d,codec:f,levelCodec:g,container:m,metadata:A,supplemental:I}=u;let y=i[l];const C=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],E=C!=null&&C.buffer?C:y,v=E?.pendingCodec||E?.codec,T=E?.levelCodec;y||(y=i[l]={buffer:void 0,listeners:[],codec:f,supplemental:I,container:m,levelCodec:g,metadata:A,id:d});const S=bs(v,T),L=S?.replace(Ja,"$1");let R=bs(f,g);const x=(h=R)==null?void 0:h.replace(Ja,"$1");R&&S&&L!==x&&(l.slice(0,5)==="audio"&&(R=xs(R,this.appendSource)),this.log(`switching codec ${v} to ${R}`),R!==(y.pendingCodec||y.codec)&&(y.pendingCodec=R),y.container=m,this.appendChangeType(l,m,R))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,H.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>i||X.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,i)||((l=this.fragmentTracker.getAppendedFrag(i,H.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:l,chunkMeta:c,offset:h}=t,u=c.buffering[r],d=Ie(o)&&!l&&!o.gap&&!c.partial&&!c.iframe;let f=null,g=!1;const{sn:m,cc:A}=o,I=self.performance.now();u.start=I;const y=o.stats.buffering,C=l?l.stats.buffering:null;y.start===0&&(y.start=I),C?.start===0&&(C.start=I);const E=s.audio;let v=!1;r==="audio"&&E?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const T=s.video,S=T?.buffer;if(S&&m!=="initSegment"&&h!==void 0){const x=E?.buffer,P=l||o;if(r==="audio"&&a!=="main"&&!(T.ending||T.ended)&&x&&X.getBuffered(x).length){const F=P.start+P.duration*.05,V=X.getBuffered(S),U=this.currentOp("video");!V.length&&!U?this.blockAudio(P):!X.isBuffered(S,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(P)}else if(r==="video"){const _=P.end,F=this.lastVideoAppendEnd-_;this.lastVideoAppendEnd=_,F<0||F>P.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const L=(l||o).start,R={label:`append-${r}`,execute:()=>{var x;u.executeStart=self.performance.now();const P=(x=this.tracks[r])==null?void 0:x.buffer;P&&(d&&(f=X.timeRangesToArray(X.getBuffered(P)),g=ro(Qi(f,o),o)),v?this.updateTimestampOffset(P,L,.1,r,m,A):h!==void 0&&B(h)&&this.updateTimestampOffset(P,h,1e-6,r,m,A)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const x=self.performance.now();u.executeEnd=u.end=x,y.first===0&&(y.first=x),C?.first===0&&(C.first=x);const P={};if(this.sourceBuffers.forEach(([_,F])=>{_&&(P[_]=X.getBuffered(F))}),d){const _=this.getFragmentAppendProgress(o),F=P[r];if(F&&f){const V=X.timeRangesToArray(F),U=Qi(V,o);_.progressed||(_.progressed=U-Qi(f,o)>Fu);const k=g&&ro(U,o);_.fullyBuffered[r]=(_.fullyBuffered[r]===void 0||_.fullyBuffered[r])&&k}}this.hls.trigger(p.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:c,parent:a,timeRanges:P})},onError:x=>{var P;this.clearBufferAppendTimeoutId(this.tracks[r]);const _=x.code===DOMException.QUOTA_EXCEEDED_ERR||x.name=="QuotaExceededError"||"quota"in x;if(_&&!this._quotaEvictionPending[r]){const k=this.getBackBufferEvictionTarget(r,i.byteLength,o.type);if(k>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${m} - evicting back buffer to ${k.toFixed(3)}s and retrying`);const M=this.getFlushOp(r,0,k),w=this.getClearEvictionPendingOp(r);this.insertNext([M,R,w],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${m} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);const F={type:W.MEDIA_ERROR,parent:a,details:b.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:c,error:x,err:x,fatal:!1},V=(P=this.media)==null?void 0:P.error;if(x.name===eo&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))F.errorAction=ts(!0);else{var U;_&&(F.details=b.BUFFER_FULL_ERROR);const k=++this.appendErrors[r],M=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${k}/${M+1} times to append segment in "${r}" sourceBuffer with error: ${x.message}`),k>=M&&(F.fatal=!_);const w=(U=this.mediaSource)==null?void 0:U.readyState;(w==="ended"||w==="closed"||V)&&(this.warn(`MediaSource readyState "${w}" during SourceBuffer${so(F.fatal,V)}`),F.details=b.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=F,this.hls.trigger(p.ERROR,F),_&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${r}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${A} offset: ${h} bytes: ${i.byteLength}`),this.append(R,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var i;const r=(i=this.tracks[e])==null?void 0:i.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${r?Ns(X.getBuffered(r)):"(detached)"}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){const{frag:s,part:i,chunkMeta:r}=t,a=[],o=i?i.elementaryStreams:s.elementaryStreams;o[de.AUDIOVIDEO]?a.push("audiovideo"):(o[de.AUDIO]&&a.push("audio"),o[de.VIDEO]&&a.push("video"));const l=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const h=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,a),this.hls&&(this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:h,id:s.type,chunkMeta:r}),!i&&s.gap&&h.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${h.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(c=>{this.warn(`Fragment buffered callback ${c.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const{backBufferLength:a,frontBufferFlushThreshold:o}=r;this.trimBuffers(o,a,t.frag,t.previousFrag);const l=t.frag.elementaryStreams,{appendErrors:c}=this,h=(i=this.appendError)==null?void 0:i.sourceBufferName;Object.keys(l).forEach(u=>{l[u]&&(c[u]=0,u===h&&(this.appendError=void 0),u==="audio"||u==="video"?(c.audiovideo=0,h==="audiovideo"&&(this.appendError=void 0)):(c.audio=0,c.video=0,h!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(a?.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===b.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;B(i)&&i!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,t):0}getFragmentAppendProgress(e){var t;const s=io(e);let i=this.fragmentAppendProgress[s];return((t=i)==null?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(e,t,s,i){if(t||!Ie(e)||e.gap||s.iframe||s.partial)return;const r=io(e),a=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const o=e.stats.buffering;if(o.start&&!o.first)return;const l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;const c=i.length>0&&i.every(f=>l?.fullyBuffered[f]===!0);if(l!=null&&l.progressed||c){delete this.appendsWithoutProgress[r];return}if(!l&&i.length===0)return;const h=(this.appendsWithoutProgress[r]||0)+1,u=this.hls;h>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=h,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${h} time${h>1?"s":""} without buffered range growth`),u.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:h,error:new Error(`Fragment append did not increase buffered coverage (${h})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,s,i){const{hls:r,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;const l=r.config,c=o.currentTime,h=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let u=-1/0;if(B(t)&&t>=0){const d=Math.max(t,h);u=Math.floor(c/h)*h-d}if(s){const d=this.getLoopBackBufferFlushEnd(s,i??null);d>0&&(u=Math.max(u,d))}if(u>0&&this.flushBackBuffer(c,h,u),B(e)&&e>0){const d=Math.max(l.maxBufferLength,e),f=Math.max(d,h),g=Math.floor(c/h)*h+f;this.flushFrontBuffer(c,h,g)}}getLoopBackBufferFlushEnd(e,t){var s;const{media:i}=this;if(((s=this.hls)==null?void 0:s.config.loopBackBufferFlush)===!1||!(i!=null&&i.loop)||!t||e.level<=t.level)return 0;const{video:r,audiovideo:a}=e.elementaryStreams;if(r!=null&&r.partial||a!=null&&a.partial)return 0;const o=this.getEarliestElementaryStreamStart(e)-Ou;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){const{audio:t,video:s,audiovideo:i}=e.elementaryStreams;let r=e.start;return i?r=Math.min(r,i.startDTS):(t&&(r=Math.min(r,t.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const c=X.getBuffered(r);if(c.length>0&&s>c.start(0)){var a,o,l;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s});const h=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(h!=null&&h.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=X.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(s>l||e>=l&&e<=c)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),h=Math.max(c,i);return{duration:1/0,start:c,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return B(r)?{duration:r}:null;const a=this.media.duration,o=B(s.duration)?s.duration:0;return i>o&&i>a||!B(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!i||!this.media||i.readyState!=="open"||(i.duration!==e&&(B(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${fe(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${fe(o)}`);try{const h=s.addSourceBuffer(c),u=Zi(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&Zt(s,"video")&&(i=_c(i,s));const r=bs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?xs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&(this.log(`${r} buffer removed ${Ns(o)}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:r,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);if(!i)return;if(i.onComplete(),(s=this.tracks[e])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var s;const i=(s=this.mediaSource)==null?void 0:s.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,t),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const a=this.currentOp(e);a&&a.onError(r)}updateTimestampOffset(e,t,s,i,r,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,a=this.tracks[e],o=a?.buffer;if(!i||!r||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const l=B(i.duration)?i.duration:1/0,c=B(r.duration)?r.duration:1/0,h=Math.max(0,t);if(h>=c){var u;(u=this.currentOp(e))==null||u.onComplete(),this.shiftAndExecuteNext(e);return}const d=Math.min(s,l,c);if(d>h&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),o.remove(h,d);else throw new Error(`Cannot remove ${d<=h?`invalid range (${h} >= ${d}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Nu(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const r=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,i,r),r)}i.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Xn;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(this.media===null)return s;const i=X.bufferInfo(e,this.media.currentTime,0);return i.len?(s=Math.max(i.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const a=s.bind(this,e);i.listeners.push({event:t,listener:a}),he(r,t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{ce(s,i.event,i.listener)}),t.listeners.length=0)}}function to(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function Uu(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function Zi(n){return n==="audio"?1:0}function so(n,e){return`${n?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function io(n){return`${n.type}_${n.sn}_${n.level}`}function Qi(n,e){const{start:t,end:s}=e;let i=0;for(let r=0;r<n.length;r++){const a=n[r];if(a.start>=s)break;const o=Math.max(t,a.start),l=Math.min(s,a.end);l>o&&(i+=l-o)}return i}function ro(n,e){return e.duration-n<=.05}class Ji{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:e}=this;e&&(e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){const s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(B(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const e=this.hls.levels;if(e.length>1){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.observer||(this.clientRect=null),Ji.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(t=>{var s;const i=(s=t[0])==null?void 0:s.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}}var Fe=class wr{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof wr?s:new wr(s))),this.value=e,this.params=t}};const $u="Dict";function Gu(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Vu(n,e,t,s){return new Error(`failed to ${n} "${Gu(e)}" as ${t}`,{cause:s})}const no="Bare Item",Ku="Boolean",Hu="Byte Sequence",Yu="Decimal",Wu="Integer";function ju(n){return n<-999999999999999||999999999999999<n}const zu="String",qu=/[\x00-\x1f\x7f]+/;var ao=class{constructor(n){this.description=n}};const Xu="Token",Zu="Key";function ct(n,e,t){return Vu("serialize",n,e,t)}function Qu(n){if(typeof n!="boolean")throw ct(n,Ku);return n?"?1":"?0"}function Ju(n){if(ArrayBuffer.isView(n)===!1)throw ct(n,Hu);return`:${Gl(n)}:`}function oo(n){if(ju(n))throw ct(n,Wu);return n.toString()}function ed(n){return`@${oo(n.getTime()/1e3)}`}function td(n){const e=qr(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ct(n,Yu);const t=e.toString();return t.includes(".")?t:`${t}.0`}function sd(n){if(qu.test(n))throw ct(n,zu);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function id(n){return n.description||n.toString().slice(7,-1)}function lo(n){const e=id(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ct(e,Xu);return e}function er(n){switch(typeof n){case"number":if(!B(n))throw ct(n,no);return Number.isInteger(n)?oo(n):td(n);case"string":return sd(n);case"symbol":return lo(n);case"boolean":return Qu(n);case"object":if(n instanceof Date)return ed(n);if(n instanceof Uint8Array)return Ju(n);if(n instanceof ao)return lo(n);default:throw ct(n,no)}}function tr(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw ct(n,Zu);return n}function sr(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${tr(e)}`:`;${tr(e)}=${er(t)}`).join("")}function co(n){return n instanceof Fe?`${er(n.value)}${sr(n.params)}`:er(n)}function rd(n){return`(${n.value.map(co).join(" ")})${sr(n.params)}`}function nd(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw ct(n,$u);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Fe||(r=new Fe(r));let a=tr(i);return r.value===!0?a+=sr(r.params):(a+="=",Array.isArray(r.value)?a+=rd(r):a+=co(r)),a}).join(`,${s}`)}function ho(n,e){return nd(n,e)}const ad=["url"],od=["version","eventTargets","sid","transmissionMode"],ld=["customData","headers"],uo=n=>n instanceof Fe?new Fe(Math.round(n.value),n.params):Math.round(n),ir=n=>Array.isArray(n)?n.map(uo):uo(n),rr=(n,e)=>Array.isArray(n)?n.map(t=>rr(t,e)):n instanceof Fe&&typeof n.value=="string"?new Fe(rr(n.value,e),n.params):(e.baseUrl&&(n=Yl(n,Hl(e.baseUrl))),e.version===1?encodeURIComponent(n):n),fo=n=>n instanceof Fe?new Fe(Math.round(n.value/100)*100,n.params):Math.round(n/100)*100,Ws=n=>Array.isArray(n)?n.map(fo):fo(n),cd={br:ir,d:ir,bl:Ws,dl:Ws,mtp:Ws,nor:(n,e)=>{let t=n;return e.version>=2&&(n instanceof Fe&&typeof n.value=="string"?t=new Fe([n]):typeof n=="string"&&(t=[n])),rr(t,e)},rtp:Ws,tb:ir},us=2,go="bc",hd="ps",mo="pr",ud="e",po="t",dd="c",Ao="b",nr="rr",Io="ce",js={BITRATE_CHANGE:go,ERROR:ud,RESPONSE_RECEIVED:nr,CUSTOM_EVENT:Io},Co=new Map([[hd,"sta"],[mo,"pr"],[dd,"cid"],[Ao,"bg"],[go,"br"]]),ar="event",or="request",yo=["cen","e","h","ts"],Eo=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],fd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function lr(n){return fd.test(n)}const gd=new Set(Eo);function vo(n){return gd.has(n)||lr(n)}const To=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],md=new Set(To);function So(n){return md.has(n)}const pd=new Set(yo);function Ad(n){return vo(n)||So(n)||pd.has(n)}const Id=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),zs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Cd=new Set(zs);function yd(n){return Cd.has(n)||lr(n)}const Ed=new Set(["ot","sf","st","e","sta"]);function vd(n){return Ed.has(n)}function Td(n){return typeof n=="number"?B(n):n!=null&&n!==""&&n!==!1}const Sd={[ar]:Ad,[or]:vo};function xo(n,e){if(Array.isArray(n)){let t;return e&&(t=n.find(s=>{var i;return((i=s.params)==null?void 0:i.ot)===e})),t||(t=n[0]),xo(t)}return n instanceof Fe?n.value:n}function xd(n){const e={};for(const[s,i]of Object.entries(n)){if(i==null){e[s]=i;continue}if(s==="nor"){const r=(Array.isArray(i)?i:[i])[0];if(r instanceof Fe){var t;e.nor=r.value,(t=r.params)!=null&&t.r&&(e.nrr=r.params.r)}else e.nor=r}else Id.has(s)?e[s]=xo(i,n.ot):e[s]=i}return e}function bo(n,e={}){const t={};if(n==null||typeof n!="object")return t;const s=e.version||n.v||us,i=e.reportingMode||or,r=s===1?xd(n):n,a=s===1?yd:Sd[i];let o=Object.keys(r).filter(a);r.e&&r.e!==nr&&(o=o.filter(f=>!So(f)));const l=e.filter;typeof l=="function"&&(o=o.filter(l));const c=i===ar;if(c){const f=r.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&r.cen!=null&&f===Io&&o.push("cen");const g=f?Co.get(f):void 0;g&&r[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;s>1&&!o.includes("v")&&o.push("v");const h={version:s,reportingMode:i,baseUrl:e.baseUrl};o.sort();for(const f of o){var u,d;let g=r[f];const m=(u=(d=e.formatters)==null?void 0:d[f])!=null?u:cd[f];if(typeof m=="function"&&(g=m(g,h)),f==="v"){if(s===1)continue;g=s}if(f==="pr"&&g===1&&!(c&&r.e===mo))continue;c&&f==="ts"&&!B(g)&&(g=Date.now());const A=c&&g===!1&&f==="bg"&&r.e===Ao;!Td(g)&&!A||(vd(f)&&typeof g=="string"&&(g=new ao(g)),t[f]=g)}return t}const mt="CMCD-Object",Ne="CMCD-Request",Gt="CMCD-Session",qe="CMCD-Status",bd={REQUEST:Ne},Ld={ab:mt,br:mt,d:mt,lab:mt,lb:mt,ot:mt,tab:mt,tb:mt,tpb:mt,bl:Ne,cs:Ne,dfa:Ne,dl:Ne,ltc:Ne,mtp:Ne,nor:Ne,nrr:Ne,pb:Ne,sn:Ne,sta:Ne,su:Ne,tbl:Ne,cid:Gt,msd:Gt,sf:Gt,sid:Gt,st:Gt,v:Gt,bg:qe,bs:qe,bsa:qe,bsd:qe,bsda:qe,cdn:qe,ec:qe,nr:qe,pr:qe,pt:qe,rtp:qe};function Rd(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])==null||s.forEach(i=>e[i]=t),e},{})}function Dd(n,e){const t={};if(!n)return t;const s=Object.keys(n),i=e?Rd(e):{};for(const a of s){var r;const o=Ld[a]||i[a]||bd.REQUEST,l=(r=t[o])!=null?r:t[o]={};l[a]=n[a]}return t}function Pd(n,e){const t={},s=Dd(n,e);for(const[i,r]of Object.entries(s)){const a=ho(r,{whitespace:!1});a&&(t[i]=a)}return t}const Lo="CMCD";function Ro(n){return ho(n,{whitespace:!1})}function _d(n,e={}){return n?Ro(bo(n,e)):""}const kd=30,cr=[...zs,...Eo,...To,...yo].filter((n,e,t)=>t.indexOf(n)===e),wd="application/cmcd",Md=1,Re={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Xe={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},hr="query",Do="headers";function Po(n,e,t){var s;const i=new Set((s=e.enabledKeys)!=null?s:[]);return{version:e.version||us,reportingMode:n,filter:r=>i.has(r),baseUrl:t}}function Od(n,e){if(n===e)return!0;if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++){const s=n[t],i=e[t];if(s===i)continue;if(typeof s=="number"||typeof i=="number"||s.value!==i.value)return!1;const r=s.params,a=i.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&r&&a&&r[o]!==a[l])return!1}return!0}const Fd=Object.is,Nd=n=>n,_o=Array.from(Co,([n,e])=>e==="br"?{event:n,field:e,equal:(t,s)=>t===void 0||s===void 0?t===s:Od(t,s),snapshot:t=>t.slice()}:{event:n,field:e,equal:Fd,snapshot:Nd}),Bd=new Map(_o.map(n=>[n.event,n]));function Ud(n){const{url:e}=n,t=ms(n,ad);return fetch(e,t)}function $d(n){const{version:e=us,eventTargets:t=[],sid:s=Xr(),transmissionMode:i=hr}=n,r=ms(n,od);return z(z({},r),{},{version:e,transmissionMode:i,sid:s,eventTargets:t.reduce((a,o)=>{var l,c,h;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||us,enabledKeys:((c=o.enabledKeys)==null?void 0:c.slice())||[],url:o.url,events:o.events.slice(),interval:(h=o.interval)!=null?h:kd,batchSize:o.batchSize||1}),a},[])})}var Gd=class{constructor(n,e=Ud){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=$d(n),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((n,e)=>{if(this.disarmInterval(n),e.interval===0||!e.events.includes(po))return;const t=()=>{this.recordTargetEvent(n,e,po),this.processEventTargets()};n.intervalId=setInterval(t,e.interval*1e3),t()})}stop(n=!1){n&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(n){n.sid&&n.sid!==this.data.sid&&this.resetSession(),n.msd&&!isNaN(n.msd)&&(this.msd=n.msd),this.data=z(z(z({},this.data),n),{},{msd:void 0});for(const e of _o)e.field in n&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(n,e={}){const t=Bd.get(n);if(t){const s=t.field,i=e[s];i!==void 0&&ue(this.data,{[s]:i});const r=this.data[s];if(r===void 0||t.equal(r,this.lastEmitted[s]))return;ue(this.lastEmitted,{[s]:t.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,n,e)}),this.processEventTargets()}recordTargetEvent(n,e,t,s={}){var i;if(!e.events.includes(t))return;const r=z(z(z({},this.data),s),{},{e:t,ts:(i=s.ts)!=null?i:Date.now(),sn:n.sn++});!isNaN(this.msd)&&!n.msdSent&&(r.msd=this.msd,n.msdSent=!0),n.queue.push(r)}recordResponseReceived(n,e={}){var t,s,i;const{request:r}=n,a=(t=e.url)!=null?t:r?.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Lo);const l={url:o.toString(),rc:n.status},c=n.resourceTiming;c&&(c.startTime!=null&&(l.ts=Math.round(this.timeOrigin+c.startTime),c.responseStart!=null&&(l.ttfb=Math.round(c.responseStart-c.startTime))),c.duration!=null&&(l.ttlb=Math.round(c.duration)));const h=(s=(i=r.customData)==null?void 0:i.cmcd)!=null?s:{};this.recordEvent(nr,z(z(z({},h),l),e))}applyRequestReport(n){var e;return(e=this.createRequestReport(n))!=null?e:n}isRequestReportingEnabled(){var n;return!!((n=this.config.enabledKeys)!=null&&n.length)}createRequestReport(n,e){var t;const{customData:s={},headers:i={}}=n,r=ms(n,ld),a=z(z({},r),{},{headers:z({},i),customData:z(z({},s),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;const o=new URL(a.url),l=z(z(z({},this.data),e),{},{sn:this.requestTarget.sn++}),c=Po(or,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);const h=a.customData.cmcd=bo(l,c);switch(this.config.transmissionMode){case hr:const u=Ro(h);u&&(o.searchParams.set(Lo,u),a.url=o.toString());break;case Do:ue(a.headers,Pd(h,c.customHeaderMap));break}return a}processEventTargets(n=!1){let e=!1;this.eventTargets.forEach((t,s)=>{const{queue:i}=t;if(!i.length||i.length<s.batchSize&&!n)return;const r=n?i.length:s.batchSize,a=i.splice(0,r);this.sendEventReport(s,a).catch(()=>{t.queue.unshift(...a)}),e||(e=i.length>0)}),e&&this.processEventTargets()}async sendEventReport(n,e){const t=Po(ar,n),{status:s}=await this.requester({url:n.url,method:"POST",headers:{"Content-Type":wd},body:e.map(i=>_d(i,t)).join(`
|
|
177
|
+
`)+`
|
|
178
|
+
`});if(s===410)this.disposeEventTarget(n);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(n){clearInterval(n.intervalId),n.intervalId=void 0}disposeEventTarget(n){const e=this.eventTargets.get(n);e&&(this.disarmInterval(e),this.eventTargets.delete(n))}resetSession(){this.eventTargets.forEach(n=>n.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Vd={HLS:"h"},ur={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function Kd(n,e){return new Fe(n,e)}new Set(zs),new Set(cr);const Hd=["includeKeys"];function ko(n){return Object.keys(n).every(lr)}class Yd{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Xe.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Xe.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Xe.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Xe.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Xe.SEEKING)},this.onSeeked=()=>{var i;this.initialized&&(i=this.media)!=null&&i.paused&&this.setPlayerState(Xe.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Re.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:o,part:l}=i,c=this.hls.levels[o.level],h=this.getObjectType(o,c),u={d:(l||o).duration*1e3,ot:h};if(h===Re.VIDEO||h===Re.AUDIO||h===Re.MUXED||h==null&&(o.type==="main"||o.type==="audio")){var r;const f=c.bitrate/1e3;u.br=[f];const{cmcd:g}=this.config,m=(r=g?.rtpSafetyFactor)!=null?r:5;if(u.rtp=Math.round(f*m/100)*100,h===Re.MUXED||h==null&&o.type==="main"){const y=this.getTopBandwidth()/1e3;B(y)&&(u.tb=[y]);const C=this.getLowestBandwidth()/1e3;B(C)&&(u.lb=[C])}const A=this.getBufferLength(o);if(B(A)){var a;u.bl=[A];const y=((a=this.media)==null?void 0:a.playbackRate)||1;u.dl=Math.round(A/y/100)*100}this.playheadLevel&&(u.pb=[this.playheadLevel.bitrate/1e3]);const I=this.hls.maxAutoLevel;if(I>=0){const y=this.hls.levels[I];y&&(u.tpb=[y.bitrate/1e3])}}const d=l?this.getNextPart(l):this.getNextFrag(o);d!=null&&d.url&&d.url!==o.url&&(d.byteRange.length>0?u.nor=[Kd(d.url,{r:`${d.byteRange[0]}-${d.byteRange[1]}`})]:u.nor=[d.url]),this.apply(i,u)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(i,r,a)=>{var o;const{cmcd:l}=this.config,c=l==null||(o=l.eventTargets)==null?void 0:o.some(h=>{var u;return(u=h.events)==null?void 0:u.includes(js.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!c))try{this.reporter.recordResponseReceived({request:{url:i},status:r.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(h){this.hls.logger.warn("Could not record fragment response CMCD data.",h)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:s}=this.config;if(s==null)return;const i=s.version||Md;if(this.reporter=new Gd({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:s.useHeaders===!0?Do:hr,enabledKeys:(e=s.includeKeys)!=null?e:[...i>=us?cr:zs],eventTargets:((t=s.eventTargets)!=null?t:[]).map(r=>{let{includeKeys:a}=r,o=ms(r,Hd);return z(z({},o),{},{enabledKeys:a??cr})})},s.loader),this.reporter.update({sf:Vd.HLS,sta:this.playerState}),s.reporterCallback){const r=this.reporter,a={updateCustomData:o=>{ko(o)&&r.update(o)},recordCustomEvent:(o,l={})=>{ko(l)&&r.recordEvent(js.CUSTOM_EVENT,z({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(p.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(p.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const s=this.media=t.media;this.setPlayerState(this.media.autoplay?Xe.STARTING:Xe.PRELOADING),he(s,"waiting",this.onWaiting),he(s,"play",this.onPlay),he(s,"playing",this.onPlaying),he(s,"pause",this.onPause),he(s,"seeking",this.onSeeking),he(s,"seeked",this.onSeeked),he(s,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(ce(e,"waiting",this.onWaiting),ce(e,"play",this.onPlay),ce(e,"playing",this.onPlaying),ce(e,"pause",this.onPause),ce(e,"seeking",this.onSeeking),ce(e,"seeked",this.onSeeked),ce(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Xe.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Xe.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Xe.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(js.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;const i={br:[t.bitrate/1e3]},r=(s=t.details)==null?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,t)),this.reporter.recordEvent(js.BITRATE_CHANGE,i)}onLevelSwitched(e,t){const s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?ur.LOW_LATENCY:ur.LIVE:ur.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});const i=t.ot===Re.INIT||t.ot===Re.VIDEO||t.ot===Re.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=i;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===s&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e,t){const{type:s}=e;if(s==="subtitle")return Re.TIMED_TEXT;if(e.sn==="initSegment")return Re.INIT;if(s==="audio")return Re.AUDIO;if(s==="main"){if(e.hasStreams){const i=e.elementaryStreams;if(i.audiovideo)return Re.MUXED;if(i.video)return Re.VIDEO;if(i.audio)return Re.AUDIO}if(t){const{audioCodec:i,videoCodec:r}=t;if(!this.hls.audioTracks.length){if(i&&r)return Re.MUXED;if(i)return Re.AUDIO}if(r)return Re.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),B(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;const s=e||t;return s?s.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const s=this.getEventBufferLength();B(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=this.recordFragmentResponse,i=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new i(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);const{onSuccess:c}=l;this.loader.load(a,o,z(z({},l),{},{onSuccess:(h,u,d,f)=>{c(h,u,d,f),s(a.url,h,u)}}))}}}}const Wd=3e5;class jd extends Ue{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===be.SendAlternateToPenaltyBox&&s.flags&xe.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a,!s.resolved&&(t.details!==b.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${fe(r)} penalized: ${fe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Wd&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,ya(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===se.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===se.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new Ae(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Mo(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Jt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let A=1;A<h.audioGroups.length;A++)m.addGroupId("audio",`${h.audioGroups[A]}_clone_${a}`);if(h.subtitleGroups)for(let A=1;A<h.subtitleGroups.length;A++)m.addGroupId("text",`${h.subtitleGroups[A]}_clone_${a}`);return m});t.push(...c),wo(this.audioTracks,s,l,a),wo(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;yt(i,"_HLS_pathway",this.pathwayId),yt(i,"_HLS_throughput",""+h)}const r={type:se.STEERING_MANIFEST,responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":A,"PATHWAY-PRIORITY":I}=g;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),A&&this.clonePathways(A);const y={steeringManifest:g,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,y),I&&this.updatePathwayPriority(I)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const A=m.getResponseHeader("Retry-After");A&&(g=parseFloat(A)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function wo(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=ue({},a);return o.details=void 0,o.attrs=new Ae(o.attrs),o.url=o.attrs.URI=Mo(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Mo(n,e,t,s){if(e){const{[t]:o}=s;if(o){const l=o[e];if(l)return l}}const{HOST:i,PARAMS:r}=s,a=new self.URL(n);return i&&(a.hostname=i),r&&Object.keys(r).sort().forEach(o=>{o&&yt(a,o,r[o])}),a.href}class zd{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Gi,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();const e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class Ze extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class Vt extends Ue{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=Vt.CDMCleanupPromise?[Vt.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.log(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ss(this.config));const o=a.map(Mi).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o;const l=Os(a),c=this.activeLevelKeys();if(l===me.FAIRPLAY&&s==="sinf")try{const g=ze(new Uint8Array(i)),m=pi(JSON.parse(g).sinf),A=hn(m);if(!A)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(A.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}else if(l===me.PLAYREADY)o=Oi(new Uint8Array(i));else if(l===me.WIDEVINE){const g=mn(i).filter(m=>m.systemId===ea.WIDEVINE);if(g.length){var h;const m=g[0];o=(h=m.kids)!=null&&h.length?m.kids[0]:null}}let u;if(o){const g=Ee(o);for(let m=0;m<c.length;m++){const A=c[m];if(A.keyId&&(ws(o,A.keyId)||A.uri.replace(/-/g,"").indexOf(g)!==-1)){A.pssh||(A.scheme=s,A.pssh=new Uint8Array(i),A.keyId=o,dt.setKeyIdForUri(A.uri,o)),u=this.getSessionForKey(A,"encrypted-event-key-match");break}}}if(!u){if(c.length){var d,f;return(d=c[0]).scheme||(d.scheme=s),(f=c[0]).pssh||(f.pssh=new Uint8Array(i)),this.getSessionForKey(c[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ee(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return u}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof Ze?o(u):o(new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return ta===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=ph(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fe(r)}`),o=this.requestMediaKeySystemAccess(e,r);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.throwIfDestroyed(),this.log(`Access for key-system "${c.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,s,i){const{mediaKeySessions:r}=this,a=` key-session "${e}" keyId: ${Ee(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let c=0;c<r.length;c++){const h=r[c];if(!h.initialized&&h.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),h}this.log(`Creating${a}`);const o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(l),l}resetMediaKeys(){var e;const t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ee(t.keyId||[])}
|
|
179
|
+
} (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Mi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{const s=Mi(t);if(!s)throw new Error(`Unable to find format for key-system "${t}"`);return s})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=ss(this.config),s=e.map(Os).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}loadClear(e,t,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const a=t[i];if(e.cc<=a.cc&&(!Ie(e)||!Ie(a)||e.sn<a.sn)||!s&&i==r-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);const l=Os(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const i=ss(this.config);if(i.length)return this.getKeySystemAccess(i)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=dr(e,t[s]);if(i)return i}}loadKey(e){const t=e.decryptdata,s=this.getKeyStatus(t);if(s==="internal-error"){const o=Oo(s,t);return o.data.frag=e,this.error(`${o.message} (${Ee(t.keyId||[])})`),Promise.reject(o)}const i=e.type,r=this.activeKeys,a=r[i];a&&!t.matches(a.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(a),delete r[i]),r[i]||(r[i]=e);for(let o=this.mediaKeySessions.length;o--;){const l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ee(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,s){const i=this.getSessionForKey(e,t);return i.catch(r=>this.handleError(r,s)),i.then(r=>e)}getSessionForKey(e,t){const s=this.findContextForKey(e);if(s!==void 0)return Promise.resolve(s);const i=e.uri,r=this.sessionSetupByUri[i];let a;r===void 0?a=this.resolveSessionForKey(e,t):a=r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[i]=a;const o=()=>{this.sessionSetupByUri[i]===a&&delete this.sessionSetupByUri[i]};return a.then(o,o),a}findContextForKey(e){const{mediaKeySessions:t}=this;for(let s=t.length;s--;){const i=t[s];if(dr(e,i))return i}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let r=this.mediaKeySessions.length;r--;){const a=this.mediaKeySessions[r];if(dr(e,a))return a;const o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,e,t))).then(r=>{this.throwIfDestroyed();const a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(r,e,a,o,t)})})}getUsableKeyPromise(e,t,s){const i=e.keyRequests[t.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${Zd(t)} format: "${t.keyFormat}" URI: ${t.uri})`),i.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ze){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ee(s.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,e.data)}else this.error(e.message),this.hls.trigger(p.ERROR,{type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Os(e.keyFormat),s=t?[t]:ss(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=ss(this.config)),e.length===0)throw new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(s=>s.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}filterInitData(e,t,s,i,r){var a;const o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const c=o.call(this.hls,s,i,ue({},e,{decryptdata:t,reason:r}),r);if(!c)throw new Error("Invalid response from configured generateRequest filter");t.scheme=c.initDataType?c.initDataType:"cenc";const h=c.initData?c.initData:null;return t.pssh=h?new Uint8Array(h):null,c}catch(c){var l;if(this.warn(c.message),(l=this.hls)!=null&&l.config.debug)throw c}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(e,t,s,i,r){const a=this.getUsableKeyPromise(e,t,r);if(a)return a;const o=this.filterInitData(e,t,s,i,r);if(o&&(i=o.initData?o.initData:null,s=o.initDataType),i===null)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));const l=t.uri,c=new zd;e.keyRequests[l]=c;const h=d=>{const f=e.mediaKeysSession;if(!f){const A=new Error("invalid state");c.errored=A;return}const{messageType:g,message:m}=d;c.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(A=>{c.errored=A,c.hasListeners||this.handleError(A),this.removeSession(e)}):g==="license-release"?e.keySystem===me.FAIRPLAY&&this.updateKeySession(e,t,wi("acknowledged")).then(()=>this.removeSession(e)).catch(A=>this.handleError(A)):this.warn(`unhandled media key message type "${g}"`)};return c.onmessage=h,he(e.mediaKeysSession,"message",h),this.generateRequest(e,t,s,i,r,!1)}generateRequest(e,t,s,i,r,a){if(a){const f=this.filterInitData(e,t,s,i,r);f&&(i=f.initData?f.initData:i,s=f.initDataType)}const o=t.uri,l=e.keyRequests[o],c=Ee(t.keyId||[]),h=f=>{let g;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=Oo(f,t):f==="expired"?g=new Error(`key expired (keyId: ${c})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${c})`),g&&(l.errored=g,l.hasListeners||this.handleError(g))},u=f=>{if(!e.mediaKeysSession){const v=new Error("invalid state");l.errored=v;return}const m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(v=>m[v]!=="status-pending"))return;const I=this.activeLevelKeys();for(let v=0;v<I.length;v++){const T=Ee(I[v].keyId||[]);if(m[T]==="expired"){var y;this.log(`Expired key ${fe(m)} in key-session "${(y=e.mediaKeysSession)==null?void 0:y.sessionId}"`),this.renewKeySession(t,e).catch(S=>this.handleError(S));break}}let C=m[c];if(C)h(C);else{var E;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(E=e.keyStatusTimeouts)[c]||(E[c]=self.setTimeout(()=>{var T;if(!e.mediaKeysSession)return;const S=this.getKeyStatus(t);if(S&&S!=="status-pending"){var L;return this.log(`No status for keyId ${c} in key-session "${(L=e.mediaKeysSession)==null?void 0:L.sessionId}". Using session key-status ${S} from other session.`),h(S)}this.log(`key status for ${c} in key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}" timed out after 1000ms`),C="internal-error",h(C)},1e3)),this.log(`No status for keyId ${c} (${fe(m)}).`)}};l.onkeystatuseschange=u,he(e.mediaKeysSession,"keystatuseschange",u);const d=l.useable;return this.log(`Generating key-session request for "${r}" keyId: ${c} URI: ${o} (init data type: ${s} length: ${i.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,i).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);const m=(g=f.data)==null?void 0:g.details;return(m===b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===b.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(A=>e.keyStatuses[A]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){const t={},s=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){const l=r;r=i,i=l}const a="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===me.PLAYREADY&&a.length===16){const l=Ee(a);t[l]=i,Qn(a)}const o=Ee(a);this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${s}"`),t[o]=i}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=Xd(e,t);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={type:se.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:z({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(l,h,u)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(i=>this.updateKeySession(e,t,new Uint8Array(i)).catch(r=>{throw new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){const s=ze(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=i.querySelector("Challenge"),c=l?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return wi(atob(c))}setupLicenseXHR(e,t,s,i,r){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,z(z({},s),{},{decryptdata:i}),r))).catch(o=>{if(!s.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,z(z({},s),{},{decryptdata:i}),r)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,s){return new Promise((i,r)=>{const a=qd(e.keySystem,this.config);if(!a)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const o=e.keyRequests[t.uri];if(!o)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);const l=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType="arraybuffer",c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(c.readyState===4)if(c.status===200){o.requestErrors=[];let h=c.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const u=this.config.licenseResponseCallback;if(u)try{h=u.call(this.hls,c,a,z(z({},e),{},{decryptdata:t}))}catch(d){this.error(d)}i(h)}else{const h=l.errorRetry,u=h?h.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>u||c.status>=400&&c.status<500)r(new Ze({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:c,response:{url:a,data:void 0,code:c.status,text:c.statusText}},`License Request XHR failed (${a}). Status: ${c.status} (${c.statusText})`));else{const d=u-o.requestErrors.length;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t,s).then(i,r)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,s).then(({xhr:h,licenseChallenge:u})=>{e.keySystem==me.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(h,u)),h.send(u)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,he(s,"encrypted",this.onMediaEncrypted),he(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(ce(e,"encrypted",this.onMediaEncrypted),ce(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,dt.clearKeyUriToKeyIdMap();const r=i.length;Vt.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{const l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(o=>self.clearTimeout(i[o]));const{drmSystemOptions:r}=this.config;return(Ih(r)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}Vt.CDMCleanupPromise=void 0;function qd(n,e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?.[n];if(i)return i.licenseUrl;if(n===me.WIDEVINE&&s)return s}function Xd(n,e){const{drmSystems:t}=e,s=t?.[n];if(s)return s.serverCertificateUrl}function Zd(n){if(n.keyFormat===Le.FAIRPLAY)return n.uri;if(n.keyId===null)throw new Error("keyId is null");return Ee(n.keyId)}function dr(n,e){const t=n.keyId,s=e.mediaKeysSession;if(t&&s){const i=e.mediaKeysSession.keyStatuses;if(i.size)return i.has(t)?i.get(t):e.keyStatuses[Ee(t)]}}function Oo(n,e){const t=n==="output-restricted",s=t?b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:b.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ze({type:W.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}class Qd{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var fr=(function(){if(Ms!=null&&Ms.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,m=l,A=c,I=null,y="",C=!0,E="auto",v="start",T=50,S="middle",L=50,R="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(x){d=""+x}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(x){f=!!x}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(x){if(typeof x!="number")throw new TypeError("Start time must be set to a number.");g=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return m},set:function(x){if(typeof x!="number")throw new TypeError("End time must be set to a number.");m=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return A},set:function(x){A=""+x,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return I},set:function(x){I=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return y},set:function(x){const P=s(x);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return C},set:function(x){C=!!x,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return E},set:function(x){if(typeof x!="number"&&x!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");E=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return v},set:function(x){const P=i(x);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");v=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return T},set:function(x){if(x<0||x>100)throw new Error("Position must be between 0 and 100.");T=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return S},set:function(x){const P=i(x);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");S=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return L},set:function(x){if(x<0||x>100)throw new Error("Size must be between 0 and 100.");L=x,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return R},set:function(x){const P=i(x);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");R=P,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Jd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Fo(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class ef{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function No(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const gr=new fr(0,0,""),qs=gr.align==="middle"?"middle":"center";function tf(n,e,t){const s=n;function i(){const o=Fo(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new ef;No(o,function(d,f){let g;switch(d){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){c.set(d,t[m].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",!1),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",qs,"end"]);break;case"position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",qs,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",qs,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&gr.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",qs);let u=c.get("position","auto");u==="auto"&&gr.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function Bo(n){return n.replace(/<br(?: \/)?>/gi,`
|
|
180
|
+
`)}class sf{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Jd,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=Bo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
|
|
181
|
+
`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
|
|
182
|
+
`&&++a,t.buffer=r.slice(a),o}function i(r){No(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new fr(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{tf(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
183
|
+
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
382
184
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
${this.showTimeDisplay?'<span class="time-display duration">0:00</span>':""}
|
|
388
|
-
</div>
|
|
389
|
-
<div id="controls-row">
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
185
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}function ds(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const rf=/\r\n|\n\r|\n|\r/g,Uo="Missing initPTS for VTT ",nf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!B(t)||!B(s)||!B(i)||!B(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function mr(n,e,t){return ds(n.toString())+ds(e.toString())+ds(t)}function af(n,e,t,s,i,r,a){const o=new sf,l=$e(new Uint8Array(n)).trim().replace(rf,`
|
|
186
|
+
`).split(`
|
|
187
|
+
`),c=[],h=e?Cu(e.baseTime,e.timescale):0;let u="00:00.000",d=0,f=0,g=!1,m,A=!0;o.oncue=function(I){const y=t[s];let C=t.ccOffset;const E=(d-h)/9e4;if(g){if(y!=null&&y.new&&(C=t.ccOffset=y.start),E){if(!e){m=new Error(Uo+"MPEGTS");return}C=E-t.presentationOffset}}else if(e)C=-e.baseTime/e.timescale;else{m=new Error(Uo+"without X-TIMESTAMP-MAP");return}const v=I.endTime-I.startTime,T=Ge((I.startTime+C-f)*9e4,i*9e4)/9e4;I.startTime=Math.max(T,0),I.endTime=Math.max(T+v,0);const S=I.text.trim();I.text=decodeURIComponent(encodeURIComponent(S)),I.id?s&&(I.id=`hlsjscc${s}_${I.id}`):I.id=mr(I.startTime,I.endTime,S),I.endTime>0&&c.push(I)},o.onparsingerror=function(I){m=I},o.onflush=function(){if(m){a(m);return}r(c)},l.forEach(I=>{if(A)if(I.startsWith("X-TIMESTAMP-MAP=")){A=!1,g=!0,I.slice(16).split(",").forEach(y=>{y.startsWith("LOCAL:")?u=y.slice(6):y.startsWith("MPEGTS:")&&(d=parseInt(y.slice(7)))});try{f=nf(u)/1e3}catch(y){m=y}return}else I===""&&(A=!1);o.parse(I+`
|
|
188
|
+
`)}),o.flush()}const pr="stpp.ttml.im1t",$o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Go=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,of={left:"start",center:"center",right:"end",start:"start",end:"end"};function Vo(n,e,t,s){const i=J(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>$e(o)),a=Iu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(lf(o,a)))}catch(o){s(o)}}function lf(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));const o=i.getAttribute("xml:space")!=="preserve",l=Ko(Ar(i,"styling","style")),c=Ko(Ar(i,"layout","region")),h=Ar(i,"body","[begin]");return[].map.call(h,u=>{const d=Ho(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=Cr(u.getAttribute("begin"),a),g=Cr(u.getAttribute("dur"),a);let m=Cr(u.getAttribute("end"),a);if(f===null)throw Yo(u);if(m===null){if(g===null)throw Yo(u);m=f+g}const A=new fr(f-e,m-e,d);A.id=mr(A.startTime,A.endTime,A.text);const I=c[u.getAttribute("region")],y=l[u.getAttribute("style")],C=cf(I,y,l),{textAlign:E}=C;if(E){const v=of[E];v&&(A.lineAlign=v),A.align=E}return ue(A,C),A}).filter(u=>u!==null)}function Ar(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Ko(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Ho(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
|
|
189
|
+
`:(r=s.childNodes)!=null&&r.length?Ho(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function cf(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,l)=>{const c=Ir(e,s,l)||Ir(n,s,l)||Ir(i,s,l);return c&&(o[l]=c),o},{})}function Ir(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Yo(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Cr(n,e){if(!n)return null;let t=Fo(n);return t===null&&($o.test(n)?t=hf(n,e):Go.test(n)&&(t=uf(n,e))),t}function hf(n,e){const t=$o.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function uf(n,e){const t=Go.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}function yr(n,e,t,s="",i="disabled"){const r=n.ownerDocument.createElement("track");return r.kind=e,r.label=t,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=i,n.appendChild(r),r}function df(n){return n.forced&&Lc()?"forced":n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Er(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){le.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){le.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function vr(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=gf(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function ff(n,e){if(e<=n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function gf(n,e,t){const s=[],i=ff(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}class mf extends Xi{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,s=!1;if(this.currentTrack){var i;const o=(i=this.currentTrack.trackNode)==null?void 0:i.track.mode;o==="showing"?(t=this.trackId,s=!0):o==="hidden"&&(t=this.trackId)}if(!s)for(let o=0;o<this.tracksInGroup.length;o++){var r;const l=(r=this.tracksInGroup[o].trackNode)==null?void 0:r.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=yr(this.media,df(s),s.name,s.lang))});const t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const s=t.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!i&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(r=>{const a=r.trackNode;a&&(a.track.mode="hidden",a.remove(),r.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s;const a=[];if(this.tracks.forEach(h=>{(h.textCodec===pr?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(h.groupId)>-1?(h.id=a.length,a.push(h)):h.trackNode&&(h.trackNode.remove(),h.trackNode=void 0))}),a.length===this.tracksInGroup.length){let h=!1;for(let u=0;u<a.length;u++)if(a[u]!==this.tracksInGroup[u]){h=!0;break}if(!h)return}a.length&&this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=nt(o,a);if(h>-1)r=a[h];else{const u=nt(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||bt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(hs(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(hs(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===se.SUBTITLE_TRACK&&t.context.id===this.trackId&&es(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&bt(e,s))return s;const i=nt(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),r}else{if(s)return null;{const r=nt(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=t.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(e,t=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!B(e)){this.warn(`Invalid subtitle track id: ${e}`);return}const i=this.currentTrack,r=s[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r){i&&this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!r.details&&!r.details.live;if(r===i&&a)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:c,type:h,url:u}=r;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:c,type:h,url:u});const d=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(d)}}const Xs=2,pf=100;class Af extends Hn{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(pf),this.mediaSource=t.mediaSource;const s=this.media=t.media;he(s,"playing",this.onMediaPlaying),he(s,"waiting",this.onMediaWaiting),he(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(ce(s,"playing",this.onMediaPlaying),ce(s,"waiting",this.onMediaWaiting),ce(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(h){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!X.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}const u=X.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&zo(u,e,d,this.hls);const f=u.nextStart||0;if(o&&d&&this.hls){const T=Wo(this.hls.inFlightFragments,e),S=u.len>Xs,L=!f||T||f-e>Xs&&!d.getPartialFragment(e);if(S||L)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&d){if(!(u.len>0)&&!f)return;const S=Math.max(f,u.start||0)-e,R=!!(g!=null&&g.live)?g.targetduration*2:Xs,x=fs(e,d);if(S>0&&(S<=R||x)){a.paused||this._trySkipBufferHole(x);return}}const m=r.detectStallWithCurrentTimeMs,A=self.performance.now(),I=this.waiting;let y=this.stalled;if(y===null)if(I>0&&A-I<m)y=this.stalled=I;else{this.stalled=A;return}const C=A-y;if(!o&&(C>=m||I&&this.moved)&&this.hls){var E;if(((E=this.mediaSource)==null?void 0:E.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-(g?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return;if(a.currentTime!==e){const T=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${T} > ${e}`);return}}const v=X.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(v,C,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=X.timeRangesToArray(i),o=X.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=X.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=fs(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=X.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:a,media:o}=this,l=(i=this.hls)==null?void 0:i.config;if(!o||!a||!l)return;const c=(r=this.hls)==null?void 0:r.latestLevelDetails,h=fs(s,a);if((h||c!=null&&c.live&&s<c.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,H.MAIN),a=s.getFragAtPos(i,H.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${fe(e)})`);this.warn(a.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:s,hls:i}=this,r=i?.config;if(!s||!t||!r)return 0;const a=s.currentTime,o=X.bufferInfo(s,a,0);zo(o,a,t,i);const l=a<o.start?o.start:o.nextStart;if(l){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&s.readyState<3,d=l-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let I=!1;if(a===0){const y=t.getAppendedFrag(0,H.MAIN);y&&l<y.end&&(I=!0)}if(!I&&e){var c;if(!((c=i.loadLevelObj)!=null&&c.details)||Wo(i.inFlightFragments,l))return 0;let C=!1,E=e.end;for(;E<l;){const v=fs(E,t),T=v?v.duration:0;if(T>0)E+=T;else{C=!0;break}}if(C)return 0}}const{nudgeMaxRetry:f,skipBufferHolePadding:g}=r,m=++this.skipRetry>f,A=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${A}`),this.moved=!0,s.currentTime=A),!(e!=null&&e.gap)||m){const I=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${A} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${A}`),y={type:W.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:m,error:I,reason:I.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?y.part=e:y.frag=e),i.trigger(p.ERROR,y)}return A}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=a+(i+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Wo(n,e){const t=jo(n.main);if(t&&t.start<=e)return t;const s=jo(n.audio);return s&&s.start<=e?s:null}function jo(n){if(!n)return null;switch(n.state){case D.IDLE:case D.STOPPED:case D.ENDED:case D.ERROR:return null}return n.frag}function fs(n,e){return e.getAppendedFrag(n,H.MAIN)||e.getPartialFragment(n)}function zo(n,e,t,s){const i=s.latestLevelDetails,r=fs(e,t);if(Bs(s.config)&&!n.nextStart&&i&&r&&s.interstitialsManager){const a="type"in r?r:r.fragment,o=Fn(i,a.sn);o?.level===a.level&&Sa(o,s.interstitialsManager.playerQueue,e)&&(n.nextStart=o.start)}}const If=.25;function Tr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Sr(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,fe(i?z({type:i},s):s))}return r}const Zs=(()=>{const n=Tr();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Cf{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return yr(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Tr();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===_e.emsg&&!s||!i)continue;const c=Qr(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>Zs&&(u=Zs),u-h<=0&&(u=h+If);for(let f=0;f<c.length;f++){const g=c[f];if(!Jr(g)){this.updateId3CueEnds(h,l);const m=Sr(a,h,u,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.track.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===Zs&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;i==="audio"?c=h=>h.type===_e.audioId3&&l:i==="video"?c=h=>h.type===_e.emsg&&o:c=h=>h.type===_e.audioId3&&l||h.type===_e.emsg&&o,vr(r.track,t,s,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Tr();if(s&&i&&!a){const{fragmentStart:m,fragmentEnd:A}=e;let I=this.assetCue;I?(I.startTime=m,I.endTime=A):o&&(I=this.assetCue=Sr(o,m,A,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),I&&(I.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(I),I.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c);let u=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.track.cues)!=null&&d.length){const m=Object.keys(u).filter(A=>h.indexOf(A)===-1);for(let A=m.length;A--;){var f;const I=m[A],y=(f=u[I])==null?void 0:f.cues;delete u[I],y&&Object.keys(y).forEach(C=>{const E=y[C];if(E){E.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(E)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(h.length===0||!B(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<h.length;m++){const A=h[m],I=c[A],y=I.startTime,C=u[A],E=C?.cues||{};let v=C?.durationKnown||!1,T=Zs;const{duration:S,endDate:L}=I;if(L&&S!==null)T=y+S,v=!0;else if(I.endOnNext&&!v){const x=h.reduce((P,_)=>{if(_!==I.id){const F=c[_];if(F.class===I.class&&F.startDate>I.startDate&&(!P||I.startDate<P.startDate))return F}return P},null);x&&(T=x.startTime,v=!0)}const R=Object.keys(I.attr);for(let x=0;x<R.length;x++){const P=R[x];if(!dh(P))continue;const _=E[P];if(_)v&&!(C!=null&&C.durationKnown)?_.endTime=T:Math.abs(_.startTime-y)>.01&&(_.startTime=y,_.endTime=T);else if(o){let F=I.attr[P];fh(P)&&(F=en(F));const U=Sr(o,y,T,{key:P,data:F},_e.dateRange);U&&(U.id=A,this.id3Track.track.addCue(U),E[P]=U,a&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}u[A]={cues:E,dateRange:I,durationKnown:v}}}}}function qo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Xo(){if(!Ct())return!1;const e=qo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function yf(){if(!Xo())return!1;const n=Ct();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Qt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Qt(e,"audio"))))}function Ef(){var n;const e=qo();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}var ht={DISABLED:0,SWITCHING:1,SWITCHED:2};const vf=100;let Zo=class extends Ui{constructor(e,t,s){super(e,t,s,"stream-controller",H.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=ht.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!B(r)||(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(i,r,H.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(vf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=D.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=D.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case D.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=D.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=D.IDLE;break}break}case D.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===D.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={type:this.targetBufferType()};this.hls.trigger(p.BUFFER_EOS,m),this.state=D.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||this.state===D.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=D.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ie(f)&&this.fragmentTracker.getState(f)!==pe.OK){var g;const A=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,I=c.fragments[A-1];I&&f.cc===I.cc&&(f=I,this.fragmentTracker.removeFragment(I))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const A=this.audioOnly&&!this.altAudio?de.AUDIO:de.VIDEO,I=(A===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;I&&this.afterBufferFlushed(I,A)}f=this.getNextFragmentLoopLoading(f,c,o,H.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===pe.NOT_LOADED||i===pe.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==ht.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===ht.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const s=this.fragPlaying;if(s){const i=s.level;this.hls.trigger(p.FRAG_CHANGED,{frag:s,previousFrag:e}),e?.level!==i&&this.hls.trigger(p.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===ht.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;he(s,"playing",this.onMediaPlaying),he(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(ce(s,"playing",this.onMediaPlaying),ce(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=ht.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Ef(),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:s}=this;if(!s||this.state!==D.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=D.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=t.levelInfo,h=this.fragCurrent;h&&(this.state===D.FRAG_LOADING||this.state===D.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=c.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,r||this.setStartPosition(o,u),this.hls.trigger(p.LEVEL_UPDATED,{details:o,level:a}),this.state===D.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=D.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i}`),this.config.liveSyncMode==="buffered"){var c;const u=X.bufferInfo(s,i,0);if(!((c=u.buffered)!=null&&c.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:f}=X.bufferedInfo(u.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Xa(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,m=g!==-1,{decryptRange:A,byteRange:I}=_s(s,i,this.iframesOnly),y=new Di(s.level,s.sn,s.stats.chunkCount,I?I.end-I.start:r.byteLength,g,m,s.duration,this.iframesOnly,A),C=this.initPTS[s.cc];f.push(r,u,d,c,s,i,l.totalduration,h,y,C)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==ht.DISABLED;if(Ds(t.url,s))this.altAudio=ht.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=ht.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),s.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ds(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?ht.SWITCHED:ht.DISABLED,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===H.MAIN;if(r){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}`),this.state===D.PARSED&&(this.state=D.IDLE);return}let l=!1;if(Ie(s)&&(l=!!s.gap&&!s.tagList.some(c=>c[0]==="GAP")),this.fragBufferedComplete(s,i),l){var a;s.stats.retry++;const c=(a=this.levels)==null?void 0:a[s.level];c&&c.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&X.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=D.ERROR;return}switch(t.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===D.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===se.LEVEL&&(this.state=D.IDLE);break;case b.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case b.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=D.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==de.AUDIO||!this.altAudio){const s=(t===de.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),a=X.getBuffered(e),o=a.length?a.start(0):0,l=o-s,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=D.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===D.STOPPED||this.state===D.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=i,{details:g}=c,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=D.PARSING,f){const A=f.tracks;if(A){const E=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,A,E,r),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:t,tracks:A})}const I=f.initPTS,y=f.timescale,C=this.initPTS[o.cc];if(B(I)&&(!C||C.baseTime!==I||C.timescale!==y)){const E=f.trackId;this.initPTS[o.cc]={baseTime:I,timescale:y,trackId:E};const v=this.initPTS.slice(0);s.trigger(p.INIT_PTS_FOUND,{timestampOffsets:v,frag:o,id:t,initPTS:I,timescale:y,trackId:E})}}if(h&&g){m&&h.type==="audiovideo"&&this.logMuxedErr(o);const A=g.fragments[o.sn-1-g.startSN],I=o.sn===g.startSN,y=!A||o.cc>A.cc;if(i.independent!==!1){const{startPTS:C,endPTS:E,startDTS:v,endDTS:T}=h;if(l)l.elementaryStreams[h.type]={startPTS:C,endPTS:E,startDTS:v,endDTS:T};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!y&&(this.couldBacktrack=!0),h.dropped&&h.independent){const S=this.getMainFwdBufferInfo(),L=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,R=h.firstKeyFramePTS?h.firstKeyFramePTS:C;if(!I&&L<R-this.config.maxBufferHole&&!y){this.backtrack(o);return}else y&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,E,o.start,T,!0)}else I&&C-(g.appliedTimelineOffset||0)>Xs&&(o.gap=!0);o.setElementaryStreamInfo(h.type,C,E,v,T),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,I||y)}else if(I||y)o.gap=!0;else{this.backtrack(o);return}}if(m){const{startPTS:A,endPTS:I,startDTS:y,endDTS:C}=m;l&&(l.elementaryStreams[de.AUDIO]={startPTS:A,endPTS:I,startDTS:y,endDTS:C}),o.setElementaryStreamInfo(de.AUDIO,A,I,y,C),this.bufferFragmentData(m,o,l,r)}if(g&&d!=null&&d.samples.length){const A={id:t,frag:o,details:g,samples:d.samples};s.trigger(p.FRAG_PARSING_METADATA,A)}if(g&&u){const A={id:t,frag:o,details:g,samples:u.samples};s.trigger(p.FRAG_PARSING_USERDATA,A)}}logMuxedErr(e){this.warn(`${Ie(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==D.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:a,audiovideo:o}=t;if(r){const c=e.audioCodec;let h=bs(r.codec,c);if(h==="mp4a"&&(h="mp4a.40.5"),this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&!bc()&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&Rc()&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),c&&c!==h&&this.log(`Swapping manifest audio codec "${c}" for "${h}"`),r.levelCodec=h,r.id=H.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=H.MAIN;const c=a.codec;if(c?.length===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const u=t[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:c,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,H.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=D.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return B(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(B(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?Ft(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const a=r+(t-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}};class Qo extends Zo{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:s}=t,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case D.STOPPED:case D.ENDED:case D.ERROR:this.state=D.IDLE}this.state===D.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(p.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){const t=this.media;if(t){var s;const i=(s=this.getLevelDetails())==null?void 0:s.edge,r=i!==void 0?i:t.duration;if(e>=r&&(e=r-.01),X.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const r=s.shift();if(r.data)this.cachedSize-=r.data.byteLength,r.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:s,payload:i}=e;this.cacheFragmentData&&!s&&i!=null&&i.byteLength&&!t.data&&Ie(t)&&this.cacheSet(t,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if((i===pe.NOT_LOADED||i===pe.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,s)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;const s=e.decryptdata;return s?.keyFormat!=="identity"||!!s.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const s=e.stats=new oi;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=D.FRAG_LOADING;const i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(p.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=D.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Ns(X.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,t){if(t){const s=this.media;if(s){const i=X.bufferInfo(s,e,0),r=i.len?i.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,H.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(p.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(p.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||i||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,H.MAIN);return!!(t!=null&&t.endList)}}class Tf extends Qo{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const s=(t=this._img)==null?void 0:t.src;s&&self.URL.revokeObjectURL(s),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case D.STOPPED:case D.ENDED:case D.ERROR:this.state=D.IDLE}if(this.state===D.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===D.IDLE){const s=this.getBufferedAt(e);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{const s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){const i=e.data;i||this.fragmentTracker.removeFragment(e);const r=this._img;if(r&&i){const a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,r.onload=()=>{if(!this.hls)return;const h=this.hls.levels[e.level];h!=null&&h.fragmentError&&(h.fragmentError=0,e.stats.retry=0);const u=self.performance.now(),d=t?t.stats:e.stats;d.buffering.end=e.stats.buffering.end=u,this.hls.trigger(p.FRAG_BUFFERED,{frag:e,part:t,stats:d,id:e.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",e,t,s)};const l=r.src;l&&self.URL.revokeObjectURL(l);const c=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(c)}else this.state=D.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,i){if(!this.hls)return;const r=new Error(e);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,s,i){super.bufferFragmentData(e,t,s,i,!0);const r=J(new Uint8Array(e.data1),["mdat"]);if(r.length===0){this.handleError("Could not find I-Frame mdat",t,s,i);return}const a=t;this.cacheSet(a,r[0]),this.updateImage(a,s,i)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){const s=this.getAppendedFrag(t);if(s&&!Ht(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const Sf=10,xf="Image I-Frame player does not accept HTMLMediaElements",Jo={seekOnAppend:!0};let Qs,xr;class bf extends Ue{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Qs||(Qs=Lf(t)),xr||(xr=Rf(Qs)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MANIFEST_LOADING,this.clearAsset,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.clearAsset,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var s;const i=(s=this.hls)==null?void 0:s.pathwayPriority;t.length&&i&&this.iframeInstances.forEach(r=>{r.pathwayPriority=i})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===H.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;const i=this.hls;i&&i.hasEnoughToStart&&(((s=i.mainForwardBufferInfo)==null?void 0:s.len)||0)>Sf&&this.iframeInstances.forEach(r=>{if(!r.loadingEnabled){var a;r.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Qs,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const s=(t=this.hls)==null?void 0:t.iframeVariants.filter(i=>i.imageCodec);return this.createInstance(xr,s,e,"image-")}createInstance(e,t,s,i){const{hls:r}=this;if(!r)return null;const{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:c,loadLevel:h,bandwidthEstimate:u,sessionId:d}=r,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;const m=`${i||""}iframe-player-${this.instanceCounter++}`,A=r.levels,I=c||A[h],y=kn(I,o.videoPreference),C=I?.pathwayId||".",E=z(z({},o),{},{loggerId:m,primarySessionId:d,videoPreference:y,abrEwmaDefaultEstimate:u,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),v=new e(E,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(T=>!T.url),this.iframeInstances.push(v),v.trigger(p.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:C},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),v}}function Lf(n){return class extends n{constructor(t,s,i,r){t.streamController||(t.streamController=Qo),super(t),this._url=s,this.streamController.setInitPts(i),this.streamController.initDetails=r}loadSource(){}loadMediaAt(t,s=Jo){if(t<0)return;const i=z(z({},Jo),s);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}}function Rf(n){return class extends n{constructor(t,s,i,r){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=Tf),t.capLevelController=void 0,t.bufferController=void 0,super(t,s,i,r)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(xf)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}const Tt=.025;let Js=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function Df(n,e,t){return`${n.identifier}-${t+1}-${ds(e)}`}class Pf{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 el(t,e)?ei(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=ei(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=B(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 el(t,e)?ei(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Tt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Js.Range:Js.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return _f(this)}}function ei(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<Tt)?e.start:e.start+e.duration}function el(n,e){return e>n.start-Tt&&e<n.start+n.duration+Tt}function tl(n,e,t){const s=new self.URL(n,t);return s.protocol!=="data:"&&yt(s,"_HLS_primary_id",e),s}function br(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function _f(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function Kt(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class kf{constructor(e,t,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=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};r.once(p.LEVEL_LOADED,a),r.once(p.AUDIO_TRACK_LOADED,a),r.once(p.SUBTITLE_TRACK_LOADED,a),r.on(p.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(p.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(p.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=tl(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),a=X.bufferInfo(e,r,.02);return this.getAssetTime(a.end)>=i-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=X.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Kt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Lr=.033;class wf extends Ue{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((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];t&&t!=="primary"&&(r=r[t]);const a=r.start,o=s[i].event,l=o!=null&&o.cue.pre?o.duration:r.end;if(e===a||e>a&&e<l)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const a=s[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t,s=0){const i=e.main.details,{dateRanges:r}=i,a=this.events,o=this.parseDateRanges(r,{url:i.url},t),l=Object.keys(r),c=a?a.filter(h=>l.indexOf(h.identifier)===-1):[];o.length&&o.sort((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=u.cue.pre,m=u.cue.post;if(d&&!g)return-1;if(g&&!d||f&&!m)return 1;if(m&&!f)return-1;if(!d&&!g&&!f&&!m){const A=h.startTime,I=u.startTime;if(A!==I)return A-I}return h.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,c.forEach(h=>{this.removeEvent(h)}),this.updateSchedule(e,c,s)}updateSchedule(e,t=[],s=0,i=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const a=this.items,o=this.parseSchedule(r,e,s);(i||t.length||a?.length!==o.length||o.some((c,h)=>Math.abs(c.playout.start-a[h].playout.start)>.005||Math.abs(c.playout.end-a[h].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new Pf(l,t),this.eventMap[o]=c,s===!1&&(c.appendInPlace=s)),i.push(c)}}return i}parseSchedule(e,t,s=0){const i=[],r=t.main.details,a=r.live?1/0:r.edge;let o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,h=0;if(e.forEach((u,d)=>{const f=u.cue.pre,g=u.cue.post,m=e[d-1]||null,A=u.appendInPlace,I=g?a:u.startOffset,y=u.duration,C=u.timelineOccupancy===Js.Range?y:0,E=f&&r.live?s+(u.resumeOffset||0):0,v=E||u.resumptionOffset,T=m?.startTime===I,S=I+u.cumulativeDuration;let L=A?S+y:I+v;if(f||!g&&I<=0){const x=h;h+=C,u.timelineStart=S;const P=o;o+=y,i.push({event:u,start:S,end:L,playout:{start:P,end:o},integrated:{start:x,end:h}})}else if(I<=a){if(!T){const _=I-c;if(_>Lr){const F=c,V=h;h+=_;const U=o;o+=_;const k={previousEvent:e[d-1]||null,nextEvent:u,start:F,end:F+_,playout:{start:U,end:o},integrated:{start:V,end:h}};i.push(k)}else _>0&&m&&(m.cumulativeDuration+=_,i[i.length-1].end=I)}g&&(L=S),u.timelineStart=S;const x=h;h+=C;const P=o;o+=y,i.push({event:u,start:S,end:L,playout:{start:P,end:o},integrated:{start:x,end:h}})}else return;const R=E||u.resumeTime;g||R>a?c=a:!f&&L&&u.appendInPlaceStarted&&R-L>Lr?c=L:c=R}),c<a){var l;const u=c,d=h,f=a-c;h+=f;const g=o;o+=f,i.push({previousEvent:((l=i[i.length-1])==null?void 0:l.event)||null,nextEvent:null,start:c,end:u+f,playout:{start:g,end:o},integrated:{start:d,end:h}})}this.setDurations(a,o,h)}else i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return i}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,h=o.cue.post,u=c?0:h?i:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Ft(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Lr&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=B(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Tt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;const c=Ft(null,o.fragments,s);if(!c)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(c.start-s)<Tt+h||Math.abs(c.end-s)<Tt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,i||(i=o.duration===null),r||(r=!!o.error);const c=o.error?0:o.duration||0;s+=c}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ve(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class Mf{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=tl(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(p.ERROR,f);return}t&&i.protocol!=="data:"&&yt(i,"_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),l={type:se.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},c=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{const A=d.data,I=A?.ASSETS;if(!Array.isArray(I)){const y=this.assignAssetListError(e,b.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(p.ERROR,y);return}e.assetListResponse=A,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:A,networkDetails:m})},onError:(d,f,g,m)=>{const A=this.assignAssetListError(e,b.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,m,g);this.hls.trigger(p.ERROR,A)},onTimeout:(d,f,g)=>{const m=this.assignAssetListError(e,b.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(p.ERROR,m)}};return o.load(l,h,u),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}}function sl(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function Dt(n,e){return`[${n}] Advancing timeline position to ${e}`}class Of extends Ue{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){const m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=c.timelineStart,u=c.duration||0;if(a&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,c)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],c=r.durations,h=s.map(m=>m.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
190
|
+
Schedule: ${l.map(m=>Ve(m))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(m=>{m.assetList.forEach(A=>{this.clearAssetPlayer(A.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const A=m.assetItem.timelineStart,I=m.timelineOffset-A;if(I)try{m.timelineOffset=A}catch(y){Math.abs(I)>Tt&&this.warn(`${y} ("${m.assetId}" ${m.timelineOffset}->${A})`)}}}),u||i){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(a)&&h.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Mf(e),this.schedule=new wf(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=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){ce(e,"play",this.onPlay),ce(e,"pause",this.onPause),ce(e,"seeking",this.onSeeking),ce(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;he(s,"seeking",this.onSeeking),he(s,"timeupdate",this.onTimeupdate),he(s,"play",this.onPlay),he(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,m)=>{if(u){let A=u[d].start;const I=u.event;if(I){if(d==="playout"||I.timelineOccupancy!==Js.Point){const y=s(f);y?.interstitial===I&&(A+=y.assetItem.startOffset+y[m])}}else{const y=g==="bufferedPos"?a():e[g];A+=y-u.start}return A}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const m=e.schedule.findItemIndexAtTime(u),A=(g=e.schedule.items)==null?void 0:g[m];if(A){const I=A[d].start-A.start;return u+I}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,d)=>{var f,g;const m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const A=e.effectivePlayingItem,I=e.schedule.findItemIndexAtTime(u,d),y=(g=e.schedule.items)==null?void 0:g[I],C=e.getBufferingPlayer(),E=C?.interstitial,v=E?.appendInPlace,T=A&&e.itemsMatch(A,y);if(A&&(v||T)){const S=s(e.playingAsset),L=S?.media||e.primaryMedia;if(L){const R=d==="primary"?L.currentTime:i(A,d,e.playingAsset,"timelinePos","currentTime"),x=u-R,P=(v?R:L.currentTime)+x;if(P>=0&&(!S||v||P<=S.duration)){L.currentTime=P;return}}}if(y){let S=u;if(d!=="primary"){const R=y[d].start,x=u-R;S=y.start+x}const L=!e.isInterstitial(y);if((!e.isInterstitial(A)||A.event.appendInPlace)&&(L||y.event.appendInPlace)){const R=e.media||(v?C?.media:null);R&&(R.currentTime=S)}else if(A){const R=e.findItemIndex(A);if(I>R){const P=e.schedule.findJumpRestrictedIndex(R+1,I);if(P>R){e.setSchedulePosition(P);return}}let x=0;if(L)e.timelinePos=S,e.checkBuffer();else{const P=y.event.assetList,_=u-(y[d]||y).start;for(let F=P.length;F--;){const V=P[F];if(V.duration&&_>=V.startOffset&&_<V.startOffset+V.duration){x=F;break}}}e.setSchedulePosition(I,x)}}},c=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=c(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=c(),f=e.effectivePlayingItem;f&&f===d&&l(u+f.playout.start,"playout")},get duration(){const u=c();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=c())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=c())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return c()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){return r(e.seekableStart,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const g=u.playout.start+u.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!B(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${fe(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else{const g=this.getBufferingPlayer();g?(r=g.transferMedia(),this.detachedData=r,h=`${g}`):c?h="detached MediaSource":h="detached media"}if(!r){if(c)r=this.detachedData,this.log(`using detachedData: MediaSource ${fe(r)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){const A=m.interstitial;this.clearInterstitial(m.interstitial,null),A.appendInPlace=!1,A.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${A}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed";if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!u&&!o){e.attachMedia(t);return}const d=u&&r?z({},r):{media:t},f=this.schedule;if(f&&o){const g=e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!u&&l){const g=e,m=g.assetItem.timelineStart;if(m){const A=g.hls,I=Math.max(this.timelinePos-m,Number.EPSILON);A.startPosition!==I&&(this.log(`Set ${g} startPosition: ${I}`),A.config.startPosition=I,A.loadingEnabled&&A.startLoad(I))}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}const a=s.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Dt("checkStart (preroll)",a));const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Dt("checkStart",a));const o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Dt("checkStart (playing item)",r.start));const a=e.findItemIndex(r);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=br(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!B(e.resumeOffset)&&this.hls){const s=this.getLiveStartPos();if(t){const i=this.getBufferingPlayer(),r=i!=null&&i.interstitial.cue.pre?i.remaining:0;return s+r}return s}}getNextItemIndex(e,t){if(this.schedule){const s=this.livePrerollResumption(e.event,t);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){const i=br(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const a=r[t],o=a.event?this.getNextItemIndex(a):t+1,l=r.length;if(o>=l){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(Dt("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&!r[o].event&&this.hls.startLoad(c+.01),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ve(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,d=this.playingAsset,f=d?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,r)||t!==void 0&&f!==u.assetList[t].identifier)){var l;const m=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${Kt(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:m,event:u,schedule:i.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,r),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Ve(a)}`),u.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once&&this.hls)){var c;this.updateSchedule();const m=(c=this.schedule)==null?void 0:c.items;if(r&&m){const A=this.findItemIndex(r),I=this.livePrerollResumption(u);if(I!==void 0){let y=I;const C=this.getNextItemIndex(a);if(!this.isInterstitial(i[C])){var h;const E=(h=this.primaryDetails)==null?void 0:h.fragments;if(u.snapOptions.in&&E){const v=Ft(null,E,I);v&&(y=Math.min(Math.max(i[C].start,ei(y,v)),i[C].end))}}if(this.log(Dt("live join (preroll)",y)),this.timelinePos=y,C!==A&&(C||C===0)){this.advanceSchedule(C,m,void 0,a,o);return}}this.advanceSchedule(A,m,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){const a=this.schedule;if(!a)return;const o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=h.cue.pre?0:a.findAssetIndex(h,this.timelinePos);const g=br(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ve(o)} ${h.appendInPlace?"append in place":""}`),h.hasPlayed=!1,this.hls.trigger(p.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,l),this.shouldPlay&&sl(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&sl(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ve(e)}`);let a=this.timelinePos;if((i=this.detachedData)!=null&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Dt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!s)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ve(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,s){const i=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;const r=this.endedItem||this.playingItem,a=r!=null&&r.event?this.livePrerollResumption(r.event,s):void 0;if(a!==void 0)return a;const o=this.primaryDetails;if(o){const{fragmentStart:l,edge:c}=o;if(i<l||i>c&&!s){const h=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${l}-${c}]) snapping to liveSync ${h}`),h||l}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;const t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||s&&s-t<i?s||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:X.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):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(e,s)),s||(this.log(Dt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:a}=s,o=s.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${i} bufferingEnabled: ${r}`),!t&&o||!i||Math.abs(a-e)>.1){const l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){const c=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${c?Ve(c):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(e,t)}else r||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=z(z({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,r===-1?0:r),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;const c=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${c?Ve(c):null}`),c?.end===1/0){const u=this.playingItem,d=this.isInterstitial(u)&&u.event.appendInPlace;this.hls.startLoad(Math.max(l,c.start),d)}else{const u=this.getBufferingPlayer();u&&u.bufferedInPlaceToEnd(this.primaryMedia,u.currentTime)&&u.hls&&u.hls.trigger(p.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=z(z({},this.altSelection),{},{audio:s});return}const r=z(z({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=z(z({},this.altSelection),{},{subtitles:s});return}const r=z(z({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Pn(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Pn(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const i=t[s];if(i.cue.post){const r=this.getEventItem(i.identifier);r&&this.eventItemsMatch(r,this.bufferingItem)&&this.bufferedToItem(r,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=X.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ve(e)} (was ${Ve(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const s=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;const i=this.mediaSelection;if(!i)return;const r=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(i,[],r,e)}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=X.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((l===-1&&r&&e>=r.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ve(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),r=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(r,e,!0):this.startLoadingPrimaryAt(r);else{const o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(r,l)}}}}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){const l=e.timelineStart,c=this.playingItem,h=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(c)&&(c==null||(o=c.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let u,d=0;if((!h||h.interstitial.cue.pre)&&this.primaryLive&&(d=this.getLiveStartPos(),h&&(d+=h.remaining)),d&&!(e.cue.pre||e.cue.post)){const g=d-l;g>0&&(u=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${d?` live-start: ${d} start-offset: ${u} (timeline-start: ${l})`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);const f=this.assetListLoader.loadAssetList(e,u);f&&(e.assetListLoader=f)}else if(!a&&i){for(let c=t;c<i;c++){const h=e.assetList[c],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const s=this.primaryDetails;if(s&&e>=s.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){const o={parentIdentifier:e.identifier,identifier:Df(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig,a=i.loadLevelObj||i.levels[i.currentLevel],o=kn(a,r.videoPreference),l=i.audioTracks[i.audioTrack],c=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const E=this.timelinePos-t.timelineStart;if(E>=0){const v=t.duration;v&&E<v&&(h=E)}}const u=t.identifier,d=z(z({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||r.audioPreference,subtitlePreference:c||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=ue({},f,{contentId:ds(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const g=new kf(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let m=!0;const A=E=>{if(E.live){const S=new Error(`Interstitials MUST be VOD assets ${e}`),L={fatal:!0,type:W.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:S},R=this.findEventIndex(e.identifier);this.handleAssetItemError(L,e,R,s,S.message);return}const v=E.edge-E.fragmentStart,T=t.duration;(m||T===null||v>T)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${T} > ${v}`),t.duration=v,this.updateSchedule())};g.on(p.LEVEL_UPDATED,(E,{details:v})=>A(v)),g.on(p.LEVEL_PTS_UPDATED,(E,{details:v})=>A(v)),g.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const I=(E,v)=>{const T=this.getAssetPlayer(u);if(T&&v.tracks){T.off(p.BUFFER_CODECS,I),T.tracks=v.tracks;const S=this.primaryMedia;this.bufferingAsset===T.assetItem&&S&&!T.media&&this.bufferAssetPlayer(T,S)}};g.on(p.BUFFER_CODECS,I);const y=()=>{const E=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${E}`),!E||!this.schedule)return;const v=this.getEventItem(e.identifier);v&&this.advanceAssetBuffering(v,E.assetItem)};g.on(p.BUFFERED_TO_END,y);const C=E=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const T=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,T,E)};return g.once(p.MEDIA_ENDED,C(s)),g.once(p.PLAYOUT_LIMIT_REACHED,C(1/0)),g.on(p.ERROR,(E,v)=>{if(!this.schedule)return;const T=this.getAssetPlayer(u);if(v.details===b.BUFFER_STALLED_ERROR){if(T!=null&&T.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(v.details===b.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(v,e,this.findEventIndex(e.identifier),s,`Asset player error ${v.error} ${e}`)}),g.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const v=new Error(`Asset player destroyed unexpectedly ${u}`),T={fatal:!0,type:W.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:v};this.handleAssetItemError(T,e,this.findEventIndex(e.identifier),s,v.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Kt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ve(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h?.identifier!==l&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Kt(o)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=e,a=this.getEventItem(i.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,r);return}const o=this.getBufferingPlayer();if(o===e)return;const l=i.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;const c=o?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!jr(c,e.tracks)){const h=new Error(`Asset ${Kt(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),u={fatal:!0,type:W.OTHER_ERROR,details:b.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},d=i.findAssetIndex(r);this.handleAssetItemError(u,i,this.findEventIndex(i.identifier),d,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||i-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${i})`),l&&(c/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,i,r){if(e.details===b.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Kt(a)} ${e.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,u=ue({},e,{fatal:!1,errorAction:ts(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:c});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=i;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,s,i):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,a=this.hls.startPosition;let o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ve(s)} startPosition: ${a} seekableStart: ${r} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,r);const c=this.updateItem(s,o);this.itemsMatch(s,c)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(i))return;const l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var s,i;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const l=r.timelineStart,c=r.duration;let h=0;o.forEach((g,m)=>{const A=parseFloat(g.DURATION);this.createAsset(r,m,h,l+h,A,g.URI),h+=A}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(d){const g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if(f?.identifier===a){const g=r.assetList[0];if(g){const m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){const A=this.primaryMedia;m&&A&&this.bufferAssetPlayer(m,A)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case b.ASSET_LIST_PARSING_ERROR:case b.ASSET_LIST_LOAD_ERROR:case b.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case b.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}const i=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${i?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Ff{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:s}=this,i=this.levelDetails;if(!s||!i||!this.hls)return;this.currentTime=s.currentTime;const r=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=r;if(!o||l===1||!i.live)return;const c=this.targetLatency;if(c===null)return;const h=a-c,u=Math.min(this.maxLatency,c+i.targetduration),d=h<u,f=Bs(r)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(d&&h>.05&&this.forwardBufferLength>1&&!f){const g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,A=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(s,A)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;const t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const s=this.levelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||!this.hls)return null;const t=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,c=this.hls.userConfig;let h=l&&i||s;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||h===0)&&(h=a!==void 0?a:o*r);const u=r;return h+Math.min(this.stallCount*t.liveSyncOnStallIncrease,u)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null||!this.hls)return 0;const t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this),e.on(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this),e.off(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var s;const i=this.hls,r=this.media||t.event.appendInPlace&&(i==null||(s=i.interstitialsManager)==null?void 0:s.playerQueue.reduce((a,o)=>a||o.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(e,t){var s;t.details===b.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const il=500;class Nf extends Ui{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=D.IDLE,this.setInterval(il),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:s,part:i,success:r}=t;if(!r)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o;const l=(i||s).start;for(let h=0;h<a.length;h++)if(l>=a[h].start&&l<=a[h].end){o=a[h];break}const c=l+(i||s).duration;if(o?o.end=c:(o={start:l,end:c},a.push(o)),!i||c>=s.end){const h=this.fragmentTracker.fragBuffered(s);i&&h&&(h.range.subs={time:[{startPTS:s.start,endPTS:c}],partial:!0}),Ie(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,H.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===H.SUBTITLE&&(t.details===b.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==D.STOPPED&&(this.state=D.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Qa(this.levels,t)){this.levels=t.map(s=>new Jt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Jt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];if(!(i!=null&&i.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==D.STOPPED&&this.setInterval(il)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const c=this.mainDetails;let h=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}if(l.details){var u;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}a.alignedSliding||(Fs(c,a,this),h=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,c&&!this.startFragRequested&&this.setStartPosition(c,h),o===i&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:s,payload:i}=e;!s||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,s)}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e;this.fragContextChanged(t)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Bt(t.method))}decryptPayload(e,t,s){const i=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,ki(i.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(p.FRAG_DECRYPTED,{frag:t,part:s,payload:a,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=D.IDLE)})}doTick(){if(this.state===D.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],a=r?.details;if(!a||this.waitForLive(r)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}const{config:o}=this,l=this.playhead,c=X.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:h,len:u}=c,d=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(u>d||u&&!this.buffering)return;let f=this.getNextFragment(h,a);if(!f)return;if(Ie(f)){var t;const g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===m?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===pe.NOT_LOADED&&(f=m)}this.loadFragment(f,r,h)}}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);(i===pe.NOT_LOADED||i===pe.PARTIAL)&&super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new Bf(this.tracksBuffered[this.currentTrackId]||[])}}class Bf{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Uf={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},rl=n=>String.fromCharCode(Uf[n]||n),Qe=15,Je=42,$f={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Gf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vf={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Kf={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Hf=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yf{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;le.log(`${this.time} [${e}] ${s}`)}}}const Pt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Rr=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class nl{constructor(){this.styles=Rr}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Rr}setStyles(e){const t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Wf{constructor(){this.uchar=" ",this.penState=new nl}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class jf{constructor(e){this.chars=[],this.pos=0,this.currPenState=new nl,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Je;t++)this.chars.push(new Wf);this.logger=e}equals(e){const t=this.chars,s=e.chars;for(let i=0;i<Je;i++){const r=t[i],a=s[i];if(r.uchar!==a.uchar)return!1;const o=r.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Je;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<Je;t++){const s=e[t];if(s.uchar!==" ")return!1;const i=s.penState.styles;if(i!==Rr&&(i.foreground!=="white"||i.underline||i.italics||i.background!=="black"||i.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Je&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Je-1)}moveCursor(e){const t=Math.min(this.pos+e,Je);if(e>1)for(let s=this.pos+1;s<t;s++)this.chars[s].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=rl(e);if(this.pos>=Je){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Je;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 s=0;s<Je;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Dr{constructor(e){this.rows=[],this.currRow=Qe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Qe;t++)this.rows.push(new jf(e));this.logger=e}reset(){for(let e=0;e<Qe;e++)this.rows[e].clear();this.currRow=Qe-1}equals(e){let t=!0;for(let s=0;s<Qe;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Qe;t++){const s=this.rows[t].chars,i=e.rows[t].chars;for(let r=0;r<Je;r++){const a=s[r],o=i[r];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Qe;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 = "+fe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Qe;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+fe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Qe;r++){const a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
191
|
+
`)),s}getTextAndFormat(){return this.rows}}class zf{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Dr(s),this.nonDisplayedMemory=new Dr(s),this.lastOutputScreen=new Dr(s),this.currRollUpRow=this.displayedMemory.rows[Qe-1],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[Qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+fe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class al{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Xf(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Yf,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,(s=this.channels[e])==null||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new zf(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Pt([t[s],t[s+1]])+"] -> ("+Pt([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(qf(i,r,l)){ti(null,null,l),this.logger.log(3,()=>"Repeated command ("+Pt([i,r])+") is dropped");continue}ti(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else ti(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.getChannel(h).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Pt([i,r])+" orig: "+Pt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,a=this.getChannel(r);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Pt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const a=e<=23?1:2;return t>=64&&t<=95?s=a===1?$f[e]:Vf[e]:s=a===1?Gf[e]:Kf[e],this.getChannel(a).setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,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=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+rl(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Pt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Hf[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}ti(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function ti(n,e,t){t.a=n,t.b=e}function qf(n,e,t){return t.a===n&&t.b===e}function Xf(){return{a:null,b:null}}class si{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Zf{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ol(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new si(this,"textTrack1"),t=new si(this,"textTrack2"),s=new si(this,"textTrack3"),i=new si(this,"textTrack4");this.cea608Parser1=new al(1,e,t),this.cea608Parser2=new al(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let l=r.length;l--;){const c=r[l],h=Qf(c[0],c[1],t,s);if(h>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,h/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const l=this.cueCache[e];if(l){const c=this.Cues.newCue(null,t,s,i);c.length&&l.push.apply(l,c)}else{const c=this.captionsTracks[e].track;this.Cues.newCue(c,t,s,i)}}else{var o;const l=this.Cues.newCue(null,t,s,i),c=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:c})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){const{unparsedVttFrags:i}=this;t===H.MAIN&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(r=>{this.initPTS[r.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,r):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,cueCache:i,media:r}=this,{label:a,languageCode:o}=t[e];r&&(i[e]=[],s[e]=yr(r,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:i,cueCache:r}=this;for(const a in i)i[a].remove(),delete r[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ol(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!Qa(this.tracks,s)){const i=s.map(r=>({label:r.name,kind:r.type.toLowerCase(),default:r.default,subtitleTrack:r}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.level<this.tracks.length&&s.type===H.SUBTITLE){var r;if(i.byteLength||(r=s.initSegment)!=null&&(r=r.data)!=null&&r.byteLength){const a=s.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){const l=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l?.textCodec===pr?this._parseIMSC1(t):this._parseVTTs(t)}}else{const a="part"in t?t.part:null;this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){const{frag:t,payload:s}=e,i="part"in e?e.part:null,r=this.hls;Vo(s,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:i})},a=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:i,error:a})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,r="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(e);return}const c=this.hls,h=(t=s.initSegment)==null?void 0:t.data,u=h?Ye(h,new Uint8Array(i)).buffer:i;af(u,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!h?r:s).start,d=>{this._appendCues(d,s.level),c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},d=>{const f=d.message.startsWith("Missing initPTS");if(c.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${d}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:d})})}_fallbackToIMSC1(e){const{frag:t,payload:s}=e,i=this.tracks[t.level];i.textCodec||Vo(s,this.initPTS[t.cc],()=>{i.textCodec=pr,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const r=(i=this.tracks[t].trackNode)==null?void 0:i.track;if(!r||r.mode==="disabled")return;e.forEach(a=>Er(r,a))}else{const r=this.tracks[t];if(!r)return;const a=r.default?"default":"subtitles"+t;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===H.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===H.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var s;const{type:i,timeRanges:r}=t;if(i==="video"&&(s=r[i])!=null&&s.length){const{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var c;const h=(c=a[l])==null?void 0:c.track;if(h){const u=o[l];for(let d=0;d<u.length;d++)Er(h,u[d])}delete o[l]})}}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<i)){if(!a||a==="video"){const{captionsTracks:l,cueCache:c}=this;Object.keys(l).forEach(h=>vr(l[h].track,s,i)),Object.keys(c).forEach(h=>{const u=c[h];for(let d=u.length;d--;){const f=u[d];f.startTime>=s&&f.endTime<=i&&u.splice(d,1)}})}this.config.renderTextTracksNatively&&s===0&&r!==void 0&&this.tracks.forEach(l=>{var c;const h=(c=l.trackNode)==null?void 0:c.track;h&&vr(h,s,r)})}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function Qf(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function ol(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Jf=/\s/,eg={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let m=0;m<r.chars.length;m++)Jf.test(r.chars[m].uchar)&&o?l++:(c+=r.chars[m].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Bo(c.trim()),g=mr(e,t,f);n!=null&&(u=n.cues)!=null&&u.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>Er(n,d))),i}};class ll{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new oi}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Yt(e,t,!0))this.retry(e);else{var s;le.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=ci(e,s.retry),s.retry++,le.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function tg(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const sg=/(\d+)-(\d+)\/(\d+)/;class cl extends ll{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||ag}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=ig(t,this.controller.signal),r=t.responseType==="arraybuffer",a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=o&&B(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(cs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var u;this.response=h;const d=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(d-s.loading.start)),!h.ok){const{status:g,statusText:m}=h;throw new og(m||"fetch, bad network response",g,h)}s.loading.first=d,s.total=ng(h.headers)||s.total;const f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&B(e.highWaterMark)?this.loadProgressively(h,s,t,e.highWaterMark,f):r?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var u,d;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const g=h[a];g&&(s.loaded=s.total=g);const m={url:f.url,data:h,code:f.status},A=(u=this.callbacks)==null?void 0:u.onProgress;A&&!B(e.highWaterMark)&&A(s,t,h,f),(d=this.callbacks)==null||d.onSuccess(m,s,t,f)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=h&&h.code||0,d=h?h.message:null,f=e.loadPolicy.errorRetry,g=s.retry,m={url:t.url,data:void 0,code:u};if(Yt(f,g,!1,m))this.retry(f);else{var A;le.error(`${u} while loading ${t.url}`),(A=this.callbacks)==null||A.onError({code:u,text:d},t,h?h.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,s,i=0,r){const a=new xa,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function ig(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ue({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function rg(n){const e=sg.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function ng(n){const e=n.get("Content-Range");if(e){const s=rg(e);if(B(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function ag(n,e){return new self.Request(n.url,e)}class og extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const lg=(n,e,t)=>Math.max(e,Math.min(n,t)),cg=/^age:\s*[\d.]+\s*$/im;class hl extends ll{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const 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.call(this,s,t.url,t)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&B(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(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)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const m=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=m,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const A=(a=this.callbacks)==null?void 0:a.onProgress;A&&A(s,e,g,t);const I={url:t.responseURL,data:g,code:c};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&le.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(I,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:c};if(Yt(u,d,!1,f))this.retry(u);else{var l;le.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,s)}}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&cg.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 hg={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ug=z(z({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:hl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ta,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:hg},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Zo,abrController:Xc,bufferController:Bu,capLevelController:Ji,errorController:eh,fpsController:Qd,id3TrackController:Cf,gapController:Af,latencyController:Ff},dg()),{},{subtitleStreamController:Nf,subtitleTrackController:mf,timelineController:Zf,audioStreamController:ku,audioTrackController:wu,emeController:Vt,cmcdController:Yd,contentSteeringController:jd,iframeController:bf,interstitialsController:Of});function dg(){return{cueHandler:eg,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function fg(n,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){const a=e.liveMaxUnchangedPlaylistRefresh,o=lg(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}const s=Pr(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&l){c.push(u);const f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${fe(e[o])}`)}),z(z({},s),e)}function Pr(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(Pr):Object.keys(n).reduce((e,t)=>(e[t]=Pr(n[t]),e),{}):n}function gg(n,e){const t=n.loader;t!==cl&&t!==hl?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):tg()&&(n.loader=cl,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class mg extends Xi{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1,h=!1;t.levels.forEach(u=>{const d=u.attrs,f=fl(u,s),{audioCodec:g,videoCodec:m,imageCodec:A,width:I,height:y}=u;if(!f){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}o||(o=!!(I&&y)),l||(l=!!m),c||(c=!!g),h||(h=!!A);const{CODECS:C,"FRAME-RATE":E,"HDCP-LEVEL":v,"PATHWAY-ID":T,RESOLUTION:S,"VIDEO-RANGE":L}=d,x=`${`${T||"."}-`}${u.bitrate}-${S}-${E}-${C}-${L}-${v}`;if(r[x])if(r[x].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const P=a[x]+=1;u.attrs["PATHWAY-ID"]=new Array(P+1).join(".");const _=this.createLevel(u);r[x]=_,i.push(_)}else u.iframes||(r[x].addGroupId("audio",d.AUDIO),r[x].addGroupId("text",d.SUBTITLES));else{const P=this.createLevel(u);r[x]=P,a[x]=1,i.push(P)}}),this.filterAndSortMediaOptions(i,t,o,l,c,h)}createLevel(e){const t=new Jt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!dl(s.videoCodec,this.hls.config.preferManagedMediaSource)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=vn(i,[])}return t}filterAndSortMediaOptions(e,t,s,i,r,a){var o;let l=[],c=[],h=e;const u=((o=t.stats)==null?void 0:o.parsing)||{},d=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(h=h.filter(({videoCodec:v,videoRange:T,width:S,height:L})=>(!!v||!!(S&&L))&&Gc(T))),i&&a&&(h=h.filter(v=>!v.imageCodec)),h.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",T=v;t.levels.length&&(T=`one or more CODECS in variant not supported: ${fe(t.levels.map(L=>L.attrs.CODECS).filter((L,R,x)=>x.indexOf(L)===R))}`,this.warn(T),v+=` (${T})`);const S=new Error(v);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:S,reason:T})}}),u.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(v=>!v.audioCodec||ul(v.audioCodec,d)),gl(l)),t.subtitles&&(c=t.subtitles,gl(c));const f=h.slice(0);h.sort((v,T)=>{if(v.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&v.height!==T.height)return v.height-T.height;if(v.frameRate!==T.frameRate)return v.frameRate-T.frameRate;if(v.videoRange!==T.videoRange)return Ls.indexOf(v.videoRange)-Ls.indexOf(T.videoRange);if(v.videoCodec!==T.videoCodec){const S=In(v.videoCodec),L=In(T.videoCodec);if(S!==L)return L-S}if(v.uri===T.uri&&v.codecSet!==T.codecSet){const S=Ss(v.codecSet),L=Ss(T.codecSet);if(S!==L)return L-S}return v.averageBitrate!==T.averageBitrate?v.averageBitrate-T.averageBitrate:0});let g=f[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==f.length)){for(let v=0;v<f.length;v++)if(f[v].pathwayId===h[0].pathwayId){g=f[v];break}}this._levels=h;for(let v=0;v<h.length;v++)if(h[v]===g){var m;this._firstLevel=v;const T=g.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${T}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){const L=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);L>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const A=t.iframeVariants.filter(v=>fl(v,d));this._iframeVariants=A;const I=r&&!i,y=this.hls.config,C=!!(y.audioStreamController&&y.audioTrackController),E={levels:h,audioTracks:l,subtitleTracks:c,iframeVariants:A,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:C&&!I&&l.some(v=>!!v.url)};u.end=performance.now(),this.hls.trigger(p.MANIFEST_PARSED,E)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i?.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===se.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===H.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(i,t,l)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(p.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){const i=this.hls.config.abrSwitchInterval;if(i>0){const r=performance.now(),a=r-this.lastABRSwitchTime,o=i*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${i}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${i}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));ya(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function ul(n,e){return Zt(n,"audio",e)}function dl(n,e){return Zt(n,"video",e)}function fl(n,e){let{audioCodec:t,videoCodec:s}=n;t&&(n.audioCodec=t=xs(t,e)||void 0),s&&(s=n.videoCodec=kc(s));const{unknownCodecs:i}=n;return!(i?.length||0||t&&!ul(t,e)||s&&!dl(s,e))}function gl(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class pg extends Ue{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);const i=e.decryptdata;if(!i){const a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(St(e,b.KEY_LOAD_ERROR,a))}const r=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(St(e,b.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){const s=dc(e.initSegment.data);if(s.length){let i=s[0];const r=e.decryptdata.uri;if(i.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ee(i)} keyUri: ${r}`),dt.setKeyIdForUri(r,i);else{const a=dt.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Ee(a)} keyUri: ${r}`),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(St(e,b.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(St(e,b.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return t.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(c=>(t.key=i.decryptdata.key,z(z({},c),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ee(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const r=this.config,a=r.loader,o=new a(r);e.keyLoader=o;const l=this.keyLoaderInfo[s]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((c,h)=>{const u={type:se.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:s},d=r.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,A,I,y)=>{const{frag:C,keyInfo:E,url:v}=I;if(!C.decryptdata||E!==this.keyLoaderInfo[v])return h(St(C,b.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));E.decryptdata.key=C.decryptdata.key=new Uint8Array(m.data),C.keyLoader=E.loader=E.keyLoadPromise=null,c({frag:C,keyInfo:E})},onError:(m,A,I,y)=>{this.resetLoader(A),h(St(e,b.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),I,z({url:s,data:void 0},m)))},onTimeout:(m,A,I)=>{this.resetLoader(A),h(St(e,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),I))},onAbort:(m,A,I)=>{this.resetLoader(A),h(St(e,b.INTERNAL_ABORTED,new Error("key loading aborted"),I))}};o.load(u,f,g)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}}function St(n,e=b.KEY_LOAD_ERROR,t,s,i){return new at({type:W.NETWORK_ERROR,details:e,fatal:!1,frag:n,response:i,error:t,networkDetails:s||null})}function ml(n){const{type:e}=n;switch(e){case se.AUDIO_TRACK:return H.AUDIO;case se.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function _r(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Ag{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:se.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:se.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[se.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[se.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=this.hls.logger,h=i.context;if(h?.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===se.MANIFEST?r=s.manifestLoadPolicy.default:r=ue({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),B((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===se.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===se.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===se.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=ue({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=c.data;h.parsing.start=performance.now(),ot.isMediaPlaylist(g)||u.type!==se.MANIFEST?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};i.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=_r(e,s),l=ot.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}const{contentSteering:c,levels:h,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,h.forEach(C=>{const{unknownCodecs:E}=C;if(E){const{preferManagedMediaSource:v}=this.hls.config;let{audioCodec:T,videoCodec:S}=C;for(let L=E.length;L--;){const R=E[L];Zt(R,"audio",v)?(C.audioCodec=T=T?`${T},${R}`:R,Ot.audio[T.substring(0,4)]=2,E.splice(L,1)):Zt(R,"video",v)&&(C.videoCodec=S=S?`${S},${R}`:R,Ot.video[S.substring(0,4)]=2,E.splice(L,1))}}});const{AUDIO:A=[],SUBTITLES:I,"CLOSED-CAPTIONS":y}=ot.parseMasterPlaylistMedia(a,o,l);A.length&&!A.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"),A.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ae({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:A,subtitles:I,iframeVariants:u,captions:y,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:l,type:c}=s,h=_r(e,s),u=B(l)?l:B(o)?o:0,d=ml(s),f=ot.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(c===se.MANIFEST){const g={attrs:new Ae({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+pa(f,0),a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.MANIFEST_PARSING_ERROR,fatal:t.type===se.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===se.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===se.AUDIO_TRACK||e.type===se.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=b.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case se.MANIFEST:l=s?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,c=!0;break;case se.LEVEL:l=s?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,c=!1;break;case se.AUDIO_TRACK:l=s?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case se.SUBTITLE_TRACK:l=s?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:W.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){let d=e.url;t&&"url"in t&&(d=t.url),u.response=z({url:d,data:void 0},i)}this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:l,level:c,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=i,g=_r(t,i),m=ml(i);let A=typeof i.level=="number"&&m===H.MAIN?c:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const I=e.playlistParsingError;if(I){if(this.hls.logger.warn(`${I} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:I,reason:I.message,response:t,context:i,level:A,parent:m,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:i,level:A,parent:m,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case se.MANIFEST:case se.LEVEL:if(A){if(!h)A=0;else if(h!==o.levels[A]){const y=o.levels.indexOf(h);y>-1&&(A=y)}}o.trigger(p.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:A||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===se.MANIFEST,context:i});break;case se.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break;case se.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break}}}class ke{static get version(){return rs}static isMSESupported(){return Xo()}static isSupported(){return yf()}static getMediaSource(){return Ct()}static get Events(){return p}static get MetadataSchema(){return _e}static get ErrorTypes(){return W}static get ErrorDetails(){return b}static get DefaultConfig(){return ke.defaultConfig?ke.defaultConfig:ug}static set DefaultConfig(e){ke.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Gi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Ul(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),s=this.config=fg(ke.DefaultConfig,e,t);this.userConfig=e,s.progressive&&gg(s,t);const{streamController:i,abrController:r,bufferController:a,capLevelController:o,errorController:l,fpsController:c,id3TrackController:h,iframeController:u,gapController:d}=s,f=new l(this),g=this.abrController=new r(this),m=new th(this),A=s.interstitialsController,I=A?this.interstitialsController=new A(this,ke):null,y=a?this.bufferController=new a(this,m):null,C=o?this.capLevelController=new o(this):null,E=c?new c(this):null,v=s.cmcdController,T=v?this.cmcdController=new v(this):null,S=new Ag(this),L=s.contentSteeringController,R=L?new L(this):null,x=this.levelController=new mg(this,R),P=h?new h(this):void 0,_=new pg(this.config,this.logger),F=this.streamController=new i(this,m,_),V=this.gapController=d?new d(this,m):void 0;C&&C.setStreamController(F);const U=[S,x,F];I&&U.splice(1,0,I),R&&U.splice(1,0,R),this.networkControllers=U;const k=[g];y&&k.push(y),V&&k.push(V),C&&k.push(C),E&&(E.setStreamController(F),k.push(E)),P&&k.push(P),k.push(m),this.audioTrackController=this.createController(s.audioTrackController,U);const M=s.audioStreamController;M&&U.push(this.audioStreamController=new M(this,m,_)),this.subtitleTrackController=this.createController(s.subtitleTrackController,U);const w=s.subtitleStreamController;w&&U.push(this.subtititleStreamController=new w(this,m,_)),this.createController(s.timelineController,k),_.emeController=this.emeController=this.createController(s.emeController,k),T&&k.push(T),this.latencyController=this.createController(s.latencyController,k),this.coreComponents=k,this.iframeController=u?new u(this,ke):void 0,U.push(f);const N=f.onErrorOut;typeof N=="function"&&this.on(p.ERROR,N,f),this.on(p.MANIFEST_LOADED,S.onManifestLoaded,S)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===p.ERROR;this.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(p.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(p.MEDIA_DETACHING,e),this._media=null,this.trigger(p.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(p.MEDIA_DETACHING,s),this.trigger(p.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();const s=this.media,i=this._url,r=this._url=ai.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(p.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==D.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[H.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[H.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[H.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,s=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Xr()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=this.capLevelController,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}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){$c(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Dn(t);return Tn(e,s,navigator.mediaCapabilities)}}ke.defaultConfig=void 0;const Ig="X-Jewel-Studio",Cg="69d2c1660df6540944e25eb708fb252724ab27fb";class yg{video;callbacks;options={autoPlay:!1,startLevel:-1};hls;loadId=0;failed=!1;manifestParsed=!1;networkRetried=!1;mediaRecoveries=0;streamLoaded=!1;constructor(e,t){this.video=e,this.callbacks=t,e.addEventListener("error",()=>{this.hls?this.callbacks.log("Video element error:",e.error):e.getAttribute("src")&&this.fail(`Video element error: ${e.error?.message||e.error?.code}`)})}load(e,t){const{log:s}=this.callbacks,i=this.video;this.unload();const r=this.loadId;this.options=t,this.failed=!1,this.manifestParsed=!1,this.networkRetried=!1,this.mediaRecoveries=0,this.streamLoaded=t.autoPlay,ke.isSupported()?(s("HLS.js is supported, initializing..."),this.loadHls(e)):i.canPlayType("application/vnd.apple.mpegurl")?(s("Using native HLS support"),i.autoplay=t.autoPlay,i.addEventListener("loadedmetadata",()=>{t.autoPlay&&r===this.loadId&&this.autoplay()},{once:!0}),i.src=e):this.fail("Neither HLS.js nor native HLS is supported")}unload(){this.loadId++,this.destroy(),this.video.autoplay=!1,this.video.removeAttribute("src"),this.video.load()}startLoad(){this.streamLoaded||!this.hls||(this.hls.startLoad(this.options.startLevel),this.streamLoaded=!0)}destroy(){this.hls&&(this.hls.destroy(),this.hls=void 0)}autoplay(){const{log:e}=this.callbacks,t=this.video;e("Attempting autoplay..."),t.play().then(()=>e("Playback started successfully")).catch(s=>(e("Autoplay failed, retrying muted:",s),t.muted=!0,t.play().then(()=>e("Muted autoplay successful")).catch(i=>e("Muted autoplay also failed:",i))))}fail(e){this.failed||(this.failed=!0,this.destroy(),this.callbacks.onFail(e))}loadHls(e){const{log:t}=this.callbacks;try{const s=new ke({enableWorker:!0,lowLatencyMode:!0,backBufferLength:90,startLevel:this.options.startLevel,autoStartLoad:this.options.autoPlay,manifestLoadingTimeOut:2e4,manifestLoadingMaxRetry:3,manifestLoadingRetryDelay:500,levelLoadingTimeOut:2e4,levelLoadingMaxRetry:3,levelLoadingRetryDelay:500,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:3,fragLoadingRetryDelay:500,xhrSetup:i=>{i.withCredentials=!1,i.setRequestHeader(Ig,Cg)}});this.hls=s,s.on(ke.Events.ERROR,(i,r)=>{if(t("HLS error:",r),!!r.fatal)switch(r.type){case ke.ErrorTypes.NETWORK_ERROR:this.networkRetried?this.fail(`Network error: ${r.details}`):(this.networkRetried=!0,t("Fatal network error, restarting once..."),this.manifestParsed?s.startLoad():s.loadSource(e));break;case ke.ErrorTypes.MEDIA_ERROR:this.mediaRecoveries===0?(t("Fatal media error, trying to recover..."),s.recoverMediaError()):this.mediaRecoveries===1?(t("Fatal media error again, swapping audio codec and recovering..."),s.swapAudioCodec(),s.recoverMediaError()):this.fail(`Media error: ${r.details}`),this.mediaRecoveries++;break;default:this.fail(`Fatal HLS error: ${r.details}`);break}}),s.once(ke.Events.MEDIA_ATTACHED,()=>{t("Media attached, loading source:",e),s.loadSource(e)}),s.on(ke.Events.MANIFEST_PARSED,(i,r)=>{t("Manifest parsed, levels:",r.levels),this.manifestParsed=!0,this.options.autoPlay&&this.autoplay()}),t("Attaching media element..."),s.attachMedia(this.video)}catch(s){this.fail(`HLS initialization error: ${s instanceof Error?s.message:String(s)}`)}}}const Eg=`
|
|
192
|
+
:host {
|
|
193
|
+
display: block;
|
|
194
|
+
}
|
|
195
|
+
.video-container {
|
|
196
|
+
position: relative;
|
|
197
|
+
width: 100%;
|
|
198
|
+
background: var(--player-bg, #000);
|
|
199
|
+
overflow: hidden;
|
|
200
|
+
margin: 0 auto;
|
|
201
|
+
}
|
|
202
|
+
/* Always in the accessibility tree (no display: none) so the role="alert" text
|
|
203
|
+
set by fail() is announced. Empty and transparent until then. */
|
|
204
|
+
.error-message {
|
|
205
|
+
position: absolute;
|
|
206
|
+
inset: 0;
|
|
207
|
+
display: flex;
|
|
208
|
+
align-items: center;
|
|
209
|
+
justify-content: center;
|
|
210
|
+
padding: 16px;
|
|
211
|
+
text-align: center;
|
|
212
|
+
color: #fff;
|
|
213
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
214
|
+
font-size: 16px;
|
|
215
|
+
z-index: 2;
|
|
216
|
+
pointer-events: none;
|
|
217
|
+
}
|
|
218
|
+
/* Holds the overlay slot (e.g. a logo) above the video and below the controls.
|
|
219
|
+
Clicks pass through unless the slotted element sets pointer-events itself. */
|
|
220
|
+
.overlay {
|
|
221
|
+
position: absolute;
|
|
222
|
+
inset: 0;
|
|
223
|
+
z-index: 1;
|
|
224
|
+
pointer-events: none;
|
|
225
|
+
}
|
|
226
|
+
/* The whole player is the fullscreen element, so the controls and overlay stay.
|
|
227
|
+
The prefixed rule is separate: a selector list with an unknown pseudo-class is dropped. */
|
|
228
|
+
:host(:fullscreen) .video-container {
|
|
229
|
+
max-width: none !important;
|
|
230
|
+
height: 100%;
|
|
231
|
+
}
|
|
232
|
+
:host(:-webkit-full-screen) .video-container {
|
|
233
|
+
max-width: none !important;
|
|
234
|
+
height: 100%;
|
|
235
|
+
}
|
|
236
|
+
.video-container.has-error .error-message {
|
|
237
|
+
background: rgba(0, 0, 0, 0.6);
|
|
238
|
+
}
|
|
239
|
+
.video-container.has-error #control-bar {
|
|
240
|
+
display: none;
|
|
241
|
+
}
|
|
242
|
+
.video-container svg {
|
|
243
|
+
fill: #fff;
|
|
244
|
+
}
|
|
245
|
+
.video-container img {
|
|
246
|
+
filter: invert(1) brightness(100);
|
|
247
|
+
}
|
|
248
|
+
.video-container.light-theme {
|
|
249
|
+
--player-bg: #fff;
|
|
250
|
+
background: var(--player-bg);
|
|
251
|
+
}
|
|
252
|
+
.video-container.light-theme svg {
|
|
253
|
+
fill: #000;
|
|
254
|
+
}
|
|
255
|
+
.video-container.light-theme img {
|
|
256
|
+
filter: none;
|
|
257
|
+
}
|
|
258
|
+
.video-container.light-theme #control-bar {
|
|
259
|
+
background: linear-gradient(transparent, rgba(255, 255, 255, 0.7));
|
|
260
|
+
}
|
|
261
|
+
.video-container:not(.light-theme) #control-bar {
|
|
262
|
+
background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
|
|
263
|
+
}
|
|
264
|
+
video {
|
|
265
|
+
width: 100%;
|
|
266
|
+
height: 100%;
|
|
267
|
+
object-fit: contain;
|
|
268
|
+
}
|
|
269
|
+
#control-bar {
|
|
270
|
+
position: absolute;
|
|
271
|
+
bottom: 0;
|
|
272
|
+
left: 0;
|
|
273
|
+
right: 0;
|
|
274
|
+
display: flex;
|
|
275
|
+
flex-direction: column;
|
|
276
|
+
padding: 10px;
|
|
277
|
+
background: linear-gradient(transparent, var(--control-bg));
|
|
278
|
+
gap: 10px;
|
|
279
|
+
z-index: 1;
|
|
280
|
+
transition: opacity 0.3s ease, transform 0.3s ease;
|
|
281
|
+
}
|
|
282
|
+
/* opacity + pointer-events (not visibility: hidden) so the buttons stay
|
|
283
|
+
keyboard-focusable and :focus-visible can reveal the bar. */
|
|
284
|
+
:host([auto-hide-controls]) #control-bar {
|
|
285
|
+
opacity: 0;
|
|
286
|
+
pointer-events: none;
|
|
287
|
+
transform: translateY(8px);
|
|
288
|
+
}
|
|
289
|
+
/* .controls-visible is toggled by setupAutoHide() for mouse movement and taps. */
|
|
290
|
+
:host([auto-hide-controls]) .video-container.controls-visible #control-bar {
|
|
291
|
+
opacity: 1;
|
|
292
|
+
pointer-events: auto;
|
|
293
|
+
transform: none;
|
|
294
|
+
}
|
|
295
|
+
/* Kept in its own rule: browsers without :has() drop the whole selector list,
|
|
296
|
+
which would also disable the rule above.
|
|
297
|
+
:focus-visible (not :focus-within) so a mouse click on a button doesn't pin the bar open. */
|
|
298
|
+
:host([auto-hide-controls]) .video-container:has(:focus-visible) #control-bar {
|
|
299
|
+
opacity: 1;
|
|
300
|
+
pointer-events: auto;
|
|
301
|
+
transform: none;
|
|
302
|
+
}
|
|
303
|
+
@media (prefers-reduced-motion: reduce) {
|
|
304
|
+
#control-bar {
|
|
305
|
+
transform: none !important;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
#progress-row {
|
|
309
|
+
display: flex;
|
|
310
|
+
align-items: center;
|
|
311
|
+
gap: 10px;
|
|
312
|
+
width: 100%;
|
|
313
|
+
color: var(--control-color);
|
|
314
|
+
font-size: 14px;
|
|
315
|
+
}
|
|
316
|
+
/* Wrapper so the progress bar can be redrawn alone; display: contents keeps
|
|
317
|
+
.progress-bar a flex item of #progress-row. */
|
|
318
|
+
.progress-track {
|
|
319
|
+
display: contents;
|
|
320
|
+
}
|
|
321
|
+
#controls-row {
|
|
322
|
+
display: flex;
|
|
323
|
+
justify-content: space-between;
|
|
324
|
+
align-items: center;
|
|
325
|
+
width: 100%;
|
|
326
|
+
}
|
|
327
|
+
.button {
|
|
328
|
+
background: transparent;
|
|
329
|
+
border: none;
|
|
330
|
+
cursor: pointer;
|
|
331
|
+
padding: 5px;
|
|
332
|
+
display: flex;
|
|
333
|
+
align-items: center;
|
|
334
|
+
}
|
|
335
|
+
.button svg {
|
|
336
|
+
width: 24px;
|
|
337
|
+
height: 24px;
|
|
338
|
+
display: block;
|
|
339
|
+
}
|
|
340
|
+
.button:hover {
|
|
341
|
+
opacity: 0.8;
|
|
342
|
+
}
|
|
343
|
+
.time-display {
|
|
344
|
+
color: #fff;
|
|
345
|
+
font-size: 14px;
|
|
346
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
347
|
+
opacity: 0.9;
|
|
348
|
+
}
|
|
349
|
+
.light-theme .time-display {
|
|
350
|
+
color: #000;
|
|
351
|
+
}
|
|
352
|
+
.video-controls {
|
|
353
|
+
display: flex;
|
|
354
|
+
align-items: center;
|
|
355
|
+
gap: 8px;
|
|
356
|
+
}
|
|
357
|
+
.speed-control {
|
|
358
|
+
justify-content: center;
|
|
359
|
+
min-width: 34px;
|
|
360
|
+
min-height: 34px;
|
|
361
|
+
border-radius: 4px;
|
|
362
|
+
color: #fff;
|
|
363
|
+
font-size: 14px;
|
|
364
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
365
|
+
}
|
|
366
|
+
.light-theme .speed-control {
|
|
367
|
+
color: #000;
|
|
368
|
+
}
|
|
369
|
+
.speed-control img,
|
|
370
|
+
.speed-control svg {
|
|
371
|
+
width: 24px;
|
|
372
|
+
height: 24px;
|
|
373
|
+
display: block;
|
|
374
|
+
transition: opacity 0.2s;
|
|
375
|
+
}
|
|
376
|
+
.speed-control:hover img,
|
|
377
|
+
.speed-control:hover svg {
|
|
378
|
+
opacity: 0.7;
|
|
379
|
+
}
|
|
380
|
+
.volume-control {
|
|
381
|
+
display: flex;
|
|
382
|
+
align-items: center;
|
|
383
|
+
gap: 4px;
|
|
384
|
+
}
|
|
385
|
+
.volume-slider {
|
|
386
|
+
width: 80px;
|
|
387
|
+
margin: 0;
|
|
388
|
+
accent-color: #0A84FF;
|
|
389
|
+
cursor: pointer;
|
|
390
|
+
}
|
|
391
|
+
`;function pl(n){switch(n){case Oe.DualLayer:return`
|
|
392
|
+
<div class="progress-bar">
|
|
393
|
+
<div class="progress-bar-buffer"></div>
|
|
394
|
+
<div class="progress-bar-fill" style="width: 0%"></div>
|
|
395
|
+
<div class="progress-handle"></div>
|
|
396
|
+
</div>
|
|
397
|
+
`;case Oe.Segments:return`
|
|
398
|
+
<div class="progress-bar">
|
|
399
|
+
${Array.from({length:20},(e,t)=>`
|
|
400
|
+
<div class="progress-segment" data-index="${t}"></div>
|
|
401
|
+
`).join("")}
|
|
408
402
|
</div>
|
|
403
|
+
`;case Oe.MinimalWave:return`
|
|
404
|
+
<div class="progress-bar">
|
|
405
|
+
<div class="progress-bar-fill" style="width: 0%"></div>
|
|
406
|
+
<div class="progress-wave"></div>
|
|
407
|
+
</div>
|
|
408
|
+
`;case Oe.None:default:return""}}function vg(n){const e=n.showVolumeControl?`
|
|
409
|
+
<div class="volume-control">
|
|
410
|
+
<button type="button" class="button mute" data-action="mute" title="Mute" aria-label="Mute">
|
|
411
|
+
${He.volume}
|
|
412
|
+
</button>
|
|
413
|
+
${n.showVolumeSlider?'<input type="range" class="volume-slider" min="0" max="1" step="0.05" aria-label="Volume">':""}
|
|
414
|
+
</div>
|
|
415
|
+
`:"";return`
|
|
416
|
+
<div id="progress-row">
|
|
417
|
+
${n.showTimeDisplay?'<span class="time-display current-time">0:00</span>':""}
|
|
418
|
+
<div class="progress-track">${pl(n.progressBarStyle)}</div>
|
|
419
|
+
${n.showTimeDisplay?'<span class="time-display duration">0:00</span>':""}
|
|
420
|
+
</div>
|
|
421
|
+
<div id="controls-row">
|
|
422
|
+
<div class="video-controls">
|
|
423
|
+
<button type="button" class="button backward" data-action="backward" title="Backward" aria-label="Backward">
|
|
424
|
+
${He.backward}
|
|
425
|
+
</button>
|
|
426
|
+
<button type="button" class="button play-pause" data-action="play-pause" title="Play" aria-label="Play">
|
|
427
|
+
${He.play}
|
|
428
|
+
</button>
|
|
429
|
+
<button type="button" class="button forward" data-action="forward" title="Forward" aria-label="Forward">
|
|
430
|
+
${He.forward}
|
|
431
|
+
</button>
|
|
432
|
+
</div>
|
|
433
|
+
<div class="video-controls">
|
|
434
|
+
${e}
|
|
435
|
+
${n.showSpeedControl?'<button type="button" class="button speed-control" data-action="speed" title="Playback speed" aria-label="Playback speed 1x">1x</button>':""}
|
|
436
|
+
${n.showFullscreen?`
|
|
437
|
+
<button type="button" class="button fullscreen" data-action="fullscreen" title="Fullscreen" aria-label="Fullscreen">
|
|
438
|
+
${He.fullscreen}
|
|
439
|
+
</button>
|
|
440
|
+
`:""}
|
|
409
441
|
</div>
|
|
410
|
-
|
|
442
|
+
</div>
|
|
443
|
+
`}function Tg(){return`
|
|
444
|
+
<div class="video-container">
|
|
445
|
+
<video id="player"
|
|
446
|
+
muted
|
|
447
|
+
playsinline
|
|
448
|
+
style="width: 100%; height: 100%;">
|
|
449
|
+
</video>
|
|
450
|
+
|
|
451
|
+
<div class="overlay"><slot name="overlay"></slot></div>
|
|
452
|
+
|
|
453
|
+
<div class="error-message" role="alert"></div>
|
|
454
|
+
|
|
455
|
+
<div id="control-bar"></div>
|
|
456
|
+
</div>
|
|
457
|
+
`}let kr;function Sg(){if(kr===void 0){const n=document.createElement("video");n.volume=.5,kr=n.volume===.5}return kr}class ii extends HTMLElement{autoHide;_video;_stream;_speeds=[];_speedIndex=0;_fullscreenMode="none";constructor(){super();const e=this.attachShadow({mode:"open"});this.autoHide=new ri(e,{enabled:()=>this.autoHideControls,paused:()=>this._video?.paused??!1});const t=()=>this.syncFullscreenButton();this.addEventListener("fullscreenchange",t),this.addEventListener("webkitfullscreenchange",t)}static booleanProperties=["autoPlay","showTimeDisplay","showSpeedControl","showVolumeControl","autoHideControls","hideFullscreen","unmuted","noLoop","debug"];get autoPlay(){return this.hasAttribute("auto-play")}set autoPlay(e){this.toggleAttribute("auto-play",!!e)}get showTimeDisplay(){return this.hasAttribute("show-time-display")}set showTimeDisplay(e){this.toggleAttribute("show-time-display",!!e)}get showSpeedControl(){return this.hasAttribute("show-speed-control")}set showSpeedControl(e){this.toggleAttribute("show-speed-control",!!e)}get showVolumeControl(){return this.hasAttribute("show-volume-control")}set showVolumeControl(e){this.toggleAttribute("show-volume-control",!!e)}get autoHideControls(){return this.hasAttribute("auto-hide-controls")}set autoHideControls(e){this.toggleAttribute("auto-hide-controls",!!e)}get hideFullscreen(){return this.hasAttribute("hide-fullscreen")}set hideFullscreen(e){this.toggleAttribute("hide-fullscreen",!!e)}get unmuted(){return this.hasAttribute("unmuted")}set unmuted(e){this.toggleAttribute("unmuted",!!e)}get noLoop(){return this.hasAttribute("no-loop")}set noLoop(e){this.toggleAttribute("no-loop",!!e)}get debug(){return this.hasAttribute("debug")}set debug(e){this.toggleAttribute("debug",!!e)}get progressBarStyle(){const e=this.getAttribute("progress-bar-style");return Object.values(Oe).includes(e)?e:Oe.None}log=(...e)=>{this.debug&&console.debug("[v360-player]",...e)};fail(e){this.autoHide.cancel(),this.shadowRoot?.querySelector(".video-container")?.classList.add("has-error");const t=this.shadowRoot?.querySelector(".error-message");t&&(t.textContent="Video unavailable"),console.error("[v360-player] Playback failed:",e)}clearError(){this.shadowRoot?.querySelector(".video-container")?.classList.remove("has-error");const e=this.shadowRoot?.querySelector(".error-message");e&&(e.textContent="")}upgradeProperties(){const e=this;for(const t of ii.booleanProperties)if(Object.prototype.hasOwnProperty.call(this,t)){const s=e[t];delete e[t],this[t]=!!s}}static get observedAttributes(){return["video-src","poster-src","auto-play","width","playback-speeds","default-speed","show-time-display","show-speed-control","show-volume-control","hide-fullscreen","unmuted","no-loop","progress-bar-style","background"]}attributeChangedCallback(e,t,s){const i=this._video;if(!(!i||t===s))switch(e){case"video-src":this.loadSource();break;case"poster-src":this.applyPoster(i);break;case"width":this.applyWidth();break;case"background":this.applyTheme();break;case"auto-play":i.preload=this.autoPlay?"auto":"metadata";break;case"unmuted":this.applyMuted(i);break;case"no-loop":i.loop=!this.noLoop;break;case"progress-bar-style":this.renderProgressBar();break;case"playback-speeds":case"default-speed":this.applySpeeds(i),this.renderControlBar();break;default:this.renderControlBar();break}}connectedCallback(){this.upgradeProperties(),this._video||this.render(),this.loadSource()}disconnectedCallback(){this.autoHide.cancel(),this._stream?.unload()}render(){const e=this.shadowRoot;if(!e)return;e.innerHTML=`<style>${Eg}</style><style id="progress-styles"></style>${Tg()}`;const t=e.querySelector("video");this._video=t,this._stream=new yg(t,{log:this.log,onFail:s=>this.fail(s)}),this.applyPoster(t),this.applyWidth(),this.applyTheme(),this.applyMuted(t),t.loop=!this.noLoop,t.preload=this.autoPlay?"auto":"metadata",this.applySpeeds(t),this.listenToVideo(t),this.listenToControls(e.querySelector("#control-bar")),this.renderControlBar()}loadSource(){const e=this._video,t=this._stream;if(!e||!t)return;this.log("Loading video-src");const s=!e.paused;this.clearError();const i=this.getAttribute("video-src");i?t.load(i,{autoPlay:this.autoPlay||s,startLevel:parseInt(this.getAttribute("default-quality")||"-1")}):(this.log("No video-src set, nothing to load"),t.unload()),this.updateProgress(),this.updateDuration()}applyPoster(e){const t=this.getAttribute("poster-src");t?e.poster=t:e.removeAttribute("poster")}applyWidth(){const e=this.shadowRoot?.querySelector(".video-container");e&&(e.style.maxWidth=this.getAttribute("width")||"100%")}applyTheme(){this.shadowRoot?.querySelector(".video-container")?.classList.toggle("light-theme",this.getAttribute("background")==="light")}applyMuted(e){e.defaultMuted=!this.unmuted,e.muted=!this.unmuted}applySpeeds(e){this._speeds=Tl(this.getAttribute("playback-speeds"),this.log),this._speedIndex=Sl(this._speeds,this.getAttribute("default-speed")),this.setSpeed(e,this._speeds[this._speedIndex])}setSpeed(e,t){e.defaultPlaybackRate=t,e.playbackRate=t}renderControlBar(){const e=this.shadowRoot,t=this._video,s=e?.querySelector("#control-bar");!e||!t||!s||(this._fullscreenMode=Cl(this,t),s.innerHTML=vg({progressBarStyle:this.progressBarStyle,showTimeDisplay:this.showTimeDisplay,showSpeedControl:this.showSpeedControl,showVolumeControl:this.showVolumeControl,showVolumeSlider:Sg(),showFullscreen:!this.hideFullscreen&&this._fullscreenMode!=="none"}),this.applyProgressStyles(),this.updatePlayPauseButton(!t.paused),this.updateProgress(),this.updateDuration(),this.updateSpeedButton(),this.updateVolumeControl(),this.syncFullscreenButton())}renderProgressBar(){const e=this.shadowRoot?.querySelector(".progress-track");e&&(e.innerHTML=pl(this.progressBarStyle)),this.applyProgressStyles(),this.updateProgress()}applyProgressStyles(){const e=this.shadowRoot?.querySelector("#progress-styles");e&&(e.textContent=Il[this.progressBarStyle])}listenToVideo(e){e.addEventListener("play",()=>{this.updatePlayPauseButton(!0),this.autoHide.schedule()}),e.addEventListener("pause",()=>{this.updatePlayPauseButton(!1),this.autoHide.cancel()}),e.addEventListener("emptied",()=>{this.updatePlayPauseButton(!e.paused),this.updateProgress(),this.updateDuration()}),e.addEventListener("timeupdate",()=>this.updateProgress()),e.addEventListener("durationchange",()=>this.updateDuration()),e.addEventListener("volumechange",()=>this.updateVolumeControl())}listenToControls(e){e.addEventListener("click",t=>{const s=t.target,i=s.closest(".progress-bar");if(i){this.seek(i,t.clientX);return}switch(s.closest("[data-action]")?.dataset.action){case"play-pause":this._video?.paused?this.play():this.pause();break;case"forward":this.step(1);break;case"backward":this.step(-1);break;case"speed":this.nextSpeed();break;case"mute":this.toggleMute();break;case"fullscreen":this.toggleFullscreen();break}}),e.addEventListener("input",t=>{const s=t.target,i=this._video;if(!i||!s.classList.contains("volume-slider"))return;const r=Number(s.value);i.volume=r,i.muted=r===0})}play(){const e=this._video;e&&(this._stream?.startLoad(),e.play()?.catch(t=>this.log("play() was rejected:",t)))}pause(){this._video?.pause()}step(e){const t=this._video;t&&(t.paused||t.pause(),t.currentTime=t.currentTime+e*.2*t.playbackRate)}seek(e,t){const s=this._video;if(!s)return;const i=s.duration;if(!Number.isFinite(i)||i<=0)return;const r=e.getBoundingClientRect();if(r.width<=0)return;const a=Math.max(0,Math.min(1,(t-r.left)/r.width));s.currentTime=a*i}nextSpeed(){const e=this._video;e&&(this._speedIndex=(this._speedIndex+1)%this._speeds.length,this.setSpeed(e,this._speeds[this._speedIndex]),this.updateSpeedButton())}toggleMute(){const e=this._video;e&&(e.muted||e.volume===0?(e.volume===0&&(e.volume=1),e.muted=!1):e.muted=!0)}toggleFullscreen(){const e=this._video;e&&yl(this,e,this._fullscreenMode).catch(t=>this.log("Fullscreen request failed:",t))}updatePlayPauseButton(e){const t=this.shadowRoot?.querySelector(".play-pause");if(!t)return;const s=e?"Pause":"Play";t.innerHTML=e?He.pause:He.play,t.setAttribute("aria-label",s),t.title=s}updateProgress(){const e=this.shadowRoot,t=this._video;if(!e||!t)return;const{currentTime:s,duration:i}=t,r=e.querySelector(".current-time");r&&(r.textContent=Mr(s));const a=Number.isFinite(i)&&i>0?s/i*100:0,o=e.querySelector(".progress-bar-fill");o&&(o.style.width=`${a}%`);const l=e.querySelectorAll(".progress-segment");l.forEach((c,h)=>{const u=(h+1)*(100/l.length);c.classList.toggle("filled",a>=u)})}updateDuration(){const e=this.shadowRoot?.querySelector(".duration");e&&this._video&&(e.textContent=Mr(this._video.duration))}updateSpeedButton(){const e=this.shadowRoot?.querySelector(".speed-control"),t=this._speeds[this._speedIndex];if(!e||t===void 0)return;const s=He[`speed-${t.toFixed(2)}`];s?e.innerHTML=s:e.textContent=`${t}x`,e.setAttribute("aria-label",`Playback speed ${t}x`)}updateVolumeControl(){const e=this.shadowRoot,t=this._video;if(!e||!t)return;const s=t.muted||t.volume===0,i=e.querySelector(".mute");if(i){const a=s?"Unmute":"Mute";i.innerHTML=s?He.volumeMuted:He.volume,i.setAttribute("aria-label",a),i.title=a}const r=e.querySelector(".volume-slider");r&&(r.value=String(s?0:t.volume))}syncFullscreenButton(){const e=this.shadowRoot?.querySelector(".fullscreen");if(!e)return;const t=Or(this),s=t?"Exit fullscreen":"Fullscreen";e.innerHTML=t?He.exitFullscreen:He.fullscreen,e.setAttribute("aria-label",s),e.title=s}}customElements.define("v360-player",ii),kt.V360Player=ii,Object.defineProperty(kt,Symbol.toStringTag,{value:"Module"})}));
|