vue3-video-players
Version:
hls.js player component for Vue3
27 lines • 383 kB
JavaScript
(function(Ae,T){typeof exports=="object"&&typeof module<"u"?T(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],T):(Ae=typeof globalThis<"u"?globalThis:Ae||self,T(Ae.index={},Ae.Vue))})(this,function(Ae,T){"use strict";function yr(a,e,t){var s=t||{},i=s.noTrailing,r=i===void 0?!1:i,n=s.noLeading,o=n===void 0?!1:n,l=s.debounceMode,c=l===void 0?void 0:l,d,h=!1,u=0;function f(){d&&clearTimeout(d)}function g(y){var E=y||{},S=E.upcomingOnly,x=S===void 0?!1:S;f(),h=!x}function p(){for(var y=arguments.length,E=new Array(y),S=0;S<y;S++)E[S]=arguments[S];var x=this,R=Date.now()-u;if(h)return;function L(){u=Date.now(),e.apply(x,E)}function _(){d=void 0}!o&&c&&!d&&L(),f(),c===void 0&&R>a?o?(u=Date.now(),r||(d=setTimeout(c?_:L,a))):L():r!==!0&&(d=setTimeout(c?_:L,c===void 0?a-R:a))}return p.cancel=g,p}function Ss(a,e,t){var s=t||{},i=s.atBegin,r=i===void 0?!1:i;return yr(a,e,{debounceMode:r!==!1})}function Tr(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var vs={exports:{}};(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,d){if(d=d||{},l=l.trim(),c=c.trim(),!c){if(!d.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):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 p={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)p.path=f.path,u.params||(p.params=f.params,u.query||(p.query=f.query));else{var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+u.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(p)},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(n,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()})(vs);var Lt=vs.exports;function Ls(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function oe(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ls(Object(t),!0).forEach(function(s){Er(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):Ls(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Er(a,e,t){return e=Sr(e),e in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function te(){return te=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},te.apply(this,arguments)}function xr(a,e){if(typeof a!="object"||a===null)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e||"default");if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Sr(a){var e=xr(a,"string");return typeof e=="symbol"?e:String(e)}const B=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)};let m=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a}({}),G=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),I=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.UNKNOWN="unknown",a}({});const we=function(){},At={trace:we,debug:we,log:we,warn:we,info:we,error:we};let He=At;function vr(a){const e=self.console[a];return e?e.bind(self.console,`[${a}] >`):we}function Lr(a,...e){e.forEach(function(t){He[t]=a[t]?a[t].bind(a):vr(t)})}function Ar(a,e){if(self.console&&a===!0||typeof a=="object"){Lr(a,"debug","log","info","warn","error");try{He.log(`Debug logs enabled for "${e}" in hls.js version 1.4.12`)}catch{He=At}}else He=At}const v=He,Ir=/^(\d+)x(\d+)$/,As=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Z{constructor(e){typeof e=="string"&&(e=Z.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&(t.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}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}else 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]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Ir.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const s={},i='"';for(As.lastIndex=0;(t=As.exec(e))!==null;){let r=t[2];r.indexOf(i)===0&&r.lastIndexOf(i)===r.length-1&&(r=r.slice(1,-1));const n=t[1].trim();s[n]=r}return s}}function Rr(a){return a!=="ID"&&a!=="CLASS"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function br(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"}class Is{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const s=t.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==s[i]){v.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=te(new Z({}),s,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=new Date(this.attr["END-DATE"]);B(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*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 isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class tt{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var z={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Rs{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[z.AUDIO]:null,[z.VIDEO]:null,[z.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const s=e.split("@",2),i=[];s.length===1?i[0]=t?t.byteRangeEndOffset:0:i[0]=parseInt(s[1]),i[1]=parseInt(s[0])+i[0],this._byteRange=i}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Lt.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class It extends Rs{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new tt,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!B(this.programDateTime))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){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};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)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[z.AUDIO]=null,e[z.VIDEO]=null,e[z.AUDIOVIDEO]=null}}class Dr extends Rs{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new tt,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 n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const Cr=10;class _r{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.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=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Cr}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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Rt(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function kr(a){const e=bs(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function wr(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function Pr(a){const e=a.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",n=i[1];r?(s.splice(-1,1),t=Rt(n)):t=kr(n)}}return t}function bs(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}var ee={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 Ds(a){switch(a){case le.FAIRPLAY:return ee.FAIRPLAY;case le.PLAYREADY:return ee.PLAYREADY;case le.WIDEVINE:return ee.WIDEVINE;case le.CLEARKEY:return ee.CLEARKEY}}var Cs={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Fr(a){if(a===Cs.WIDEVINE)return ee.WIDEVINE}function _s(a){switch(a){case ee.FAIRPLAY:return le.FAIRPLAY;case ee.PLAYREADY:return le.PLAYREADY;case ee.WIDEVINE:return le.WIDEVINE;case ee.CLEARKEY:return le.CLEARKEY}}function bt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[ee.FAIRPLAY,ee.WIDEVINE,ee.PLAYREADY,ee.CLEARKEY].filter(i=>!!e[i]):[];return!s[ee.WIDEVINE]&&t&&s.push(ee.WIDEVINE),s}const ks=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Or(a,e,t,s){let i;switch(a){case ee.FAIRPLAY:i=["cenc","sinf"];break;case ee.WIDEVINE:case ee.PLAYREADY:i=["cenc"];break;case ee.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return Nr(i,e,t,s)}function Nr(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"not-allowed",distinctiveIdentifier:s.distinctiveIdentifier||"not-allowed",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 Pe(a,e,t){return Uint8Array.prototype.slice?a.slice(e,t):new Uint8Array(Array.prototype.slice.call(a,e,t))}const Dt=(a,e)=>e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,ws=(a,e)=>e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,st=(a,e)=>{const t=e;let s=0;for(;Dt(a,e);){s+=10;const i=it(a,e+6);s+=i,ws(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)},it=(a,e)=>{let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t},Mr=(a,e)=>Dt(a,e)&&it(a,e+6)+10<=a.length-e,Br=a=>{const e=Fs(a);for(let t=0;t<e.length;t++){const s=e[t];if(Ps(s))return Hr(s)}},Ps=a=>a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp",Ur=a=>{const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=it(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}},Fs=a=>{let e=0;const t=[];for(;Dt(a,e);){const s=it(a,e+6);e+=10;const i=e+s;for(;e+8<i;){const r=Ur(a.subarray(e)),n=$r(r);n&&t.push(n),e+=r.size+10}ws(a,e)&&(e+=10)}return t},$r=a=>a.type==="PRIV"?Gr(a):a.type[0]==="W"?Kr(a):Vr(a),Gr=a=>{if(a.size<2)return;const e=xe(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}},Vr=a=>{if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=xe(a.data.subarray(t),!0);t+=s.length+1;const i=xe(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=xe(a.data.subarray(1));return{key:a.type,data:e}},Kr=a=>{if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=xe(a.data.subarray(t),!0);t+=s.length+1;const i=xe(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=xe(a.data);return{key:a.type,data:e}},Hr=a=>{if(a.data.byteLength===8){const e=new Uint8Array(a.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)}},xe=(a,e=!1)=>{const t=Wr();if(t){const c=t.decode(a);if(e){const d=c.indexOf("\0");return d!==-1?c.substring(0,d):c}return c.replace(/\0/g,"")}const s=a.length;let i,r,n,o="",l=0;for(;l<s;){if(i=a[l++],i===0&&e)return o;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:r=a[l++],o+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=a[l++],n=a[l++],o+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return o};let Ct;function Wr(){return!Ct&&typeof self.TextDecoder<"u"&&(Ct=new self.TextDecoder("utf-8")),Ct}const Se={hexDump:function(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}},rt=Math.pow(2,32)-1,Yr=[].push,Os={video:1,audio:2,id3:3,text:4};function ie(a){return String.fromCharCode.apply(null,a)}function Ns(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function K(a,e){const t=Ms(a,e);return t<0?4294967296+t:t}function Ms(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function _t(a,e,t){a[e]=t>>24,a[e+1]=t>>16&255,a[e+2]=t>>8&255,a[e+3]=t&255}function H(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=K(a,i),n=ie(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const l=H(a.subarray(i+8,o),e.slice(1));l.length&&Yr.apply(t,l)}i=o}return t}function qr(a){const e=[],t=a[0];let s=8;const i=K(a,s);s+=4;const r=0,n=0;t===0?s+=8:s+=16,s+=2;let o=a.length+n;const l=Ns(a,s);s+=2;for(let c=0;c<l;c++){let d=s;const h=K(a,d);d+=4;const u=h&2147483647;if((h&2147483648)>>>31===1)return v.warn("SIDX has hierarchical references (not supported)"),null;const g=K(a,d);d+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+u-1}}),o+=u,d+=4,s=d}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function Bs(a){const e=[],t=H(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=H(r,["tkhd"])[0];if(n){let o=n[0],l=o===0?12:20;const c=K(n,l),d=H(r,["mdia","mdhd"])[0];if(d){o=d[0],l=o===0?12:20;const h=K(d,l),u=H(r,["mdia","hdlr"])[0];if(u){const f=ie(u.subarray(8,12)),g={soun:z.AUDIO,vide:z.VIDEO}[f];if(g){const p=H(r,["mdia","minf","stbl","stsd"])[0];let y;p&&(y=ie(p.subarray(12,16))),e[c]={timescale:h,type:g},e[g]={timescale:h,id:c,codec:y}}}}}}return H(a,["moov","mvex","trex"]).forEach(i=>{const r=K(i,4),n=e[r];n&&(n.default={duration:K(i,12),flags:K(i,20)})}),e}function zr(a,e){if(!a||!e)return a;const t=e.keyId;return t&&e.isCommonEncryption&&H(a,["moov","trak"]).forEach(i=>{const n=H(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=H(n,["enca"]);const l=o.length>0;l||(o=H(n,["encv"])),o.forEach(c=>{const d=l?c.subarray(28):c.subarray(78);H(d,["sinf"]).forEach(u=>{const f=Us(u);if(f){const g=f.subarray(8,24);g.some(p=>p!==0)||(v.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Se.hexDump(g)} -> ${Se.hexDump(t)}`),f.set(t,8))}})})}),a}function Us(a){const e=H(a,["schm"])[0];if(e){const t=ie(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return H(a,["schi","tenc"])[0]}return v.error("[eme] missing 'schm' box"),null}function jr(a,e){return H(e,["moof","traf"]).reduce((t,s)=>{const i=H(s,["tfdt"])[0],r=i[0],n=H(s,["tfhd"]).reduce((o,l)=>{const c=K(l,4),d=a[c];if(d){let h=K(i,4);if(r===1){if(h===rt)return v.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=rt+1,h+=K(i,8)}const u=d.timescale||9e4,f=h/u;if(isFinite(f)&&(o===null||f<o))return f}return o},null);return n!==null&&isFinite(n)&&(t===null||n<t)?n:t},null)}function Xr(a,e){let t=0,s=0,i=0;const r=H(a,["moof","traf"]);for(let n=0;n<r.length;n++){const o=r[n],l=H(o,["tfhd"])[0],c=K(l,4),d=e[c];if(!d)continue;const h=d.default,u=K(l,0)|(h==null?void 0:h.flags);let f=h==null?void 0:h.duration;u&8&&(u&2?f=K(l,12):f=K(l,8));const g=d.timescale||9e4,p=H(o,["trun"]);for(let y=0;y<p.length;y++){if(t=Qr(p[y]),!t&&f){const E=K(p[y],4);t=f*E}d.type===z.VIDEO?s+=t/g:d.type===z.AUDIO&&(i+=t/g)}}if(s===0&&i===0){let n=0;const o=H(a,["sidx"]);for(let l=0;l<o.length;l++){const c=qr(o[l]);c!=null&&c.references&&(n+=c.references.reduce((d,h)=>d+h.info.duration||0,0))}return n}return s||i}function Qr(a){const e=K(a,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let s=0;const i=K(a,4);for(let r=0;r<i;r++){if(e&256){const n=K(a,t);s+=n,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return s}function Jr(a,e,t){H(e,["moof","traf"]).forEach(s=>{H(s,["tfhd"]).forEach(i=>{const r=K(i,4),n=a[r];if(!n)return;const o=n.timescale||9e4;H(s,["tfdt"]).forEach(l=>{const c=l[0];let d=K(l,4);if(c===0)d-=t*o,d=Math.max(d,0),_t(l,4,d);else{d*=Math.pow(2,32),d+=K(l,8),d-=t*o,d=Math.max(d,0);const h=Math.floor(d/(rt+1)),u=Math.floor(d%(rt+1));_t(l,4,h),_t(l,8,u)}})})})}function Zr(a){const e={valid:null,remainder:null},t=H(a,["moof"]);if(t){if(t.length<2)return e.remainder=a,e}else return e;const s=t[t.length-1];return e.valid=Pe(a,0,s.byteOffset-8),e.remainder=Pe(a,s.byteOffset-8),e}function Fe(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function $s(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return H(s,["moof"]).map(l=>{const c=l.byteOffset-8;H(l,["traf"]).map(h=>{const u=H(h,["tfdt"]).map(f=>{const g=f[0];let p=K(f,4);return g===1&&(p*=Math.pow(2,32),p+=K(f,8)),p/i})[0];return u!==void 0&&(a=u),H(h,["tfhd"]).map(f=>{const g=K(f,4),p=K(f,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,S=(p&8)!==0;let x=0;const R=(p&16)!==0;let L=0;const _=(p&32)!==0;let D=8;g===r&&(y&&(D+=8),E&&(D+=4),S&&(x=K(f,D),D+=4),R&&(L=K(f,D),D+=4),_&&(D+=4),e.type==="video"&&(n=en(e.codec)),H(h,["trun"]).map(k=>{const P=k[0],b=K(k,0)&16777215,U=(b&1)!==0;let O=0;const Y=(b&4)!==0,re=(b&256)!==0;let j=0;const J=(b&512)!==0;let X=0;const N=(b&1024)!==0,$=(b&2048)!==0;let w=0;const F=K(k,4);let M=8;U&&(O=K(k,M),M+=4),Y&&(M+=4);let q=O+c;for(let he=0;he<F;he++){if(re?(j=K(k,M),M+=4):j=x,J?(X=K(k,M),M+=4):X=L,N&&(M+=4),$&&(P===0?w=K(k,M):w=Ms(k,M),M+=4),e.type===z.VIDEO){let Ee=0;for(;Ee<X;){const me=K(s,q);if(q+=4,tn(n,s[q])){const Me=s.subarray(q,q+me);Gs(Me,n?2:1,a+w/i,t)}q+=me,Ee+=me+4}}a+=j/i}}))})})}),t}function en(a){if(!a)return!1;const e=a.indexOf("."),t=e<0?a:a.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function tn(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Gs(a,e,t,s){const i=Vs(a);let r=0;r+=e;let n=0,o=0,l=!1,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const d=i.length-r;if(!l&&n===4&&r<i.length){if(l=!0,i[r++]===181){const u=Ns(i,r);if(r+=2,u===49){const f=K(i,r);if(r+=4,f===1195456820){const g=i[r++];if(g===3){const p=i[r++],y=31&p,E=64&p,S=E?2+y*3:0,x=new Uint8Array(S);if(E){x[0]=p;for(let R=1;R<S;R++)x[R]=i[r++]}s.push({type:g,payloadType:n,pts:t,bytes:x})}}}}}else if(n===5&&o<d){if(l=!0,o>16){const h=[];for(let g=0;g<16;g++){const p=i[r++].toString(16);h.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&h.push("-")}const u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=i[r++];s.push({payloadType:n,pts:t,uuid:h.join(""),userData:xe(f),userDataBytes:f})}}else if(o<d)r+=o;else if(o>d)break}}function Vs(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function sn(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,l=0,c=0;if(e===0){for(;ie(a.subarray(c,c+1))!=="\0";)t+=ie(a.subarray(c,c+1)),c+=1;for(t+=ie(a.subarray(c,c+1)),c+=1;ie(a.subarray(c,c+1))!=="\0";)s+=ie(a.subarray(c,c+1)),c+=1;s+=ie(a.subarray(c,c+1)),c+=1,i=K(a,12),r=K(a,16),o=K(a,20),l=K(a,24),c=28}else if(e===1){c+=4,i=K(a,c),c+=4;const h=K(a,c);c+=4;const u=K(a,c);for(c+=4,n=2**32*h+u,Number.isSafeInteger(n)||(n=Number.MAX_SAFE_INTEGER,v.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(a,c),c+=4,l=K(a,c),c+=4;ie(a.subarray(c,c+1))!=="\0";)t+=ie(a.subarray(c,c+1)),c+=1;for(t+=ie(a.subarray(c,c+1)),c+=1;ie(a.subarray(c,c+1))!=="\0";)s+=ie(a.subarray(c,c+1)),c+=1;s+=ie(a.subarray(c,c+1)),c+=1}const d=a.subarray(c,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:l,payload:d}}function rn(a,...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(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function nn(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;if(e){s=1,i=new Uint8Array(e.length*16);for(let o=0;o<e.length;o++){const l=e[o];if(l.byteLength!==16)throw new RangeError("Invalid key");i.set(l,o*16)}}else 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 n=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),rn([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t||new Uint8Array)}function an(a){if(!(a instanceof ArrayBuffer)||a.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(a),s=t.getUint32(0);if(a.byteLength!==s&&s>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=Se.hexDump(new Uint8Array(a,12,16));const r=t.getUint32(28);if(e.version===0){if(s-32<r)return null;e.data=new Uint8Array(a,32,r)}else if(e.version===1){e.kids=[];for(let n=0;n<r;n++)e.kids.push(new Uint8Array(a,32+n*16,16))}return e}let nt={};class We{static clearKeyUriToKeyIdMap(){nt={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||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["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&v.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=on(e);return new We(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=Pr(this.uri);if(t)switch(this.keyFormat){case le.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case le.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=nn(s,null,t);const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),n=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(c){const d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){const h=Rt(d).subarray(0,16);wr(h),this.keyId=h}}break}default:{let s=t.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=nt[this.uri];if(!s){const i=Object.keys(nt).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),nt[this.uri]=s}this.keyId=s}return this}}function on(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const Ks=/\{\$([a-zA-Z0-9-_]+)\}/g;function Hs(a){return Ks.test(a)}function ce(a,e,t){if(a.variableList!==null||a.hasVariableRefs)for(let s=t.length;s--;){const i=t[s],r=e[i];r&&(e[i]=kt(a,r))}}function kt(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Ks,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function Ws(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function ln(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function at(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const cn={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},Ys=at();function dn(a,e){const t=cn[e];return!!t&&t[a.slice(0,4)]===!0}function wt(a,e){var t;return(t=Ys==null?void 0:Ys.isTypeSupported(`${e||"video"}/mp4;codecs="${a}"`))!=null?t:!1}const qs=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,zs=/#EXT-X-MEDIA:(.*)/g,hn=/^#EXT(?:INF|-X-TARGETDURATION):/m,js=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),un=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class pe{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let s=t.shift()+".";return s+=parseInt(t.shift()).toString(16),s+=("000"+parseInt(t.shift()).toString(16)).slice(-4),s}return e}static resolve(e,t){return Lt.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return hn.test(e)}static parseMasterPlaylist(e,t){const s=Hs(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];qs.lastIndex=0;let n;for(;(n=qs.exec(e))!=null;)if(n[1]){var o;const c=new Z(n[1]);ce(i,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=kt(i,n[2]),h={attrs:c,bitrate:c.decimalInteger("AVERAGE-BANDWIDTH")||c.decimalInteger("BANDWIDTH"),name:c.NAME,url:pe.resolve(d,t)},u=c.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),fn((c.CODECS||"").split(/[ ,]+/).filter(f=>f),h),h.videoCodec&&h.videoCodec.indexOf("avc1")!==-1&&(h.videoCodec=pe.convertAVC1ToAVCOTI(h.videoCodec)),(o=h.unknownCodecs)!=null&&o.length||r.push(h),i.levels.push(h)}else if(n[3]){const c=n[3],d=n[4];switch(c){case"SESSION-DATA":{const h=new Z(d);ce(i,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=h["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=h);break}case"SESSION-KEY":{const h=Xs(d,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):v.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const h=new Z(d);ce(i,h,["NAME","VALUE","QUERYPARAM"]),Ws(i,h,t)}break}case"CONTENT-STEERING":{const h=new Z(d);ce(i,h,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:pe.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Qs(d);break}}}const l=r.length>0&&r.length<i.levels.length;return i.levels=l?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={},n=s.levels,o={AUDIO:n.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:n.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(zs.lastIndex=0;(i=zs.exec(e))!==null;){const c=new Z(i[1]),d=c.TYPE;if(d){const h=o[d],u=r[d]||[];r[d]=u,ce(s,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",instreamId:c["INSTREAM-ID"],name:c.NAME||c.LANGUAGE||"",type:d,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:c.LANGUAGE,url:c.URI?pe.resolve(c.URI,t):""};if(h!=null&&h.length){const g=pe.findGroup(h,f.groupId)||h[0];Js(f,g,"audioCodec"),Js(f,g,"textCodec")}u.push(f)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){const o=new _r(t),l=o.fragments;let c=null,d=0,h=0,u=0,f=0,g=null,p=new It(i,t),y,E,S,x=-1,R=!1;for(js.lastIndex=0,o.m3u8=e,o.hasVariableRefs=Hs(e);(y=js.exec(e))!==null;){R&&(R=!1,p=new It(i,t),p.start=u,p.sn=d,p.cc=f,p.level=s,c&&(p.initSegment=c,p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null));const k=y[1];if(k){p.duration=parseFloat(k);const P=(" "+y[2]).slice(1);p.title=P||null,p.tagList.push(P?["INF",k,P]:["INF",k])}else if(y[3]){if(B(p.duration)){p.start=u,S&&ti(p,S,o),p.sn=d,p.level=s,p.cc=f,p.urlId=r,l.push(p);const P=(" "+y[3]).slice(1);p.relurl=kt(o,P),Zs(p,g),g=p,u+=p.duration,d++,h=0,R=!0}}else if(y[4]){const P=(" "+y[4]).slice(1);g?p.setByteRange(P,g):p.setByteRange(P)}else if(y[5])p.rawProgramDateTime=(" "+y[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),x===-1&&(x=l.length);else{if(y=y[0].match(un),!y){v.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E<y.length&&!(typeof y[E]<"u");E++);const P=(" "+y[E]).slice(1),b=(" "+y[E+1]).slice(1),U=y[E+2]?(" "+y[E+2]).slice(1):"";switch(P){case"PLAYLIST-TYPE":o.type=b.toUpperCase();break;case"MEDIA-SEQUENCE":d=o.startSN=parseInt(b);break;case"SKIP":{const O=new Z(b);ce(o,O,["RECENTLY-REMOVED-DATERANGES"]);const Y=O.decimalInteger("SKIPPED-SEGMENTS");if(B(Y)){o.skippedSegments=Y;for(let j=Y;j--;)l.unshift(null);d+=Y}const re=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");re&&(o.recentlyRemovedDateranges=re.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(b),1);break;case"VERSION":o.version=parseInt(b);break;case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(b||U)&&p.tagList.push(U?[b,U]:[b]);break;case"DISCONTINUITY":f++,p.tagList.push(["DIS"]);break;case"GAP":p.gap=!0,p.tagList.push([P]);break;case"BITRATE":p.tagList.push([P,b]);break;case"DATERANGE":{const O=new Z(b);ce(o,O,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ce(o,O,O.clientAttrs);const Y=new Is(O,o.dateRanges[O.ID]);Y.isValid||o.skippedSegments?o.dateRanges[Y.id]=Y:v.warn(`Ignoring invalid DATERANGE tag: "${b}"`),p.tagList.push(["EXT-X-DATERANGE",b]);break}case"DEFINE":{{const O=new Z(b);ce(o,O,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in O?ln(o,O,n):Ws(o,O,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(b);break;case"KEY":{const O=Xs(b,t,o);if(O.isSupported()){if(O.method==="NONE"){S=void 0;break}S||(S={}),S[O.keyFormat]&&(S=te({},S)),S[O.keyFormat]=O}else v.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${b}"`);break}case"START":o.startTimeOffset=Qs(b);break;case"MAP":{const O=new Z(b);if(ce(o,O,["BYTERANGE","URI"]),p.duration){const Y=new It(i,t);ei(Y,O,s,S),c=Y,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime&&(p.rawProgramDateTime=c.rawProgramDateTime)}else ei(p,O,s,S),c=p,R=!0;break}case"SERVER-CONTROL":{const O=new Z(b);o.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),o.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const O=new Z(b);o.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=o.partList;O||(O=o.partList=[]);const Y=h>0?O[O.length-1]:void 0,re=h++,j=new Z(b);ce(o,j,["BYTERANGE","URI"]);const J=new Dr(j,p,t,re,Y);O.push(J),p.duration+=J.duration;break}case"PRELOAD-HINT":{const O=new Z(b);ce(o,O,["URI"]),o.preloadHint=O;break}case"RENDITION-REPORT":{const O=new Z(b);ce(o,O,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(O);break}default:v.warn(`line parsed but not handled: ${y}`);break}}}g&&!g.relurl?(l.pop(),u-=g.duration,o.partList&&(o.fragmentHint=g)):o.partList&&(Zs(p,g),p.cc=f,o.fragmentHint=p,S&&ti(p,S,o));const L=l.length,_=l[0],D=l[L-1];if(u+=o.skippedSegments*o.targetduration,u>0&&L&&D){o.averagetargetduration=u/L;const k=D.sn;o.endSN=k!=="initSegment"?k:0,o.live||(D.endList=!0),_&&(o.startCC=_.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(u+=o.fragmentHint.duration),o.totalduration=u,o.endCC=f,x>0&&gn(l,x),o}}function Xs(a,e,t){var s,i;const r=new Z(a);ce(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const n=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,d=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&v.error(`Invalid IV: ${r.IV}`);const h=o?pe.resolve(o,e):"",u=(c||"1").split("/").map(Number).filter(Number.isFinite);return new We(n,h,d,u,l)}function Qs(a){const t=new Z(a).decimalFloatingPoint("TIME-OFFSET");return B(t)?t:null}function fn(a,e){["video","audio","text"].forEach(t=>{const s=a.filter(i=>dn(i,t));if(s.length){const i=s.filter(r=>r.lastIndexOf("avc1",0)===0||r.lastIndexOf("mp4a",0)===0);e[`${t}Codec`]=i.length>0?i[0]:s[0],a=a.filter(r=>s.indexOf(r)===-1)}}),e.unknownCodecs=a}function Js(a,e,t){const s=e[t];s&&(a[t]=s)}function gn(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Zs(a,e){a.rawProgramDateTime?a.programDateTime=Date.parse(a.rawProgramDateTime):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime),B(a.programDateTime)||(a.programDateTime=null,a.rawProgramDateTime=null)}function ei(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function ti(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}var W={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},V={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function si(a){const{type:e}=a;switch(e){case W.AUDIO_TRACK:return V.AUDIO;case W.SUBTITLE_TRACK:return V.SUBTITLE;default:return V.MAIN}}function Pt(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class mn{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}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:W.MANIFEST,url:s,deliveryDirectives:null})}onLevelLoading(e,t){const{id:s,level:i,url:r,deliveryDirectives:n}=t;this.load({id:s,level:i,responseType:"text",type:W.LEVEL,url:r,deliveryDirectives:n})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:W.AUDIO_TRACK,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:W.SUBTITLE_TRACK,url:r,deliveryDirectives:n})}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=i.context;if(c&&c.url===e.url){v.trace("[playlist-loader]: playlist request ongoing");return}v.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===W.MANIFEST?r=s.manifestLoadPolicy.default:r=te({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),(t=e.deliveryDirectives)!=null&&t.part){let c;if(e.type===W.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===W.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===W.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const d=c.partTarget,h=c.targetduration;if(d&&h){const u=Math.max(d*3,h*.8)*1e3;r=te({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(c,d,h,u)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),u||null,d);return}d.parsing.start=performance.now(),pe.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,d,h,u||null,f):this.handleMasterPlaylist(c,d,h,u)},onError:(c,d,h,u)=>{this.handleNetworkError(d,h,!1,c,u)},onTimeout:(c,d,h)=>{this.handleNetworkError(d,h,!0,void 0,c)}};i.load(e,o,l)}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Pt(e,s),l=pe.parseMasterPlaylist(n,o);if(l.playlistParsingError){this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}const{contentSteering:c,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=pe.parseMasterPlaylistMedia(n,o,l);p.length&&!p.some(x=>!x.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(v.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Z({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:y,captions:E,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:l,type:c}=s,d=Pt(e,s),h=B(o)?o:0,u=B(l)?l:h,f=si(s),g=pe.parseLevelPlaylist(e.data,d,u,f,h,this.variableList);if(c===W.MANIFEST){const p={attrs:new Z({}),bitrate:0,details:g,name:"",url:d};n.trigger(m.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:d,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:G.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===W.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 n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===W.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===W.AUDIO_TRACK||e.type===W.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);v.warn(`[playlist-loader]: ${n}`);let l=I.UNKNOWN,c=!1;const d=this.getInternalLoader(e);switch(e.type){case W.MANIFEST:l=s?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,c=!0;break;case W.LEVEL:l=s?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,c=!1;break;case W.AUDIO_TRACK:l=s?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case W.SUBTITLE_TRACK:l=s?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,c=!1;break}d&&this.resetInternalLoader(e.type);const h={type:G.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:r};if(i){const u=(t==null?void 0:t.url)||e.url;h.response=oe({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,h)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:l,level:c,id:d,groupId:h,deliveryDirectives:u}=i,f=Pt(t,i),g=si(i),p=typeof i.level=="number"&&g===V.MAIN?c:void 0;if(!e.fragments.length){const E=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:G.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){o.trigger(m.ERROR,{type:G.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:p,parent:g,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case W.MANIFEST:case W.LEVEL:o.trigger(m.LEVEL_LOADED,{details:e,level:p||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u});break;case W.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u});break;case W.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:u});break}}}function ii(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function ri(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){v.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){v.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function Be(a){const e=a.mode;if(e==="disabled"&&(a.mode="hidden"),a.cues)for(let t=a.cues.length;t--;)a.removeCue(a.cues[t]);e==="disabled"&&(a.mode=e)}function Ft(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=yn(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function pn(a,e){if(e<a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t;for(;s<=i;){const r=Math.floor((i+s)/2);if(e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r}return a[s].startTime-e<e-a[i].startTime?s:i}function yn(a,e,t){const s=[],i=pn(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}var ye={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const Tn=.25;function Ot(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const ot=(()=>{const a=Ot();try{new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Nt(a,e){return a.getTime()/1e3-e}function En(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class xn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Be(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return ii(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Ot();for(let o=0;o<r.length;o++){const l=r[o].type;if(l===ye.emsg&&!s||!i)continue;const c=Fs(r[o].data);if(c){const d=r[o].pts;let h=d+r[o].duration;h>ot&&(h=ot),h-d<=0&&(h=d+Tn);for(let f=0;f<c.length;f++){const g=c[f];if(!Ps(g)){this.updateId3CueEnds(d,l);const p=new n(d,h,"");p.value=g,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===ot&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=n;if(r&&(o||l)){let c;i==="audio"?c=d=>d.type===ye.audioId3&&l:i==="video"?c=d=>d.type===ye.emsg&&o:c=d=>d.type===ye.audioId3&&l||d.type===ye.emsg&&o,Ft(r,t,s,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=t,n=Object.keys(r);if(i){const d=Object.keys(s).filter(h=>!n.includes(h));for(let h=d.length;h--;){const u=d[h];Object.keys(s[u].cues).forEach(f=>{i.removeCue(s[u].cues[f])}),delete s[u]}}const o=t.fragments[t.fragments.length-1];if(n.length===0||!B(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=Ot();for(let d=0;d<n.length;d++){const h=n[d],u=r[h],f=s[h],g=(f==null?void 0:f.cues)||{};let p=(f==null?void 0:f.durationKnown)||!1;const y=Nt(u.startDate,l);let E=ot;const S=u.endDate;if(S)E=Nt(S,l),p=!0;else if(u.endOnNext&&!p){const R=n.reduce((L,_)=>{const D=r[_];return D.class===u.class&&D.id!==_&&D.startDate>u.startDate&&L.push(D),L},[]).sort((L,_)=>L.startDate.getTime()-_.startDate.getTime())[0];R&&(E=Nt(R.startDate,l),p=!0)}const x=Object.keys(u.attr);for(let R=0;R<x.length;R++){const L=x[R];if(!Rr(L))continue;let _=g[L];if(_)p&&!f.durationKnown&&(_.endTime=E);else{let D=u.attr[L];_=new c(y,E,""),br(L)&&(D=En(D)),_.value={key:L,data:D},_.type=ye.dateRange,_.id=h,this.id3Track.addCue(_),g[L]=_}}s[h]={cues:g,dateRange:u,durationKnown:p}}}}class Sn{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&s||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:n*i);const d=i,h=1;return c+Math.min(this.stallCount*h,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,s=this.levelDetails;if(e===null||t===null||s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;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.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(m.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var s;t.details===I.BUFFER_STALLED_ERROR&&(this.stallCount++,(s=this.levelDetails)!=null&&s.live&&v.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||r===1)return;const n=this.targetLatency;if(n===null)return;const o=s-n,l=Math.min(this.maxLatency,n+t.targetduration),c=o<l;if(t.live&&c&&o>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,r)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(d,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Mt=["NONE","TYPE-0","TYPE-1",null];var Ye={No:"",Yes:"YES",v2:"v2"};function vn(a,e){const{canSkipUntil:t,canSkipDateRanges:s,endSN:i}=a,r=e!==void 0?e-i:0;return t&&r<t?s?Ye.v2:Ye.Yes:Ye.No}class ni{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&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class qe{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=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.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return(e=this.audioGroupIds)==null?void 0:e[this.urlId]}get textGroupId(){var e;return(e=this.textGroupIds)==null?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function Bt(a,e){const t=e.startPTS;if(B(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&(i.duration=s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.start=a.start+(a.minEndPTS-a.start):e.start=a.start+a.duration:e.start=Math.max(a.start-e.duration,0)}function ai(a,e,t,s,i,r){s-t<=0&&(v.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,l=s;const c=e.startPTS,d=e.endPTS;if(B(c)){const y=Math.abs(c-t);B(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,c),t=Math.min(t,c),i=Math.min(i,e.startDTS),l=Math.min(s,d),s=Math.max(s,d),r=Math.max(r,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=s-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const u=e.sn;if(!a||u<a.startSN||u>a.endSN)return 0;let f;const g=u-a.startSN,p=a.fragments;for(p[g]=e,f=g;f>0;f--)Bt(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Bt(p[f],p[f+1]);return a.fragmentHint&&Bt(p[p.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,h}function Ln(a,e){let t=null;const s=a.fragments;for(let l=s.length-1;l>=0;l--){const c=s[l].initSegment;if(c){t=c;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let i=0,r;if(Rn(a,e,(l,c)=>{l.relurl&&(i=l.cc-c.cc),B(l.startPTS)&&B(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,c.urlId=l.urlId,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var d;(!c.initSegment||c.initSegment.relurl===((d=t)==null?void 0:d.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){v.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=An(a.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const n=e.fragments;if(i){v.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<n.length;l++)n[l].cc+=i}e.skippedSegments&&(e.startCC=e.fragments[0].cc),In(a.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?ai(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):oi(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime}function An(a,e,t){const s=te({},a);return t&&t.forEach(i=>{delete s[i]}),Object.keys(e).forEach(i=>{const r=new Is(e[i].attr,s[i]);r.isValid?s[i]=r:v.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),s}function In(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function Rn(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let c=i;c<=r;c++){const d=l[n+c];let h=o[c];s&&!h&&c<s&&(h=e.fragments[c]=d),d&&h&&t(d,h)}}function oi(a,e){const t=e.startSN+e.skippedSegments-a.startSN,s=a.fragments;t<0||t>=s.length||Ut(e,s[t].start)}function Ut(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].start+=e;a.fragmentHint&&(a.fragmentHint.start+=e)}}function bn(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments,i=4;if(s.length&&t*i>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Dn(a,e,t){if(!(a!=null&&a.details))return null;const s=a.details;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function li(a,e,t){var s;return a!=null&&a.details?ci((s=a.details)==null?void 0:s.partList,e,t):null}function ci(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function lt(a){switch(a.details){case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_TIMEOUT:case I.LEVEL_LOAD_TIMEOUT:case I.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function di(a,e){const t=lt(e);return a.default[`${t?"timeout":"error"}Retry`]}function $t(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function hi(a){return oe(oe({},a),{errorRetry:null,timeoutRetry:null})}function ct(a,e,t,s){return!!a&&e<a.maxNumRetry&&(Cn(s)||!!t)}function Cn(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}const ui={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function _n(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!B(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;t=t||0;for(let r=0;r<a.length;++r){const n=a[r];if(kn(e,t,n))return n}return null}function ze(a,e,t=0,s=0){let i=null;if(a?i=e[a.sn-e[0].sn+1]||null:t===0&&e[0].start===0&&(i=e[0]),i&&Gt(t,s,i)===0)return i;const r=ui.search(e,Gt.bind(null,t,s));return r&&(r!==a||!i)?r:i}function Gt(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function kn(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function wn(a,e){return ui.search(a,t=>t.cc<e?1:t.cc>e?-1:0)}const Pn=3e5;var ne={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ue={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Fn{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=v.log.bind(v,"[info]:"),this.warn=v.warn.bind(v,"[warning]:"),this.error=v.error.bind(v,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(e==null?void 0:e.type)===V.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s,i;if(t.fatal)return;const r=this.hls,n=t.context;switch(t.details){case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case I.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction={action:ne.DoNothing,flags:ue.None};return}case I.FRAG_GAP:case I.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ne.SendAlternateToPenaltyBox;return}case I.LEVEL_EMPTY_ERROR:case I.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===V.MAIN?t.level:r.loadLevel;t.details===I.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.SUBTITLE_LOAD_ERROR:case I.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const c=r.levels[r.loadLevel];if(c&&(n.type===W.AUDIO_TRACK&&n.groupId===c.audioGroupId||n.type===W.SUBTITLE_TRACK&&n.groupId===c.textGroupId)){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ne.SendAlternateToPenaltyBox,t.errorAction.flags=ue.MoveAllAlternatesMatchingHost;return}}return;case I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],d=c==null?void 0:c.attrs["HDCP-LEVEL"];d&&(t.errorAction={action:ne.SendAlternateToPenaltyBox,flags:ue.MoveAllAlternatesMatchingHDCP,hdcpLevel:d})}return;case I.BUFFER_ADD_CODEC_ERROR:case I.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,(i=t.level)!=null?i:r.loadLevel);return;case I.INTERNAL_EXCEPTION:case I.BUFFER_APPENDING_ERROR:case I.BUFFER_APPEND_ERROR:case I.BUFFER_FULL_ERROR:case I.LEVEL_SWITCH_ERROR:case I.BUFFER_STALLED_ERROR:case I.BUFFER_SEEK_OVER_HOLE:case I.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ne.DoNothing,flags:ue.None};return}if(t.type===G.KEY_SYSTEM_ERROR){const c=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c);return}}getPlaylistRetryOrSwitchAction(e,t){var s;const i=this.hls,r=di(i.config.playlistLoadPolicy,e),n=this.playlistError++,o=(s=e.response)==null?void 0:s.code;if(ct(r,n,lt(e),o))return{action:ne.RetryRequest,flags:ue.None,retryConfig:r,retryCount:n};const c=this.getLevelSwitchAction(e,t);return r&&(c.retryConfig=r,c.retryCount=n),c}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=di(e.details.startsWith("key")?n:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i){var c;e.details!==I.FRAG_GAP&&i.fragmentError++;const h=(c=e.response)==null?void 0:c.code;if(ct(o,l,lt(e),h))return{action:ne.RetryRequest,flags:ue.None,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i&&(i.loadError++,s.autoLevelEnabled)){var r,n;let o=-1;const{levels:l,loadLevel:c,minAutoLevel:d,maxAutoLevel:h}=s,u=(r=e.frag)==null?void 0:r.type,{type:f,groupId:g}=(n=e.context)!=null?n:{};for(let p=l.length;p--;){const y=(p+c)%l.length;if(y!==c&&y>=d&&y<=h&&l[y].loadError===0){const E=l[y];if(e.details===I.FRAG_GAP&&e.frag){const S=l[y].details;if(S){const x=ze(e.frag,S.fragments,e.frag.start);if(x!=null&&x.gap)continue}}else{if(f===W.AUDIO_TRACK&&g===E.audioGroupId||f===W.SUBTITLE_TRACK&&g===E.textGroupId)continue;if(u===V.AUDIO&&i.audioGroupId===E.audioGroupId||u===V.SUBTITLE&&i.textGroupId===E.textGroupId)continue}o=y;break}}if(o>-1&&s.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:ne.SendAlternateToPenaltyBox,flags:ue.None,nextAutoLevel:o}}return{action:ne.SendAlternateToPenaltyBox,flags:ue.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ne.DoNothing:break;case ne.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==I.FRAG_GAP&&(t.fatal=!0);break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case ue.None:this.switchLevel(e,n);break;case ue.MoveAllAlternatesMatchingHost:s.resolved||(s.resolved=this.redundantFailover(e));break;case ue.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=Mt[Mt.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){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)}redundantFailover(e){const{hls:t,penalizedRenditions:s}=this,i=e.parent===V.MAIN?e.level:t.loadLevel,r=t.levels[i],n=r.url.length,o=e.frag?e.frag.urlId:r.urlId;r.urlId===o&&(!e.frag||r.details)&&this.penalizeRendition(r,e);for(let l=1;l<n;l++){const c=(o+l)%n,d=s[c];if(!d||On(d,e,s[o]))return this.warn(`Switching to Redundant Stream ${c+1}/${n}: "${r.url[c]}" after ${e.details}`),this.playlistError=0,t.levels.forEach(h=>{h.urlId=c}),t.nextLoadLevel=i,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:s}=this,i=s[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};i.lastErrorPerfMs=performance.now(),i.errors.push(t),i.details=e.details,s[e.urlId]=i}}function On(a,e,t){if(performance.now()-a.lastErrorPerfMs>Pn)return!0;const s=a.details;if(e.details===I.FRAG_GAP&&s&&e.frag){const i=e.frag.start,r=ze(null,s.fragments,i);if(r&&!r.gap)return!0}if(t&&a.errors.length<t.errors.length){const i=a.errors[a.errors.length-1];if(s&&i.frag&&e.frag&&Math.abs(i.frag.start-e.frag.start)>s.targetduration*3)return!0}return!1}class Vt{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=v.log.bind(v,`${t}:`),this.warn=v.warn.bind(v,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const s=t==null?void 0:t.renditionReports;if(s){let i=-1;for(let r=0;r<s.length;r++){const n=s[r];let o;try{o=new self.URL(n.URI,t.url).href}catch(l){v.warn(`Could not construct new URL for Rendition Report: ${l}`),o=n.URI||""}if(o===e){i=r;break}else o===e.substring(0,o.length)&&(i=r)}if(i!==-1){const r=s[i],n=parseInt(r["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let o=parseInt(r["LAST-PART"])||(t==null?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&l>t.partTarget&&(o+=1)}return new ni(n,o>=0?o:void 0,Ye.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||s!=null&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&Ln(s,i),!this.canLoad||!i.live)return;let l,c,d;if(i.canBlockReload&&i.endSN&&i.advanced){const y=this.hls.config.lowLatencyMode,E=i.lastPartSn,S=i.endSN,x=i.lastPartIndex,R=x!==-1,L=E===S,_=y?0:x;R?(c=L?S+1:E,d=L?_:x+1):c=S+1;const D=i.age,k=D+i.ageHeader;let P=Math.min(k-i.partTarget,i.targetduration*1.5);if(P>0){if(s&&P>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${P} with playlist age: ${i.age}`),P=0;else{const b=Math.floor(P/i.targetduration);if(c+=b,d!==void 0){const U=Math.round(P%i.targetduration/i.partTarget);d+=U}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${D.toFixed(2)}s goal: ${P} skip sn ${b} to part ${d}`)}i.tuneInGoal=P}if(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,d),y||!L){this.loadPlaylist(l);return}}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,d));const h=this.hls.mainForwardBufferInfo,u=h?h.end-h.len:0,f=(i.edge-u)*1e3,g=bn(i,f);i.updated&&n>this.requestScheduled+g&&(this.requestScheduled=r.loading.start),c!==void 0&&i.canBlockReload?this.requestScheduled=r.loading.first+g-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=g);let p=this.requestScheduled-n;p=Math.max(0,p),this.log(`reload live playlist ${e} in ${Math.round(p)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,t,s,i){let r=vn(e,s);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Ye.No),new ni(s,i,r)}checkRetry(e){const t=e.details,s=lt(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===ne.RetryRequest||!i.resolved&&r===ne.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,n>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=$t(o,n);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}let Kt;class Nn extends Vt{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=[],i={};let r;t.levels.forEach(n=>{var o;const l=n.attrs;((o=n.audioCodec)==null?void 0:o.indexOf("mp4a.40.34"))!==-1&&(Kt||(Kt=/chrome|firefox/i.test(navigator.userAgent)),Kt&&(n.audioCodec=void 0));const{AUDIO:c,CODECS:d,"FRAME-RATE":h,"PATHWAY-ID":u,RESOLUTION:f,SUBTITLES:g}=l,y=`${`${u||"."}-`}${n.bitrate}-${f}-${h}-${d}`;r=i[y],r?r.addFallback(n):(r=new qe(n),i[y]=r,s.push(r)),dt(r,"audio",c),dt(r,"text",g)}),this.filterAndSortMediaOptions(s,t)}filterAndSortMediaOptions(e,t){let s=[],i=[],r=!1,n=!1,o=!1,l=e.filter(({audioCodec:f,videoCodec:g,width:p,height:y,unknownCodecs:E})=>(r||(r=!!(p&&y)),n||(n=!!g),o||(o=!!f),!(E!=null&&E.length)&&(!f||wt(f,"audio"))&&(!g||wt(g,"video"))));if((r||n)&&o&&(l=l.filter(({videoCodec:f,width:g,height:p})=>!!f||!!(g&&p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}t.audioTracks&&(s=t.audioTracks.filter(f=>!f.audioCodec||wt(f.audioCodec,"audio")),fi(s)),t.subtitles&&(i=t.subtitles,fi(i));const c=l.slice(0);l.sort((f,g)=>f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==g.bitrate?f.bitrate-g.bitrate:f.attrs["FRAME-RATE"]!==g.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-g.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==g.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-g.attrs.decimalFloatingPoint("SCORE"):r&&f.height!==g.height?f.height-g.height:0);let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){d=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===d){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${d.bitrate}`);break}const h=o&&!n,u={levels:l,audioTracks:s,subtitleTracks:i,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:o,video:n,altAudio:!h&&s.some(f=>!!f.url)};this.hls.trigger(m.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(m.ERROR,{type:G.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:d,reason:d.message}),h)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&n.details&&i&&r===o)return;this.log(`Switching to level ${e}${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l=te({},n,{level:e,maxBitrate:n.maxBitrate,attrs:n.attrs,uri:n.uri,urlId:n.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(m.LEVEL_SWITCHING,l);const c=n.details;if(!c||c.live){const d=this.switchParams(n.uri,i==null?void 0:i.details);this.loadPlaylist(d)}}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._firstLevel}else return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===W.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(t!==void 0&&t.type===V.MAIN){const s=this._levels[t.level];s!==void 0&&(s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=this._levels[i];if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(n.fragmentError===0&&(n.loadError=0),this.playlistLoaded(i,t,n.details)):(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const s=this.currentLevel;if(!s)return;const i=this.hls.audioTracks[t.id].groupId;if(s.audioGroupIds&&s.audioGroupId!==i){let r=-1;for(let n=0;n<s.audioGroupIds.length;n++)if(s.audioGroupIds[n]===i){r=n;break}r!==-1&&r!==s.urlId&&(s.urlId=r,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){const i=s.urlId;let r=s.uri;if(e)try{r=e.addDirectives(r)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}const n=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} URI ${i+1}/${s.url.length} ${r}`),this.clearTimer(),this.hls.trigger(m.LEVEL_LOADING,{url:r,level:t,id:i,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){const s=(r,n)=>n!==t,i=this._levels.filter((r,n)=>n!==e?!0:r.url.length>1&&t!==void 0?(r.url=r.url.filter(s),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(s)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(s)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1));this.hls.trigger(m.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){t.forEach((s,i)=>{const{details:r}=s;r!=null&&r.fragments&&r.fragments.forEach(n=>{n.level=i})}),this._levels=t}}function dt(a,e,t){t&&(e==="audio"?(a.audioGroupIds||(a.audioGroupIds=[]),a.audioGroupIds[a.url.length-1]=t):e==="text"&&(a.textGroupIds||(a.textGroupIds=[]),a.textGroupIds[a.url.length-1]=t))}function fi(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var se={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Mn{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),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;const n=r.end;if(r.start<=e&&n!==null&&e<=n)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const n=s[i[r]];if((n==null?void 0:n.body.type)===t&&n.buffered){const o=n.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,s,i){this.timeRanges&&(this.timeRanges[e]=t);const r=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===s&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return d&&this.removeFragment(o.body),d})})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i}=e;if(!t||s.sn==="initSegment")return;const r=Ue(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(l=>{const c=s.elementaryStreams[l];if(!c)return;const d=t[l],h=o||c.partial===!0;n.range[l]=this.getBufferedTimes(s,i,h,d)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ht(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=s.filter(i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ue(e);let i=this.fragments[s];!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,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||n;for(let d=0;d<i.length;d++){const h=i.start(d)-this.bufferPadding,u=i.end(d)+this.bufferPadding;if(c>=h&&l<=u){r.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(o,i.end(d))});break}else if(n<u&&o>h)r.partial=!0,r.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(o,i.end(d))});else if(o<=h)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const d=l[c];d&&ht(d)&&(i=d.body.start-o,r=d.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=d.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ht(t))}getState(e){const t=Ue(e),s=this.fragments[t];return s?s.buffered?ht(s)?se.PARTIAL:se.OK:se.APPENDING:se.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onFragLoaded(e,t){const{frag:s,part:i}=t;if(s.sn==="initSegment"||s.bitrateTest)return;const r=i?null:t,n=Ue(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(s.sn==="initSegment")return;const n=s.type;if(i){let o=this.activePartLists[n];o||(this.activePartLists[n]=o=[]),o.push(i)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,n,i)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ue(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];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=Ue(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=s.filter(r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ht(a){var e,t,s;return a.buffered&&(a.body.gap||((e=a.range.video)==null?void 0:e.partial)||((t=a.range.audio)==null?void 0:t.partial)||((s=a.range.audiovideo)==null?void 0:s.partial))}function Ue(a){return`${a.type}_${a.level}_${a.urlId}_${a.sn}`}const gi=Math.pow(2,17);class Bn{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Ie({type:G.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(pi(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(i):new n(i),d=mi(e),h=hi(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:gi};e.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,c);let E=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:y})},onError:(f,g,p,y)=>{this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:oe({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))},onProgress:(f,g,p,y)=>{t&&t({frag:e,part:null,payload:p,networkDetails:y})}})})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(pi(e,t));return}const c=this.loader=e.loader=r?new r(i):new n(i),d=mi(e,t),h=hi(i.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gi};t.stats=c.stats,c.load(d,u,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,g,p,y)=>{this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:oe({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,c),l(new Ie({type:G.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,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),h=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function mi(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(B(i)&&B(r)){var n;let o=i,l=r;if(a.sn==="initSegment"&&((n=a.decryptdata)==null?void 0:n.method)==="AES-128"){const c=r-i;c%16&&(l=r+(16-c%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=l}return s}function pi(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:G.MEDIA_ERROR,details:I.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new Ie(s)}class Ie extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Un{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[t].loader;if(s){if(e&&e!==s.context.frag.type)return;s.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=I.KEY_LOAD_ERROR,s,i,r){return new Ie({type:G.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const n=t[r];if(i<=n.cc&&(s==="initSegment"||n.sn==="initSegment"||s<n.sn)){this.emeController.selectKeySystemFormat(n).then(o=>{n.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,c))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let o=this.keyUriToKeyInfo[n];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=s.keyLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{const{frag:y,keyInfo:E,url:S}=g;if(!y.decryptdata||E!==this.keyUriToKeyInfo[S])return o(this.createKeyLoadError(y,I.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(u.data),y.keyLoader=null,E.loader=null,n({frag:y,keyInfo:E})},onError:(u,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,oe({url:l.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,I.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(l,d,h)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}class $n{constructor(){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)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}const Gn={length:0,start:()=>0,end:()=>0};class Q{static isBuffered(e,t){try{if(e){const s=Q.getBuffered(e);for(let i=0;i<s.length;i++)if(t>=s.start(i)&&t<=s.end(i))return!0}}catch{}return!1}static bufferInfo(e,t,s){try{if(e){const i=Q.getBuffered(e),r=[];let n;for(n=0;n<i.length;n++)r.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(r,t,s)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.sort(function(c,d){const h=c.start-d.start;return h||d.end-c.end});let i=[];if(s)for(let c=0;c<e.length;c++){const d=i.length;if(d){const h=i[d-1].end;e[c].start-h<s?e[c].end>h&&(i[d-1].end=e[c].end):i.push(e[c])}else i.push(e[c])}else i=e;let r=0,n,o=t,l=t;for(let c=0;c<i.length;c++){const d=i[c].start,h=i[c].end;if(t+s>=d&&t<h)o=d,l=h,r=l-t;else if(t+s<d){n=d;break}}return{len:r,start:o||0,end:l||0,nextStart:n}}static getBuffered(e){try{return e.buffered}catch(t){return v.log("failed to get media.buffered",t),Gn}}}class Ht{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=ut(),this.buffering={audio:ut(),video:ut(),audiovideo:ut()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function ut(){return{start:0,executeStart:0,executeEnd:0,end:0}}function yi(a,e){let t=null;for(let s=0,i=a.length;s<i;s++){const r=a[s];if(r&&r.cc===e){t=r;break}}return t}function Vn(a,e,t){return!!(e.details&&(t.endCC>t.startCC||a&&a.cc<t.startCC))}function Kn(a,e,t=0){const s=a.fragments,i=e.fragments;if(!i.length||!s.length){v.log("No fragments to align");return}const r=yi(s,i[0].cc);if(!r||r&&!r.startPTS){v.log("No frag in previous level to align on");return}return r}function Ti(a,e){if(a){const t=a.start+e;a.start=a.startPTS=t,a.endPTS=t+a.duration}}function Wt(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Ti(t[s],a);e.fragmentHint&&Ti(e.fragmentHint,a),e.alignedSliding=!0}function Hn(a,e,t){e&&(Wn(a,t,e),!t.alignedSliding&&e.details&&Yn(t,e.details),!t.alignedSliding&&e.details&&!t.skippedSegments&&oi(e.details,t))}function Wn(a,e,t){if(Vn(a,t,e)){const s=Kn(t.details,e);s&&B(s.start)&&(v.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Wt(s.start,e))}}function Yn(a,e){if(!e.fragments.length||!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=e.fragments[0].programDateTime,s=a.fragments[0].programDateTime,i=(s-t)/1e3+e.fragments[0].start;i&&B(i)&&(v.log(`Adjusting PTS using programDateTime delta ${s-t}ms, sliding:${i.toFixed(3)} ${a.url} `),Wt(i,a))}function Ei(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;const i=Math.round(s.length/2)-1,r=s[i],n=yi(t,r.cc)||t[Math.round(t.length/2)-1],o=r.programDateTime,l=n.programDateTime;if(o===null||l===null)return;const c=(l-o)/1e3-(n.start-r.start);Wt(c,a)}class qn{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class zn{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function jn(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?Pe(a,0,e-t):a}class Xn{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],n=s[2],o=s[3],l=this.invSubMix,c=l[0],d=l[1],h=l[2],u=l[3],f=new Uint32Array(256);let g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const S=f[g],x=f[S],R=f[x];let L=f[E]*257^E*16843008;i[g]=L<<24|L>>>8,r[g]=L<<16|L>>>16,n[g]=L<<8|L>>>24,o[g]=L,L=R*16843009^x*65537^S*257^g*16843008,c[E]=L<<24|L>>>8,d[E]=L<<16|L>>>16,h[E]=L<<8|L>>>24,u[E]=L,g?(g=S^f[f[f[R^S]]],p^=f[f[p]]):g=p=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 n=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],p=f[1],y=f[2],E=f[3];let S,x;for(o=0;o<n;o++){if(o<r){S=c[o]=t[o];continue}x=S,o%r===0?(x=x<<8|x>>>24,x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255],x^=u[o/r|0]<<24):r>6&&o%r===4&&(x=h[x>>>24]<<24|h[x>>>16&255]<<16|h[x>>>8&255]<<8|h[x&255]),c[o]=S=(c[o-r]^x)>>>0}for(l=0;l<n;l++)o=n-l,l&3?x=c[o]:x=c[o-4],l<4||o<=4?d[l]=x:d[l]=g[h[x>>>24]]^p[h[x>>>16&255]]^y[h[x>>>8&255]]^E[h[x&255]],d[l]=d[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,n=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],d=o[2],h=o[3],u=this.uint8ArrayToUint32Array_(s);let f=u[0],g=u[1],p=u[2],y=u[3];const E=new Int32Array(e),S=new Int32Array(E.length);let x,R,L,_,D,k,P,b,U,O,Y,re,j,J;const X=this.networkToHostOrderSwap;for(;t<E.length;){for(U=X(E[t]),O=X(E[t+1]),Y=X(E[t+2]),re=X(E[t+3]),D=U^r[0],k=re^r[1],P=Y^r[2],b=O^r[3],j=4,J=1;J<i;J++)x=l[D>>>24]^c[k>>16&255]^d[P>>8&255]^h[b&255]^r[j],R=l[k>>>24]^c[P>>16&255]^d[b>>8&255]^h[D&255]^r[j+1],L=l[P>>>24]^c[b>>16&255]^d[D>>8&255]^h[k&255]^r[j+2],_=l[b>>>24]^c[D>>16&255]^d[k>>8&255]^h[P&255]^r[j+3],D=x,k=R,P=L,b=_,j=j+4;x=n[D>>>24]<<24^n[k>>16&255]<<16^n[P>>8&255]<<8^n[b&255]^r[j],R=n[k>>>24]<<24^n[P>>16&255]<<16^n[b>>8&255]<<8^n[D&255]^r[j+1],L=n[P>>>24]<<24^n[b>>16&255]<<16^n[D>>8&255]<<8^n[k&255]^r[j+2],_=n[b>>>24]<<24^n[D>>16&255]<<16^n[k>>8&255]<<8^n[P&255]^r[j+3],S[t]=X(x^f),S[t+1]=X(_^g),S[t+2]=X(L^p),S[t+3]=X(R^y),f=U,g=O,p=Y,y=re,t=t+4}return S.buffer}}const Qn=16;class Yt{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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);return this.reset(),this.removePKCS7Padding?jn(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s){return this.useSoftware?new Promise((i,r)=>{this.softwareDecrypt(new Uint8Array(e),t,s);const n=this.flush();n?i(n.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s)}softwareDecrypt(e,t,s){const{currentIV:i,currentResult:r,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(e=Fe(n,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Xn),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=Pe(o,-16).buffer,c||null}webCryptoDecrypt(e,t,s){const i=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new zn(i,t)),this.fastAesKey.expandKey().then(r=>i?(this.logOnce("WebCrypto AES decrypt"),new qn(i,new Uint8Array(s)).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(v.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s)))}onWebCryptoError(e,t,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%Qn;return s!==e.length&&(t=Pe(e,0,s),this.remainderData=Pe(e,s)),t}logOnce(e){this.logEnabled&&(v.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Jn={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},C={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 qt extends $n{constructor(e,t,s,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.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=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=v.log.bind(v,`${i}:`),this.warn=v.warn.bind(v,`${i}:`),this.hls=e,this.fragmentLoader=new Bn(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Yt(e.config),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.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=C.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const s=t.partList;if(s!=null&&s.length){const r=s[s.length-1];return Q.isBuffered(this.media,r.start+r.duration/2)}const i=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levels[this.levelLastLoaded])==null?void 0:e.details}}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,o=Q.bufferInfo(i||s,n,e.maxBufferHole);if(this.log(`media seeking to ${B(n)?n.toFixed(3):n}, state: ${r}`),this.state===C.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,d=t.start+t.duration+l;if(!o.len||d<o.start||c>o.end){const h=n>d;(n<c||h)&&(h&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state;if(this.fragContextChanged(e)){(n===C.FRAG_LOADING||!this.fragCurrent&&n===C.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===se.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&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)===se.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{if(!s||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{payload:r}=s,n=e.decryptdata;if(r&&r.byteLength>0&&n&&n.key&&n.iv&&n.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch(l=>{throw i.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),s.payload=l,s})}return s}).then(s=>{const{fragCurrent:i,hls:r,levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const o=e.stats;this.state=C.IDLE,t.fragmentError=0,e.data=new Uint8Array(s.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),s.frag===i&&r.trigger(m.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:e.type}),this.tick()}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var s,i,r,n;const o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===V.MAIN?"level":"track"} ${e.level} (frag:[${((s=e.startPTS)!=null?s:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${o?Jn.toString(Q.getBuffered(o)):"(detached)"})`),this.state=C.IDLE,o&&(!this.loadedmetadata&&e.type==V.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((n=this.fragPrevious)==null?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(l=>!l),o=new Ht(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;const n=t==null?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===C.KEY_LOADING&&(this.state=C.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments),s=Math.max(e.start,s||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const d=n.partList;if(d&&i){s>e.end&&n.fragmentHint&&(e=n.fragmentHint);const h=this.getNextPart(d,e,s);if(h>-1){const u=d[h];this.log(`Loading part sn: ${e.sn} p: ${u.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${h}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=C.FRAG_LOADING;let f;return o?f=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,u,t,i)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,u,t,i).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:u,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(d=>!d||this.fragContextChanged(d==null?void 0:d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):c=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([d])=>(!l&&d&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const l=[],c=(o=s.details)==null?void 0:o.partList,d=h=>{this.fragmentLoader.loadPart(e,h,i).then(u=>{l[h.index]=u;const f=u.part;this.hls.trigger(m.FRAG_LOADED,u);const g=li(s,e.sn,h.index+1)||ci(c,e.sn,h.index+1);if(g)d(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===I.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:G.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(s,i,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const o=t[i],l=n>-1?li(o,r,n):null,c=l?l.fragment:Dn(o,r,s);return c?(s&&s!==c&&(c.stats=s.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var n;if(!e||this.state!==C.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=Fe(o,l)),!((n=c)!=null&&n.length))return;const d={type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=Q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const s=this.getLoadPosition();return B(s)?this.getFwdBufferInfoAtPos(e,s,t):null}getFwdBufferInfoAtPos(e,t,s){const{config:{maxBufferHole:i}}=this,r=Q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&r.nextStart<n.end)return Q.bufferInfo(e,t,Math.max(r.nextStart,i))}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)}reduceMaxBufferLength(e){const t=this.config,s=e||t.maxBufferLength;return t.maxMaxBufferLength>=s?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=V.MAIN){const s=this.fragmentTracker.getAppendedFrag(e,V.MAIN);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(o=this.getInitialLiveFragment(t,s),this.startPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=n&&(o=s[0]);if(!o){const l=r.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===se.OK||s===se.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){const n=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,n&&e&&!e.gap&&s.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(l!==null&&s.len+l.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(n=n&&!c.independent,i>-1&&s<c.start)break;const d=c.loaded;d?i=-1:(r||c.independent||n)&&c.fragment===t&&(i=o),r=d}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=_n(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=wn(t,s.cc),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:n,endSN:o}=s;const{fragmentHint:l}=s,c=i.maxFragLookUpTolerance,d=s.partList,h=!!(i.lowLatencyMode&&d!=null&&d.length&&l);h&&l&&!this.bitrateTest&&(n=n.concat(l),o=l.sn);let u;if(e<t){const f=e>t-c?0:c;u=ze(r,n,e,f)}else u=n[n.length-1];if(u){const f=u.sn-s.startSN,g=this.fragmentTracker.getState(u);if((g===se.OK||g===se.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!h||d[0].fragment.sn>u.sn)&&r&&u.level===r.level){const y=n[f+1];u.sn<o&&this.fragmentTracker.getState(y)!==se.OK?u=y:u=null}}return u}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=s.currentTime,n=e.fragments[0].start,o=e.edge,l=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&s.readyState<4||r<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}}alignPlaylists(e,t){const{levels:s,levelLastLoaded:i,fragPrevious:r}=this,n=i!==null?s[i]:null,o=e.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const l=e.fragments[0].start,c=!t,d=e.alignedSliding&&B(l);if(c||!d&&!l){Hn(r,n,e);const h=e.fragments[0].start;return this.log(`Live playlist sliding: ${h.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${o}`),h}return l}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;if(s<t&&(s=-1),s===-1||this.lastCurrentTime===-1){const i=this.startTimeOffset!==null,r=i?this.startTimeOffset:e.startTimeOffset;r!==null&&B(r)?(s=t+r,r<0&&(s+=e.totalduration),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):e.live?s=this.hls.liveSyncPosition||t:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const h=this.getCurrentContext(t.chunkMeta);h&&(t.frag=h.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const r=t.details===I.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=n||{};if(n&&o===ne.RetryRequest&&c){var d;this.resetStartWhenNotLoaded((d=this.levelLastLoaded)!=null?d:s.level);const h=$t(c,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),n.resolved=!0,this.retryDate=self.performance.now()+h,this.state=C.FRAG_LOADING_WAITING_RETRY}else c&&n?(this.resetFragmentErrors(e),l<c.maxNumRetry?r||(n.resolved=!0):v.warn(`${t.details} reached or exceeded max retry (${l})`)):(n==null?void 0:n.action)===ne.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){const t=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,t),i=s&&s.len>.5;i&&this.reduceMaxBufferLength(s.len);const r=!i;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(e){e===V.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=Q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=C.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded((t=this.levelLastLoaded)!=null?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){var r;const n=s.details;if(!n){this.warn("level.details undefined");return}if(Object.keys(e.elementaryStreams).reduce((l,c)=>{const d=e.elementaryStreams[c];if(d){const h=d.endPTS-d.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const u=i?0:ai(n,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:n,level:s,drift:u,type:c,frag:e,start:d.startPTS,end:d.endPTS}),!0}return l},!1))s.fragmentError=0;else if(((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(s.fragmentError===0&&(s.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=C.PARSED,this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){if(e.event==="demuxerWorker"){var t,s,i;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded((t=(s=this.levelLastLoaded)!=null?s:(i=this.fragCurrent)==null?void 0:i.level)!=null?t:0),this.resetLoadingState()}}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function xi(){return self.SourceBuffer||self.WebKitSourceBuffer}function Zn(){const a=at();if(!a)return!1;const e=xi(),t=a&&typeof a.isTypeSupported=="function"&&a.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),s=!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function";return!!t&&!!s}function ea(){var a;const e=xi();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}function ta(){return typeof __HLS_WORKER_BUNDLE__=="function"}function sa(){const a=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(a);return{worker:new self.Worker(e),objectURL:e}}function ia(a){const e=new self.URL(a,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function ve(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Si{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=Fe(this.cachedData,e),this.cachedData=null);let s=st(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,l=s?Br(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&B(l))&&(this.basePTS=ra(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:ye.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const d=this.appendFrame(n,e,i);d?(this.frameIndex++,this.lastPTS=d.sample.pts,i+=d.length,r=i):i=c}else Mr(e,i)?(s=st(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ye.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const d=Pe(e,r);this.cachedData?this.cachedData=Fe(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:ve(),id3Track:o,textTrack:ve()}}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:ve(),id3Track:this._id3Track,textTrack:ve()}}destroy(){}}const ra=(a,e,t)=>{if(B(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};function na(a,e,t,s){let i,r,n,o;const l=navigator.userAgent.toLowerCase(),c=s,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>d.length-1){a.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${h}`});return}return n=(e[t+2]&1)<<2,n|=(e[t+3]&192)>>>6,v.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(i=5,o=new Array(4),r=h-3):(i=2,o=new Array(2),r=h):l.indexOf("android")!==-1?(i=2,o=new Array(2),r=h):(i=5,o=new Array(4),s&&(s.indexOf("mp4a.40.29")!==-1||s.indexOf("mp4a.40.5")!==-1)||!s&&h>=6?r=h-3:((s&&s.indexOf("mp4a.40.2")!==-1&&(h>=6&&n===1||/vivaldi/i.test(l))||!s&&n===1)&&(i=2,o=new Array(2)),r=h)),o[0]=i<<3,o[0]|=(h&14)>>1,o[1]|=(h&1)<<7,o[1]|=n<<3,i===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[h],channelCount:n,codec:"mp4a.40."+i,manifestCodec:c}}function vi(a,e){return a[e]===255&&(a[e+1]&246)===240}function Li(a,e){return a[e+1]&1?7:9}function zt(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function aa(a,e){return e+5<a.length}function ft(a,e){return e+1<a.length&&vi(a,e)}function oa(a,e){return aa(a,e)&&vi(a,e)&&zt(a,e)<=a.length-e}function la(a,e){if(ft(a,e)){const t=Li(a,e);if(e+t>=a.length)return!1;const s=zt(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||ft(a,i)}return!1}function Ai(a,e,t,s,i){if(!a.samplerate){const r=na(e,t,s,i);if(!r)return;a.config=r.config,a.samplerate=r.samplerate,a.channelCount=r.channelCount,a.codec=r.codec,a.manifestCodec=r.manifestCodec,v.log(`parsed codec:${a.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function Ii(a){return 1024*9e4/a}function ca(a,e){const t=Li(a,e);if(e+t<=a.length){const s=zt(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Ri(a,e,t,s,i){const r=Ii(a.samplerate),n=s+i*r,o=ca(e,t);let l;if(o){const{frameLength:h,headerLength:u}=o,f=u+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);const p={unit:l,pts:n};return g||a.samples.push(p),{sample:p,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:n},length:c,missing:-1}}class da extends Si{constructor(e,t){super(),this.observer=void 0,this.config=void 0,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){if(!e)return!1;let s=(st(e,0)||[]).length;for(let i=e.length;s<i;s++)if(la(e,s))return v.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return oa(e,t)}appendFrame(e,t,s){Ai(e,this.observer,t,s,e.manifestCodec);const i=Ri(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const ha=/\/emsg[-/]ID3/i;class ua{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=ve("video",1),n=this.audioTrack=ve("audio",1),o=this.txtTrack=ve("text",1);if(this.id3Track=ve("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=Bs(e);if(l.video){const{id:c,timescale:d,codec:h}=l.video;r.id=c,r.timescale=o.timescale=d,r.codec=h}if(l.audio){const{id:c,timescale:d,codec:h}=l.audio;n.id=c,n.timescale=d,n.codec=h}o.id=Os.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return e=e.length>16384?e.subarray(0,16384):e,H(e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Fe(this.remainderData,e));const o=Zr(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=$s(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=$s(e,t),{videoTrack:t,audioTrack:ve(),id3Track:i,textTrack:ve()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=H(e.samples,["emsg"]);i&&i.forEach(r=>{const n=sn(r);if(ha.test(n.schemeIdUri)){const o=B(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale;let l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=n.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:ye.emsg,duration:l})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let gt=null;const fa=[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],ga=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ma=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],pa=[0,1,1,4];function bi(a,e,t,s,i){if(t+24>e.length)return;const r=Di(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Di(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,l=t===3?3-s:s===3?3:4,c=fa[l*14+i-1]*1e3,h=ga[(t===3?0:t===2?1:2)*3+r],u=o===3?1:2,f=ma[t][s],g=pa[s],p=f*8*g,y=Math.floor(f*c/h+n)*g;if(gt===null){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gt=x?parseInt(x[1]):0}return!!gt&><=87&&s===2&&c>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:h,channelCount:u,frameLength:y,samplesPerFrame:p}}}function jt(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function Ci(a,e){return e+1<a.length&&jt(a,e)}function ya(a,e){return jt(a,e)&&4<=a.length-e}function Ta(a,e){if(e+1<a.length&&jt(a,e)){const s=Di(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||Ci(a,r)}return!1}class _i{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&&v.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)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)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,s=8,i;for(let r=0;r<e;r++)s!==0&&(i=this.readEG(),s=(t+i+256)%256),t=s===0?t:s}readSPS(){let e=0,t=0,s=0,i=0,r,n,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),d=this.readUEG.bind(this),h=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);l();const y=l();if(c(5),u(3),l(),g(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const _=d();if(_===3&&u(1),g(),g(),u(1),h())for(n=_!==3?8:12,o=0;o<n;o++)h()&&(o<6?p(16):p(64))}g();const E=d();if(E===0)d();else if(E===1)for(u(1),f(),f(),r=d(),o=0;o<r;o++)f();g(),u(1);const S=d(),x=d(),R=c(1);R===0&&u(1),u(1),h()&&(e=d(),t=d(),s=d(),i=d());let L=[1,1];if(h()&&h())switch(l()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:{L=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((S+1)*16-e*2-t*2),height:(2-R)*(x+1)*16-(R?2:4)*(s+i),pixelRatio:L}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Ea{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Yt(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,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 n=Vs(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(n,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,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 n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}const ae=188;class Ce{constructor(e,t,s){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._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=s}static probe(e){const t=Ce.syncOffset(e);return t>0&&v.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let s=Math.min(ae*5,e.length-ae)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let l=i;l<t;l+=ae)if(e[l]===71){if(o++,n===-1&&(n=l,n!==0&&(s=Math.min(n+ae*99,e.length-ae)+1)),r||(r=Xt(e,l)===0),r&&o>1&&(n===0&&o>2||l+ae>s))return n}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:Os[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Ce.createTrack("video"),this._audioTrack=Ce.createTrack("audio",i),this._id3Track=Ce.createTrack("id3"),this._txtTrack=Ce.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._avcTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let d=n.pid,h=n.pesData,u=o.pid,f=l.pid,g=o.pesData,p=l.pesData,y=null,E=this.pmtParsed,S=this._pmtId,x=e.length;if(this.remainderData&&(e=Fe(this.remainderData,e),x=e.length,this.remainderData=null),x<ae&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:l,textTrack:c};const R=Math.max(0,Ce.syncOffset(e));x-=(x-R)%ae,x<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let L=0;for(let D=R;D<x;D+=ae)if(e[D]===71){const k=!!(e[D+1]&64),P=Xt(e,D),b=(e[D+3]&48)>>4;let U;if(b>1){if(U=D+5+e[D+4],U===D+ae)continue}else U=D+4;switch(P){case d:k&&(h&&(r=$e(h))&&this.parseAVCPES(n,c,r,!1),h={data:[],size:0}),h&&(h.data.push(e.subarray(U,D+ae)),h.size+=D+ae-U);break;case u:if(k){if(g&&(r=$e(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(U,D+ae)),g.size+=D+ae-U);break;case f:k&&(p&&(r=$e(p))&&this.parseID3PES(l,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(U,D+ae)),p.size+=D+ae-U);break;case 0:k&&(U+=e[U]+1),S=this._pmtId=xa(e,U);break;case S:{k&&(U+=e[U]+1);const O=Sa(e,U,this.typeSupported,s);d=O.avc,d>0&&(n.pid=d),u=O.audio,u>0&&(o.pid=u,o.segmentCodec=O.segmentCodec),f=O.id3,f>0&&(l.pid=f),y!==null&&!E&&(v.warn(`MPEG-TS PMT found at ${D} after unknown PID '${y}'. Backtracking to sync byte @${R} to parse all TS packets.`),y=null,D=R-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=P;break}}else L++;if(L>0){const D=new Error(`Found ${L} TS packet/s that do not start with 0x47`);this.observer.emit(m.ERROR,m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message})}n.pesData=h,o.pesData=g,l.pesData=p;const _={audioTrack:o,videoTrack:n,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(_),_}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,l=i.pesData;let c;if(n&&(c=$e(n))?(this.parseAVCPES(s,r,c,!0),s.pesData=null):s.pesData=n,o&&(c=$e(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break}t.pesData=null}else o!=null&&o.size&&v.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=$e(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new Ea(this.observer,this.config,t);return this.decrypt(i,r)}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._duration=0}parseAVCPES(e,t,s,i){const r=this.parseAVCNALu(e,s.data);let n=this.avcSample,o,l=!1;s.data=null,n&&r.length&&!e.audFound&&(je(n,e),n=this.avcSample=mt(!1,s.pts,s.dts,"")),r.forEach(c=>{var d;switch(c.type){case 1:{let u=!1;o=!0;const f=c.data;if(l&&f.length>4){const g=new _i(f).readSliceType();(g===2||g===4||g===7||g===9)&&(u=!0)}if(u){var h;(h=n)!=null&&h.frame&&!n.key&&(je(n,e),n=this.avcSample=null)}n||(n=this.avcSample=mt(!0,s.pts,s.dts,"")),n.frame=!0,n.key=u;break}case 5:o=!0,(d=n)!=null&&d.frame&&!n.key&&(je(n,e),n=this.avcSample=null),n||(n=this.avcSample=mt(!0,s.pts,s.dts,"")),n.key=!0,n.frame=!0;break;case 6:{o=!0,Gs(c.data,1,s.pts,t.samples);break}case 7:if(o=!0,l=!0,!e.sps){const u=c.data,g=new _i(u).readSPS();e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[u],e.duration=this._duration;const p=u.subarray(1,4);let y="avc1.";for(let E=0;E<3;E++){let S=p[E].toString(16);S.length<2&&(S="0"+S),y+=S}e.codec=y}break;case 8:o=!0,e.pps||(e.pps=[c.data]);break;case 9:o=!1,e.audFound=!0,n&&je(n,e),n=this.avcSample=mt(!1,s.pts,s.dts,"");break;case 12:o=!0;break;default:o=!1,n&&(n.debug+="unknown NAL "+c.type+" ");break}n&&o&&n.units.push(c)}),i&&n&&(je(n,e),this.avcSample=null)}getLastNalUnit(e){var t;let s=this.avcSample,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}parseAVCNALu(e,t){const s=t.byteLength;let i=e.naluState||0;const r=i,n=[];let o=0,l,c,d,h=-1,u=0;for(i===-1&&(h=0,u=t[0]&31,i=0,o=1);o<s;){if(l=t[o++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(h>=0){const f={data:t.subarray(h,o-i-1),type:u};n.push(f)}else{const f=this.getLastNalUnit(e.samples);if(f&&(r&&o<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),c=o-i-1,c>0)){const g=new Uint8Array(f.data.byteLength+c);g.set(f.data,0),g.set(t.subarray(0,c),f.data.byteLength),f.data=g,f.state=0}}o<s?(d=t[o]&31,h=o,u=d,i=0):i=-1}else i=0}if(h>=0&&i>=0){const f={data:t.subarray(h,s),type:u,state:i};n.push(f)}if(n.length===0){const f=this.getLastNalUnit(e.samples);if(f){const g=new Uint8Array(f.data.byteLength+t.byteLength);g.set(f.data,0),g.set(t,f.data.byteLength),f.data=g}}return e.naluState=i,n}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const h=i.missing,u=i.sample.unit.byteLength;if(h===-1){const f=new Uint8Array(u+r.byteLength);f.set(i.sample.unit,0),f.set(r,u),r=f}else{const f=u-h;i.sample.unit.set(r.subarray(0,h),f),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!ft(r,n);n++);if(n!==s){let h;const u=n<o-1;u?h=`AAC PES did not start with ADTS header,offset:${n}`:h="No ADTS header found in AAC PES";const f=new Error(h);if(v.warn(`parsing error: ${h}`),this.observer.emit(m.ERROR,m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:h}),!u)return}Ai(e,this.observer,r,n,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(i){const h=Ii(e.samplerate);l=i.sample.pts+h}else{v.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,d;for(;n<o;)if(d=Ri(e,r,n,l,c),n+=d.length,d.missing){this.aacOverFlow=d;break}else for(c++;n<o-1&&!ft(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){v.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(Ci(s,n)){const l=bi(e,s,n,o,r);if(l)n+=l.length,r++;else break}else n++}parseID3PES(e,t){if(t.pts===void 0){v.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=te({},t,{type:this._avcTrack?ye.emsg:ye.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function mt(a,e,t,s){return{key:a,frame:!1,pts:e,dts:t,units:[],debug:s,length:0}}function Xt(a,e){return((a[e+1]&31)<<8)+a[e+2]}function xa(a,e){return(a[e+10]&31)<<8|a[e+11]}function Sa(a,e,t,s){const i={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},r=(a[e+1]&15)<<8|a[e+2],n=e+3+r-4,o=(a[e+10]&15)<<8|a[e+11];for(e+=12+o;e<n;){const l=Xt(a,e);switch(a[e]){case 207:if(!s){v.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:i.audio===-1&&(i.audio=l);break;case 21:i.id3===-1&&(i.id3=l);break;case 219:if(!s){v.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:i.avc===-1&&(i.avc=l);break;case 3:case 4:t.mpeg!==!0&&t.mp3!==!0?v.log("MPEG audio found, not supported in this browser"):i.audio===-1&&(i.audio=l,i.segmentCodec="mp3");break;case 36:v.warn("Unsupported HEVC stream type found");break}e+=((a[e+3]&15)<<8|a[e+4])+5}return i}function $e(a){let e=0,t,s,i,r,n;const o=a.data;if(!a||a.size===0)return null;for(;o[0].length<19&&o.length>1;){const c=new Uint8Array(o[0].length+o[1].length);c.set(o[0]),c.set(o[1],o[0].length),o[0]=c,o.splice(1,1)}if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(s=(t[4]<<8)+t[5],s&&s>a.size-6)return null;const c=t[7];c&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(n=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-n>60*9e4&&(v.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),i=t[8];let d=i+9;if(a.size<=d)return null;a.size-=d;const h=new Uint8Array(a.size);for(let u=0,f=o.length;u<f;u++){t=o[u];let g=t.byteLength;if(d)if(d>g){d-=g;continue}else t=t.subarray(d),g-=d,d=0;h.set(t,e),e+=g}return s&&(s-=i+3),{data:h,pts:r,dts:n,len:s}}return null}function je(a,e){if(a.units.length&&a.frame){if(a.pts===void 0){const t=e.samples,s=t.length;if(s){const i=t[s-1];a.pts=i.pts,a.dts=i.dts}else{e.dropped++;return}}e.samples.push(a)}a.debug.length&&v.log(a.pts+"/"+a.dts+":"+a.debug)}class va extends Si{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;let s=(st(e,0)||[]).length;for(let i=e.length;s<i;s++)if(Ta(e,s))return v.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return ya(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return bi(e,t,s,this.basePTS,this.frameIndex)}}class ki{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}}}const _e=Math.pow(2,32)-1;class A{static init(){A.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in A.types)A.types.hasOwnProperty(e)&&(A.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);A.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);A.STTS=A.STSC=A.STCO=r,A.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),A.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),A.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),A.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);A.FTYP=A.box(A.types.ftyp,n,l,n,o),A.DINF=A.box(A.types.dinf,A.box(A.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return A.box(A.types.hdlr,A.HDLR_TYPES[e])}static mdat(e){return A.box(A.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(_e+1)),i=Math.floor(t%(_e+1));return A.box(A.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,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 A.box(A.types.mdia,A.mdhd(e.timescale,e.duration),A.hdlr(e.type),A.minf(e))}static mfhd(e){return A.box(A.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?A.box(A.types.minf,A.box(A.types.smhd,A.SMHD),A.DINF,A.stbl(e)):A.box(A.types.minf,A.box(A.types.vmhd,A.VMHD),A.DINF,A.stbl(e))}static moof(e,t,s){return A.box(A.types.moof,A.mfhd(e),A.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=A.trak(e[t]);return A.box.apply(null,[A.types.moov,A.mvhd(e[0].timescale,e[0].duration)].concat(s).concat(A.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=A.trex(e[t]);return A.box.apply(null,[A.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(_e+1)),i=Math.floor(t%(_e+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 A.box(A.types.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 A.box(A.types.sdtp,s)}static stbl(e){return A.box(A.types.stbl,A.stsd(e),A.box(A.types.stts,A.STTS),A.box(A.types.stsc,A.STSC),A.box(A.types.stsz,A.STSZ),A.box(A.types.stco,A.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=A.box(A.types.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,d=e.pixelRatio[0],h=e.pixelRatio[1];return A.box(A.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,A.box(A.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),A.box(A.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return A.box(A.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]),A.box(A.types.esds,A.esds(e)))}static mp3(e){const t=e.samplerate;return A.box(A.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?A.box(A.types.stsd,A.STSD,A.mp3(e)):A.box(A.types.stsd,A.STSD,A.mp4a(e)):A.box(A.types.stsd,A.STSD,A.avc1(e))}static tkhd(e){const t=e.id,s=e.duration*e.timescale,i=e.width,r=e.height,n=Math.floor(s/(_e+1)),o=Math.floor(s%(_e+1));return A.box(A.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&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=A.sdtp(e),i=e.id,r=Math.floor(t/(_e+1)),n=Math.floor(t%(_e+1));return A.box(A.types.traf,A.box(A.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),A.box(A.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),A.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,A.box(A.types.trak,A.tkhd(e),A.mdia(e))}static trex(e){const t=e.id;return A.box(A.types.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,n=new Uint8Array(r);let o,l,c,d,h,u;for(t+=8+r,n.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,d=l.size,h=l.flags,u=l.cts,n.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return A.box(A.types.trun,n)}static initSegment(e){A.types||A.init();const t=A.moov(e),s=new Uint8Array(A.FTYP.byteLength+t.byteLength);return s.set(A.FTYP),s.set(t,A.FTYP.byteLength),s}}A.types=void 0,A.HDLR_TYPES=void 0,A.STTS=void 0,A.STSC=void 0,A.STCO=void 0,A.STSZ=void 0,A.VMHD=void 0,A.SMHD=void 0,A.STSD=void 0,A.FTYP=void 0,A.DINF=void 0;const wi=9e4;function Qt(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function La(a,e,t=1,s=!1){return Qt(a,e,1/t,s)}function Xe(a,e=!1){return Qt(a,1e3,1/wi,e)}function Aa(a,e=1){return Qt(a,wi,1/e)}const Ia=10*1e3,Pi=1024,Ra=1152;let pt=null,Jt=null;class Zt{constructor(e,t,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,pt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);pt=n?parseInt(n[1]):0}if(Jt===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Jt=r?parseInt(r[1]):0}}destroy(){}resetTimeStamp(e){v.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){v.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){v.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const s=e.reduce((i,r)=>{const n=r.pts-i;return n<-4294967296?(t=!0,fe(i,r.pts)):n>0?i:r.pts},e[0].pts);return t&&v.debug("PTS rollover detected"),s}remux(e,t,s,i,r,n,o,l){let c,d,h,u,f,g,p=r,y=r;const E=e.pid>-1,S=t.pid>-1,x=t.samples.length,R=e.samples.length>0,L=o&&x>0||x>1;if((!E||R)&&(!S||L)||this.ISGenerated||o){this.ISGenerated||(h=this.generateIS(e,t,r,n));const D=this.isVideoContiguous;let k=-1,P;if(L&&(k=ba(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,k>0){v.warn(`[mp4-remuxer]: Dropped ${k} out of ${x} video samples due to a missing keyframe`);const b=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(k),t.dropped+=k,y+=(t.samples[0].pts-b)/t.inputTimeScale,P=y}else k===-1&&(v.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),g=!1);if(this.ISGenerated){if(R&&L){const b=this.getVideoStartPts(t.samples),O=(fe(e.samples[0].pts,b)-b)/t.inputTimeScale;p+=Math.max(0,O),y+=Math.max(0,-O)}if(R){if(e.samplerate||(v.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,p,this.isAudioContiguous,n,S||L||l===V.AUDIO?y:void 0),L){const b=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(v.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,n)),c=this.remuxVideo(t,y,D,b)}}else L&&(c=this.remuxVideo(t,y,D,0));c&&(c.firstKeyFrame=k,c.independent=k!==-1,c.firstKeyFramePTS=P)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Fi(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Oi(i,r,this._initPTS))),{audio:d,video:c,initSegment:h,independent:g,text:u,id3:f}}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,l={},c=this._initPTS;let d=!c||i,h="audio/mp4",u,f,g;if(d&&(u=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):A.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(g=e.inputTimeScale,!c||g!==c.timescale?u=f=r[0].pts-Math.round(g*s):d=!1)}if(t.sps&&t.pps&&n.length&&(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:A.initSegment([t]),metadata:{width:t.width,height:t.height}},d))if(g=t.inputTimeScale,!c||g!==c.timescale){const p=this.getVideoStartPts(n),y=Math.round(g*s);f=Math.min(f,fe(n[0].dts,p)-y),u=Math.min(u,p-y)}else d=!1;if(Object.keys(l).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:u,timescale:g},this._initDTS={baseTime:f,timescale:g}):u=g=void 0,{tracks:l,initPTS:u,timescale:g}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],l=n.length,c=this._initPTS;let d=this.nextAvcDts,h=8,u=this.videoSampleDuration,f,g,p=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!s||d===null){const N=t*r,$=n[0].pts-fe(n[0].dts,n[0].pts);d=N-$}const S=c.baseTime*r/c.timescale;for(let N=0;N<l;N++){const $=n[N];$.pts=fe($.pts-S,d),$.dts=fe($.dts-S,d),$.dts<n[N>0?N-1:N].dts&&(E=!0)}E&&n.sort(function(N,$){const w=N.dts-$.dts,F=N.pts-$.pts;return w||F}),f=n[0].dts,g=n[n.length-1].dts;const x=g-f,R=x?Math.round(x/(l-1)):u||e.inputTimeScale/30;if(s){const N=f-d,$=N>R,w=N<-1;if(($||w)&&($?v.warn(`AVC: ${Xe(N,!0)} ms (${N}dts) hole between fragments detected, filling it`):v.warn(`AVC: ${Xe(-N,!0)} ms (${N}dts) overlapping between fragments detected`),!w||d>=n[0].pts)){f=d;const F=n[0].pts-N;n[0].dts=f,n[0].pts=F,v.log(`Video: First PTS/DTS adjusted: ${Xe(F,!0)}/${Xe(f,!0)}, delta: ${Xe(N,!0)} ms`)}}f=Math.max(0,f);let L=0,_=0;for(let N=0;N<l;N++){const $=n[N],w=$.units,F=w.length;let M=0;for(let q=0;q<F;q++)M+=w[q].data.length;_+=M,L+=F,$.length=M,$.dts=Math.max($.dts,f),p=Math.min($.pts,p),y=Math.max($.pts,y)}g=n[l-1].dts;const D=_+4*L+8;let k;try{k=new Uint8Array(D)}catch(N){this.observer.emit(m.ERROR,m.ERROR,{type:G.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:N,bytes:D,reason:`fail allocating video mdat ${D}`});return}const P=new DataView(k.buffer);P.setUint32(0,D),k.set(A.types.mdat,4);let b=!1,U=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,Y=Number.NEGATIVE_INFINITY,re=Number.NEGATIVE_INFINITY;for(let N=0;N<l;N++){const $=n[N],w=$.units;let F=0;for(let he=0,Ee=w.length;he<Ee;he++){const me=w[he],Me=me.data,xs=me.data.byteLength;P.setUint32(h,xs),h+=4,k.set(Me,h),h+=xs,F+=4+xs}let M;if(N<l-1)u=n[N+1].dts-$.dts,M=n[N+1].pts-$.pts;else{const he=this.config,Ee=N>0?$.dts-n[N-1].dts:R;if(M=N>0?$.pts-n[N-1].pts:R,he.stretchShortVideoTrack&&this.nextAudioPts!==null){const me=Math.floor(he.maxBufferHole*r),Me=(i?p+i*r:this.nextAudioPts)-$.pts;Me>me?(u=Me-Ee,u<0?u=Ee:b=!0,v.log(`[mp4-remuxer]: It is approximately ${Me/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=Ee}else u=Ee}const q=Math.round($.pts-$.dts);U=Math.min(U,u),Y=Math.max(Y,u),O=Math.min(O,M),re=Math.max(re,M),o.push(new Ni($.key,u,F,q))}if(o.length){if(pt){if(pt<70){const N=o[0].flags;N.dependsOn=2,N.isNonSync=0}}else if(Jt&&re-O<Y-U&&R/Y<.025&&o[0].cts===0){v.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let N=f;for(let $=0,w=o.length;$<w;$++){const F=N+o[$].duration,M=N+o[$].cts;if($<w-1){const q=F+o[$+1].cts;o[$].duration=q-M}else o[$].duration=$?o[$-1].duration:R;o[$].cts=0,N=F}}}u=b||!u?R:u,this.nextAvcDts=d=g+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const j=A.moof(e.sequenceNumber++,f,te({},e,{samples:o})),J="video",X={data1:j,data2:k,startPTS:p/r,endPTS:(y+u)/r,startDTS:f/r,endDTS:d/r,type:J,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,X}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,l=n/o,c=e.segmentCodec==="aac"?Pi:Ra,d=c*l,h=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let p=e.samples,y=u?0:8,E=this.nextAudioPts||-1;const S=t*n,x=h.baseTime*n/h.timescale;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(S-E)<9e3||Math.abs(fe(p[0].pts-x,S)-E)<20*d),p.forEach(function(J){J.pts=fe(J.pts-x,S)}),!s||E<0){if(p=p.filter(J=>J.pts>=0),!p.length)return;r===0?E=0:i&&!g?E=Math.max(0,S):E=p[0].pts}if(e.segmentCodec==="aac"){const J=this.config.maxAudioFramesDrift;for(let X=0,N=E;X<p.length;X++){const $=p[X],w=$.pts,F=w-N,M=Math.abs(1e3*F/n);if(F<=-J*d&&g)X===0&&(v.warn(`Audio frame @ ${(w/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*F/n)} ms.`),this.nextAudioPts=E=N=w);else if(F>=J*d&&M<Ia&&g){let q=Math.round(F/d);N=w-q*d,N<0&&(q--,N+=d),X===0&&(this.nextAudioPts=E=N),v.warn(`[mp4-remuxer]: Injecting ${q} audio frame @ ${(N/n).toFixed(3)}s due to ${Math.round(1e3*F/n)} ms gap.`);for(let he=0;he<q;he++){const Ee=Math.max(N,0);let me=ki.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);me||(v.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),me=$.unit.subarray()),p.splice(X,0,{unit:me,pts:Ee}),N+=d,X++}}$.pts=N,N+=d}}let R=null,L=null,_,D=0,k=p.length;for(;k--;)D+=p[k].unit.byteLength;for(let J=0,X=p.length;J<X;J++){const N=p[J],$=N.unit;let w=N.pts;if(L!==null){const M=f[J-1];M.duration=Math.round((w-L)/l)}else if(s&&e.segmentCodec==="aac"&&(w=E),R=w,D>0){D+=y;try{_=new Uint8Array(D)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:G.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:D,reason:`fail allocating audio mdat ${D}`});return}u||(new DataView(_.buffer).setUint32(0,D),_.set(A.types.mdat,4))}else return;_.set($,y);const F=$.byteLength;y+=F,f.push(new Ni(!0,c,F,0)),L=w}const P=f.length;if(!P)return;const b=f[f.length-1];this.nextAudioPts=E=L+l*b.duration;const U=u?new Uint8Array(0):A.moof(e.sequenceNumber++,R/l,te({},e,{samples:f}));e.samples=[];const O=R/n,Y=E/n,j={data1:U,data2:_,startPTS:O,endPTS:Y,startDTS:O,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:P};return this.isAudioContiguous=!0,j}remuxEmptyAudio(e,t,s,i){const r=e.inputTimeScale,n=e.samplerate?e.samplerate:r,o=r/n,l=this.nextAudioPts,c=this._initDTS,d=c.baseTime*9e4/c.timescale,h=(l!==null?l:i.startDTS*r)+d,u=i.endDTS*r+d,f=o*Pi,g=Math.ceil((u-h)/f),p=ki.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(v.warn("[mp4-remuxer]: remux empty Audio"),!p){v.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const y=[];for(let E=0;E<g;E++){const S=h+E*f;y.push({unit:p,pts:S,dts:S})}return e.samples=y,this.remuxAudio(e,t,s,!1)}}function fe(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function ba(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function Fi(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const l=a.samples[o];l.pts=fe(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=fe(l.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function Oi(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=fe(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class Ni{constructor(e,t,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=s,this.cts=i,this.flags=new Da(e)}}class Da{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class Ca{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(zr(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=Bs(e);t||(t=Mi(i.audio,z.AUDIO)),s||(s=Mi(i.video,z.VIDEO));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:e,id:"main"}:v.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,n){var o,l;let{initPTS:c,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};B(d)||(d=this.lastEndTime=r||0);const u=t.samples;if(!(u!=null&&u.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(u),g=this.initData),!((l=g)!=null&&l.length))return v.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=Xr(u,g),y=jr(g,u),E=y===null?r:y;(_a(c,E,r,p)||f.timescale!==c.timescale&&n)&&(f.initPTS=E-r,c&&c.timescale===1&&v.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const S=e?E-c.baseTime/c.timescale:d,x=S+p;Jr(g,u,c.baseTime/c.timescale),p>0?this.lastEndTime=x:(v.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const R=!!g.audio,L=!!g.video;let _="";R&&(_+="audio"),L&&(_+="video");const D={data1:u,startPTS:S,startDTS:S,endPTS:x,endDTS:x,type:_,hasAudio:R,hasVideo:L,nb:1,dropped:0};return h.audio=D.type==="audio"?D:void 0,h.video=D.type!=="audio"?D:void 0,h.initSegment=f,h.id3=Fi(s,r,c,c),i.samples.length&&(h.text=Oi(i,r,c)),h}}function _a(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function Mi(a,e){const t=a==null?void 0:a.codec;return t&&t.length>4?t:t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":t==="avc1"||e===z.VIDEO?"avc1.42e01e":"mp4a.40.5"}let Re;try{Re=self.performance.now.bind(self.performance)}catch{v.debug("Unable to use Performance API on this environment"),Re=typeof self<"u"&&self.Date.now}const es=[{demux:ua,remux:Ca},{demux:Ce,remux:Zt},{demux:da,remux:Zt},{demux:va,remux:Zt}];class Bi{constructor(e,t,s,i,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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.vendor=i,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Re();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:S,initSegmentData:x}=l,R=ka(n,t);if(R&&R.method==="AES-128"){const k=this.getDecrypter();if(k.isSync()){let P=k.softwareDecrypt(n,R.key.buffer,R.iv.buffer);if(s.part>-1&&(P=k.flush()),!P)return r.executeEnd=Re(),ts(s);n=new Uint8Array(P)}else return this.decryptionPromise=k.webCryptoDecrypt(n,R.key.buffer,R.iv.buffer).then(P=>{const b=this.push(P,null,s);return this.decryptionPromise=null,b}),this.decryptionPromise}const L=this.needsProbing(d,h);if(L){const k=this.configureTransmuxer(n);if(k)return v.warn(`[transmuxer] ${k.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),r.executeEnd=Re(),ts(s)}(d||h||g||L)&&this.resetInitSegment(x,p,y,S,t),(d||g||L)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const _=this.transmux(n,R,f,u,s),D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,r.executeEnd=Re(),_}flush(e){const t=e.transmuxing;t.executeStart=Re();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const h=s.flush();h&&n.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Re(),[ts(e)];const d=l.flush(o);return yt(d)?d.then(h=>(this.flushRemux(n,h,e),n)):(this.flushRemux(n,d,e),n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;v.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const d=this.remuxer.remux(i,r,n,o,c,l,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=Re()}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){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,l,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i,vendor:r}=this;let n;for(let h=0,u=es.length;h<u;h++)if(es[h].demux.probe(e)){n=es[h];break}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=n.remux,d=n.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(s,t,i,r)),(!o||!(o instanceof d))&&(this.demuxer=new d(s,t,i),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Yt(this.config)),e}}function ka(a,e){let t=null;return a.byteLength>0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ts=a=>({remuxResult:{},chunkMeta:a});function yt(a){return"then"in a&&a.then instanceof Function}class wa{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 Pa{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}var Ui={exports:{}};(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function r(l,c,d,h,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new i(d,h||l,u),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 n(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=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},o.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},o.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,d,h,u,f,g){var p=t?t+c:c;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,S,x;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,h),!0;case 4:return y.fn.call(y.context,d,h,u),!0;case 5:return y.fn.call(y.context,d,h,u,f),!0;case 6:return y.fn.call(y.context,d,h,u,f,g),!0}for(x=1,S=new Array(E-1);x<E;x++)S[x-1]=arguments[x];y.fn.apply(y.context,S)}else{var R=y.length,L;for(x=0;x<R;x++)switch(y[x].once&&this.removeListener(c,y[x].fn,void 0,!0),E){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,d);break;case 3:y[x].fn.call(y[x].context,d,h);break;case 4:y[x].fn.call(y[x].context,d,h,u);break;default:if(!S)for(L=1,S=new Array(E-1);L<E;L++)S[L-1]=arguments[L];y[x].fn.apply(y[x].context,S)}}return!0},o.prototype.on=function(c,d,h){return r(this,c,d,h,!1)},o.prototype.once=function(c,d,h){return r(this,c,d,h,!0)},o.prototype.removeListener=function(c,d,h,u){var f=t?t+c:c;if(!this._events[f])return this;if(!d)return n(this,f),this;var g=this._events[f];if(g.fn)g.fn===d&&(!u||g.once)&&(!h||g.context===h)&&n(this,f);else{for(var p=0,y=[],E=g.length;p<E;p++)(g[p].fn!==d||u&&!g[p].once||h&&g[p].context!==h)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:n(this,f)}return this},o.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&n(this,d)):(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,a.exports=o})(Ui);var Fa=Ui.exports,ss=Tr(Fa);const is=at()||{isTypeSupported:()=>!1};class $i{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,c===m.ERROR&&(this.error=d.error),this.hls.trigger(c,d)};this.observer=new ss,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o={mp4:is.isTypeSupported("video/mp4"),mpeg:is.isTypeSupported("audio/mpeg"),mp3:is.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||ta())){try{r.workerPath?(v.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=ia(r.workerPath)):(v.log(`injecting Web Worker for "${t}"`),this.workerContext=sa()),this.onwmsg=h=>this.onWorkerMessage(h);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=h=>{const u=new Error(`${h.message} (${h.filename}:${h.lineno})`);r.enableWorker=!1,v.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:G.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})},d.postMessage({cmd:"init",typeSupported:o,vendor:l,id:t,config:JSON.stringify(r)})}catch(d){v.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Bi(this.observer,o,r,l,t)}return}this.transmuxer=new Bi(this.observer,o,r,l,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,l,c,d){var h,u;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,y=this.frag,E=!(y&&r.cc===y.cc),S=!(y&&c.level===y.level),x=y?c.sn-y.sn:-1,R=this.part?c.part-this.part.index:-1,L=x===0&&c.id>1&&c.id===(y==null?void 0:y.stats.chunkCount),_=!S&&(x===1||x===0&&(R===1||L&&R<=0)),D=self.performance.now();(S||x||r.stats.parsing.start===0)&&(r.stats.parsing.start=D),n&&(R||!_)&&(n.stats.parsing.start=D);const k=!(y&&((h=r.initSegment)==null?void 0:h.url)===((u=y.initSegment)==null?void 0:u.url)),P=new Pa(E,_,l,S,g,k);if(!_||E||k){v.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
discontinuity: ${E}
trackSwitch: ${S}
contiguous: ${_}
accurateTimeOffset: ${l}
timeOffset: ${g}
initSegmentChange: ${k}`);const b=new wa(s,i,t,o,d);this.configureTransmuxer(b)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:c,state:P},e instanceof ArrayBuffer?[e]:[]);else if(f){const b=f.push(e,p,c,P);yt(b)?(f.async=!0,b.then(U=>{this.handleTransmuxComplete(U)}).catch(U=>{this.transmuxerError(U,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(b))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let s=t.flush(e);yt(s)||t.async?(yt(s)||(s=Promise.resolve(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,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,s=this.hls;switch(t.event){case"init":{var i;const r=(i=this.workerContext)==null?void 0:i.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":v[t.data.logType]&&v[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,s.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Oa=250,rs=2,Na=.1,Ma=.05;class Ba{constructor(e,t,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:s,media:i,stalled:r}=this;if(i===null)return;const{currentTime:n,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,n!==e){if(this.moved=!0,r!==null){if(this.stallReported){const E=self.performance.now()-r;v.warn(`playback not stuck anymore @${n}, after ${Math.round(E)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!Q.getBuffered(i).length)return;const d=Q.bufferInfo(i,n,0),h=d.len>0,u=d.nextStart||0;if(!h&&!u)return;if(o){const E=d.len>rs,S=!u||t&&t.start<=n||u-n>rs&&!this.fragmentTracker.getPartialFragment(n);if(E||S)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const E=Math.max(u,d.start||0)-n,S=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,R=(S==null||(f=S.details)==null?void 0:f.live)?S.details.targetduration*2:rs,L=this.fragmentTracker.getPartialFragment(n);if(E>0&&(E<=R||L)){this._trySkipBufferHole(L);return}}const g=self.performance.now();if(r===null){this.stalled=g;return}const p=g-r;if(!o&&p>=Oa&&(this._reportStall(d),!this.media))return;const y=Q.bufferInfo(i,n,s.maxBufferHole);this._tryFixBufferStall(y,p)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(r===null)return;const n=r.currentTime,o=i.getPartialFragment(n);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-n<s.maxBufferHole)&&t>s.highBufferWatchdogPeriod*1e3&&(v.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);v.warn(r.message),t.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:i}=this;if(i===null)return 0;const r=i.currentTime,n=Q.bufferInfo(i,r,0),o=r<n.start?n.start:n.nextStart;if(o){const l=n.len<=t.maxBufferHole,c=n.len>0&&n.len<1&&i.readyState<3,d=o-r;if(d>0&&(l||c)){if(d>t.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(r===0){const g=u.getAppendedFrag(0,V.MAIN);g&&o<g.end&&(f=!0)}if(!f){const g=e||u.getAppendedFrag(r,V.MAIN);if(g){let p=!1,y=g.end;for(;y<o;){const E=u.getPartialFragment(y);if(E)y+=E.duration;else{p=!0;break}}if(p)return 0}}}const h=Math.max(o+Ma,r+Na);if(v.warn(`skipping hole, adjusting currentTime from ${r} to ${h}`),this.moved=!0,this.stalled=null,i.currentTime=h,e&&!e.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${h}`);s.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:s,nudgeRetry:i}=this;if(s===null)return;const r=s.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const n=r+(i+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${n}`);v.warn(o.message),s.currentTime=n,t.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);v.error(n.message),t.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}const Ua=100;class $a extends qt{constructor(e,t,s){super(e,t,s,"[stream-controller]",V.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.ERROR,this.onError,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.ERROR,this.onError,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:s}=this;if(this.stopLoad(),this.setInterval(Ua),this.level=-1,!this.startFragRequested){let i=s.startLevel;i===-1&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.nextAutoLevel),this.level=s.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=C.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{var e;const{levels:s,level:i}=this,r=s==null||(e=s[i])==null?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var t;const s=self.performance.now(),i=this.retryDate;(!i||s>=i||(t=this.media)!=null&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=C.IDLE)}break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this,{config:r,nextLoadLevel:n}=e;if(t===null||!i&&(this.startFragRequested||!r.startFragPrefetch)||this.altAudio&&this.audioOnly||!(s!=null&&s[n]))return;const o=s[n],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const y={};this.altAudio&&(y.type="video"),this.hls.trigger(m.BUFFER_EOS,y),this.state=C.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const d=o.details;if(!d||this.state===C.WAITING_LEVEL||d.live&&this.levelLastLoaded!==n){this.level=n,this.state=C.WAITING_LEVEL;return}const h=l.len,u=this.getMaxBufferLength(o.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==se.OK){var p;const E=((p=this.backtrackFragment)!=null?p:g).sn-d.startSN,S=d.fragments[E-1];S&&g.cc===S.cc&&(g=S,this.fragmentTracker.removeFragment(S))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const E=this.audioOnly&&!this.altAudio?z.AUDIO:z.VIDEO,S=(E===z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;S&&this.afterBufferFlushed(S,E,V.MAIN)}g=this.getNextFragmentLoopLoading(g,d,l,V.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,o,f))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===se.NOT_LOADED||i===se.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):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)):(this.startFragRequested=!0,super.loadFragment(e,t,s)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,V.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,d=Math.max(n.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*.5),c*.75));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new Ba(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;B(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const s=this.getMainFwdBufferInfo();if(s===null||s.len===0){this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1,r;t.levels.forEach(n=>{r=n.audioCodec,r&&(r.indexOf("mp4a.40.2")!==-1&&(s=!0),r.indexOf("mp4a.40.5")!==-1&&(i=!0))}),this.audioCodecSwitch=s&&i&&!ea(),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!==C.IDLE)return;const i=s[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(i.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i}=this,r=t.level,n=t.details,o=n.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${o}`);const l=i[r],c=this.fragCurrent;c&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&(c.level!==t.level||c.urlId!==l.urlId)&&c.loader&&this.abortCurrentFrag();let d=0;if(n.live||(s=l.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,l.details)}if(l.details=n,this.levelLastLoaded=r,this.hls.trigger(m.LEVEL_UPDATED,{details:n,level:r}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(n))return;this.state=C.IDLE}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:n}=this;if(!n){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=n[s.level],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,d=l.PTSKnown||!l.live,h=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new $i(this.hls,V.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Ht(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,p),E=this.initPTS[s.cc];f.push(r,h,u,c,s,i,l.totalduration,d,y,E)}onAudioTrackSwitching(e,t){const s=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;s&&(r.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=t.id,i=!!this.hls.audioTracks[s].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!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 n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s&&s.type!==V.MAIN)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}`),this.state===C.PARSED&&(this.state=C.IDLE);return}const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),s.sn!=="initSegment"&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===W.LEVEL&&(this.state=C.IDLE);break;case I.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!Q.getBuffered(e).length){const s=this.state!==C.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,s)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==z.AUDIO||this.audioOnly&&!this.altAudio){const s=(t===z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(s,t,V.MAIN)}}onLevelsUpdated(e,t){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=Q.getBuffered(e),n=(i.length?i.start(0):0)-s;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),s+=n,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${t}`),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;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:l,part:c,level:d}=o,{video:h,text:u,id3:f,initSegment:g}=r,{details:p}=d,y=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,g){if(g!=null&&g.tracks){const x=l.initSegment||l;this._bufferInitSegment(d,g.tracks,x,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:s,tracks:g.tracks})}const E=g.initPTS,S=g.timescale;B(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:S},i.trigger(m.INIT_PTS_FOUND,{frag:l,id:s,initPTS:E,timescale:S}))}if(h&&p&&l.sn!=="initSegment"){const E=p.fragments[l.sn-1-p.startSN],S=l.sn===p.startSN,x=!E||l.cc>E.cc;if(r.independent!==!1){const{startPTS:R,endPTS:L,startDTS:_,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:R,endPTS:L,startDTS:_,endDTS:D};else if(h.firstKeyFrame&&h.independent&&n.id===1&&!x&&(this.couldBacktrack=!0),h.dropped&&h.independent){const k=this.getMainFwdBufferInfo(),P=(k?k.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:R;if(!S&&P<b-this.config.maxBufferHole&&!x){this.backtrack(l);return}else x&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,L,l.start,D,!0)}l.setElementaryStreamInfo(h.type,R,L,_,D),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,n,S||x)}else if(S||x)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:E,endPTS:S,startDTS:x,endDTS:R}=y;c&&(c.elementaryStreams[z.AUDIO]={startPTS:E,endPTS:S,startDTS:x,endDTS:R}),l.setElementaryStreamInfo(z.AUDIO,E,S,x,R),this.bufferFragmentData(y,l,c,n)}if(p&&f!=null&&(t=f.samples)!=null&&t.length){const E={id:s,frag:l,details:p,samples:f.samples};i.trigger(m.FRAG_PARSING_METADATA,E)}if(p&&u){const E={id:s,frag:l,details:p,samples:u.samples};i.trigger(m.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:n,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),r.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(m.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:d,frag:s,part:null,chunkMeta:i,parent:s.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,V.MAIN)}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=C.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(Q.isBuffered(e,s)?t=this.getAppendedFrag(s):Q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r||t.urlId!==i.urlId)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,s=this.currentFrag;if(s&&B(t)&&B(s.programDateTime)){const i=s.programDateTime+(t-s.start)*1e3;return new Date(i)}}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 Ge{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 Ga{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 Ge(e),this.fast_=new Ge(t),this.defaultTTFB_=i,this.ttfb_=new Ge(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ge(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ge(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ge(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}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_}destroy(){}}class Va{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new Ga(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var s;const i=t.frag;this.ignoreFragment(i)||(this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{total:i,bwEstimate:r}=t.stats;B(i)&&B(r)&&(this.lastLevelLoadSec=8*i/r),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:s}=this,{autoLevelEnabled:i,media:r}=s;if(!e||!r)return;const n=performance.now(),o=t?t.stats:e.stats,l=t?t.duration:e.duration,c=n-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i||r.paused||!r.playbackRate||!r.readyState)return;const d=s.mainForwardBufferInfo;if(d===null)return;const h=this.bwEstimator.getEstimateTTFB(),u=Math.abs(r.playbackRate);if(c<=Math.max(h,1e3*(l/(u*2))))return;const f=d.len/u;if(f>=2*l/u)return;const g=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&g>-1,y=this.bwEstimator.getEstimate(),{levels:E,minAutoLevel:S}=s,x=E[e.level],R=o.total||Math.max(o.loaded,Math.round(l*x.maxBitrate/8));let L=c-g;L<1&&p&&(L=Math.min(c,o.loaded*8/y));const _=p?o.loaded*1e3/L:0,D=_?(R-o.loaded)/_:R*8/y+h/1e3;if(D<=f)return;const k=_?_*8:y;let P=Number.POSITIVE_INFINITY,b;for(b=e.level-1;b>S;b--){const U=E[b].maxBitrate;if(P=this.getTimeToLoadFrag(h/1e3,k,l*U,!E[b].details),P<f)break}P>=D||P>l*10||(s.nextLoadLevel=b,p?this.bwEstimator.sample(c-Math.min(h,g),o.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),v.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;
Time to underbuffer: ${f.toFixed(3)} s
Estimated load time for current fragment: ${D.toFixed(3)} s
Estimated load time for down switch fragment: ${P.toFixed(3)} s
TTFB estimate: ${g}
Current BW estimate: ${B(y)?(y/1024).toFixed(3):"Unknown"} Kb/s
New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
Aborting and switching to level ${b}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),s.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===V.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,l=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:l},n.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}}}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 n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.bwEstimator.getEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==V.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(e!==-1&&!t.canEstimate())return e;let s=this.getNextABRAutoLevel();if(e!==-1){const i=this.hls.levels;if(i.length>Math.max(e,s)&&i[e].loadError<=i[s].loadError)return e}return e!==-1&&(s=Math.min(e,s)),s}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:n,media:o}=s,l=t?t.duration:e?e.duration:0,c=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():r.abrEwmaDefaultEstimate,h=s.mainForwardBufferInfo,u=(h?h.len:0)/c;let f=this.findBestLevel(d,n,i,u,r.abrBandWidthFactor,r.abrBandWidthUpFactor);if(f>=0)return f;v.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=l?Math.min(l,r.maxStarvationDelay):r.maxStarvationDelay,p=r.abrBandWidthFactor,y=r.abrBandWidthUpFactor;if(!u){const E=this.bitrateTestDelay;E&&(g=(l?Math.min(l,r.maxLoadingDelay):r.maxLoadingDelay)-E,v.trace(`[abr] bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),p=y=1)}return f=this.findBestLevel(d,n,i,u+g,p,y),Math.max(f,0)}findBestLevel(e,t,s,i,r,n){var o;const{fragCurrent:l,partCurrent:c,lastLoadedFragLevel:d}=this,{levels:h}=this.hls,u=h[d],f=!!(u!=null&&(o=u.details)!=null&&o.live),g=u==null?void 0:u.codecSet,p=c?c.duration:l?l.duration:0,y=this.bwEstimator.getEstimateTTFB()/1e3;let E=t,S=-1;for(let x=s;x>=t;x--){const R=h[x];if(!R||g&&R.codecSet!==g){R&&(E=Math.min(x,E),S=Math.max(x,S));continue}S!==-1&&v.trace(`[abr] Skipped level(s) ${E}-${S} with CODECS:"${h[S].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const L=R.details,_=(c?L==null?void 0:L.partTarget:L==null?void 0:L.averagetargetduration)||p;let D;x<=d?D=r*e:D=n*e;const k=h[x].maxBitrate,P=this.getTimeToLoadFrag(y,D,k*_,L===void 0);if(v.trace(`[abr] level:${x} adjustedbw-bitrate:${Math.round(D-k)} avgDuration:${_.toFixed(1)} maxFetchDuration:${i.toFixed(1)} fetchDuration:${P.toFixed(1)}`),D>k&&(P===0||!B(P)||f&&!this.bitrateTestDelay||P<i))return x}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}}class Gi{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=Ka(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Ka(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}const Vi=100;class Ha extends qt{constructor(e,t,s){super(e,t,s,"[audio-stream-controller]",V.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){if(s==="main"){const n=t.cc;this.initPTS[t.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${n} found from main: ${i}`),this.videoTrackCC=n,this.state===C.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Vi),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=C.IDLE):(this.loadedmetadata=!1,this.state=C.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{var e;const{levels:s,trackId:i}=this,r=s==null||(e=s[i])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{var t;const s=performance.now(),i=this.retryDate;(!i||s>=i||(t=this.media)!=null&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=C.IDLE);break}case C.WAITING_INIT_PTS:{const s=this.waitingData;if(s){const{frag:i,part:r,cache:n,complete:o}=s;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=C.FRAG_LOADING;const l=n.flush(),c={frag:i,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=Q.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Gt(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=C.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=C.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:s,trackId:i}=this,r=e.config;if(!(t!=null&&t[i])||!s&&(this.startFragRequested||!r.startFragPrefetch))return;const n=t[i],o=n.details;if(!o||o.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(o)){this.state=C.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,z.AUDIO,V.AUDIO));const c=this.getFwdBufferInfo(l,V.AUDIO);if(c===null)return;const{bufferedTrack:d,switchingTrack:h}=this;if(!h&&this._streamEnded(c,o)){e.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,V.MAIN),f=c.len,g=this.getMaxBufferLength(u==null?void 0:u.len);if(f>=g&&!h)return;const y=o.fragments[0].start;let E=c.end;if(h&&s){const L=this.getLoadPosition();d&&h.attrs!==d.attrs&&(E=L),o.PTSKnown&&L<y&&(c.end>y||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=y+.05)}let S=this.getNextFragment(E,o),x=!1;if(S&&this.isLoopLoading(S,E)&&(x=!!S.gap,S=this.getNextFragmentLoopLoading(S,o,c,V.MAIN,g)),!S){this.bufferFlushed=!0;return}const R=u&&S.start>u.end+o.targetduration;if(R||!(u!=null&&u.len)&&c.len){const L=this.getAppendedFrag(S.start,V.MAIN);if(L===null||(x||(x=!!L.gap||!!R&&u.len===0),R&&!x||x&&c.nextStart&&c.nextStart<L.end))return}this.loadFragment(S,n,E)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new qe(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.setInterval(Vi):this.resetTransmuxer(),s?(this.switchingTrack=t,this.state=C.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=C.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(m.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var s;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:i}=this,{details:r,id:n}=t;if(!i){this.warn(`Audio tracks were reset while loading level ${n}`);return}this.log(`Track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=i[n];let l=0;if(r.live||(s=o.details)!=null&&s.live){this.checkLiveUpdate(r);const c=this.mainDetails;if(r.deltaUpdateFailed||!c)return;!o.details&&r.hasProgramDateTime&&c.hasProgramDateTime?(Ei(r,c),l=r.fragments[0].start):l=this.alignPlaylists(r,o.details)}o.details=r,this.levelLastLoaded=n,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(o.details,l),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{config:n,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 d=c.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const h=n.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new $i(this.hls,V.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 y=i?i.index:-1,E=y!==-1,S=new Ht(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);u.push(r,g,h,"",s,i,d.totalduration,!1,S,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Gi,complete:!1};p.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=C.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==V.AUDIO){if(!this.loadedmetadata&&s.type===V.MAIN){const r=this.videoBuffer||this.media;r&&Q.getBuffered(r).length&&(this.loadedmetadata=!0)}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(s.sn!=="initSegment"){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,oe({},r)))}this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(V.AUDIO,t);break;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===W.AUDIO_TRACK&&(this.state=C.IDLE);break;case I.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushed(e,{type:t}){t===z.AUDIO&&(this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE))}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:l,part:c,level:d}=o,{details:h}=d,{audio:u,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=l.initSegment||l;this._bufferInitSegment(p.tracks,y,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(u){const{startPTS:y,endPTS:E,startDTS:S,endDTS:x}=u;c&&(c.elementaryStreams[z.AUDIO]={startPTS:y,endPTS:E,startDTS:S,endDTS:x}),l.setElementaryStreamInfo(z.AUDIO,y,E,S,x),this.bufferFragmentData(u,l,c,n)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=te({id:s,frag:l,details:h},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){const y=te({id:s,frag:l,details:h},f);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s){if(this.state!==C.PARSING)return;e.video&&delete e.video;const i=e.audio;if(!i)return;i.levelCodec=i.codec,i.id="audio",this.log(`Init audio buffer, container:${i.container}, codecs[parsed]=[${i.codec}]`),this.hls.trigger(m.BUFFER_CODECS,e);const r=i.initSegment;if(r!=null&&r.byteLength){const n={type:"audio",frag:t,part:null,chunkMeta:s,parent:t.type,data:r};this.hls.trigger(m.BUFFER_APPENDING,n)}this.tick()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===se.NOT_LOADED||i===se.PARTIAL){var r;e.sn==="initSegment"?this._loadInitSegment(e,t):(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=C.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,t,s))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:s,bufferedTrack:i}=this,r=i==null?void 0:i.attrs,n=e.attrs;s&&r&&(r.CHANNELS!==n.CHANNELS||r.NAME!==n.NAME||r.LANGUAGE!==n.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,oe({},e))}}class Wa extends Vt{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Track with id:${s} and group:${i} not found in active group ${n.groupId}`);return}const o=n.details;n.details=t.details,this.log(`audio-track ${s} "${n.name}" lang:${n.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!=null&&t.audioGroupIds))return;const s=t.audioGroupIds[t.urlId];if(this.groupId!==s){this.groupId=s||null;const i=this.tracks.filter(n=>!s||n.groupId===s);this.selectDefaultTrack&&!i.some(n=>n.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=i;const r={audioTracks:i};this.log(`Updating audio tracks, ${i.length} track(s) found in group:${s}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,r),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===W.AUDIO_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const s=this.currentTrack;t[this.trackId];const i=t[e],{groupId:r,name:n}=i;if(this.log(`Switching to audio-track ${e} "${n}" lang:${i.lang} group:${r}`),this.trackId=e,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,oe({},i)),i.details&&!i.details.live)return;const o=this.switchParams(i.url,s==null?void 0:s.details);this.loadPlaylist(o)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(t!==-1)this.setAudioTrack(t);else{const s=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(s.message),this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:s})}}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||e.attrs["STABLE-RENDITION-ID"]!==void 0&&e.attrs["STABLE-RENDITION-ID"]===i.attrs["STABLE-RENDITION-ID"]||e.name===i.name&&e.lang===i.lang))return i.id}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}this.log(`loading audio-track playlist ${s} "${t.name}" lang:${t.lang} group:${i}`),this.clearTimer(),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}}function Ki(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!Ya(a[t].attrs,e[t].attrs))return!1;return!0}function Ya(a,e){const t=a["STABLE-RENDITION-ID"];return t?t===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(s=>a[s]!==e[s])}const Hi=500;class qa extends qt{constructor(e,t,s){super(e,t,s,"[subtitle-stream-controller]",V.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.ERROR,this.onError,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.ERROR,this.onError,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=C.IDLE,this.setInterval(Hi),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragPrevious=s,this.state=C.IDLE,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){n=r[c];break}const l=s.start+s.duration;n?n.end=l:(n={start:o,end:l},r.push(n)),this.fragmentTracker.fragBuffered(s)}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(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,V.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===V.MAIN){var s;(s=this.media)!=null&&s.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===V.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(Ki(this.levels,t)){this.levels=t.map(s=>new qe(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new qe(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,V.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(Hi)}onSubtitleTrackLoaded(e,t){var s;const{details:i,id:r}=t,{currentTrackId:n,levels:o}=this;if(!o.length)return;const l=o[n];if(r>=o.length||r!==n||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(i.live||(s=l.details)!=null&&s.live){const d=this.mainDetails;if(i.deltaUpdateFailed||!d)return;const h=d.fragments[0];l.details?(c=this.alignPlaylists(i,l.details),c===0&&h&&(c=h.start,Ut(i,c))):i.hasProgramDateTime&&d.hasProgramDateTime?(Ei(i,d),c=i.fragments[0].start):h&&(c=h.start,Ut(i,c))}l.details=i,this.levelLastLoaded=r,!this.startFragRequested&&(this.mainDetails||!i.live)&&this.setStartPosition(l.details,c),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(ze(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i&&i.key&&i.iv&&i.method==="AES-128"){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch(o=>{throw r.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){const{currentTrackId:e,levels:t}=this,s=t[e];if(!t.length||!s||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),n=Q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:l}=n,c=this.getFwdBufferInfo(this.media,V.MAIN),d=s.details,h=this.getMaxBufferLength(c==null?void 0:c.len)+d.levelTargetDuration;if(l>h)return;const u=d.fragments,f=u.length,g=d.edge;let p=null;const y=this.fragPrevious;if(o<g){const E=i.maxFragLookUpTolerance,S=o>g-E?0:E;p=ze(y,u,Math.max(u[0].start,o),S),!p&&y&&y.start<u[0].start&&(p=u[0])}else p=u[f-1];if(!p)return;if(p=this.mapToInitFragWhenRequired(p),p.sn!=="initSegment"){const E=p.sn-d.startSN,S=u[E-1];S&&S.cc===p.cc&&this.fragmentTracker.getState(S)===se.NOT_LOADED&&(p=S)}this.fragmentTracker.getState(p)===se.NOT_LOADED&&this.loadFragment(p,s,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,s){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,s))}get mediaBufferTimeRanges(){return new za(this.tracksBuffered[this.currentTrackId]||[])}}class za{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)}}}}class ja extends Vt{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),ns(this.media.textTracks).forEach(t=>{Be(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,details:i}=t,{trackId:r}=this,n=this.tracksInGroup[r];if(!n){this.warn(`Invalid subtitle track id ${s}`);return}const o=n.details;n.details=t.details,this.log(`subtitle track ${s} loaded [${i.startSN}-${i.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!=null&&t.textGroupIds))return;const s=t.textGroupIds[t.urlId],i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==s){const r=this.tracks.filter(l=>!s||l.groupId===s);this.tracksInGroup=r;const n=this.findTrackId(i==null?void 0:i.name)||this.findTrackId();this.groupId=s||null;const o={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${s}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,o),n!==-1&&this.setSubtitleTrack(n,i)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId,i)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||e===i.name))return i.id}return-1}onError(e,t){t.fatal||!t.context||t.context.type===W.SUBTITLE_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:s}=this;if(!t)return;const i=ns(t.textTracks),r=i.filter(o=>o.groupId===this.groupId);if(e===-1)[].slice.call(i).forEach(o=>{o.mode="disabled"});else{const o=r[s];o&&(o.mode="disabled")}const n=r[e];n&&(n.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var s;const i=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(s=i[e])!=null&&s.details)||e<-1||e>=i.length)return;this.clearTimer();const r=i[e];if(this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:"")),this.trackId=e,r){const{id:n,groupId:o="",name:l,type:c,url:d}=r;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:c,url:d});const h=this.switchParams(r.url,t==null?void 0:t.details);this.loadPlaylist(h)}else this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=ns(this.media.textTracks);for(let s=0;s<t.length;s++)if(t[s].mode==="hidden")e=s;else if(t[s].mode==="showing"){e=s;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}}function ns(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Xa{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const s=this.queues[t];s.push(e),s.length===1&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const s=new Promise(r=>{t=r}),i={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),s}executeNext(e){const{buffers:t,queues:s}=this,i=t[e],r=s[e];if(r.length){const n=r[0];try{n.execute()}catch(o){v.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),n.onError(o),i!=null&&i.updating||(r.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Wi=at(),Yi=/([ha]vc.)(?:\.[^.,]+)+/;class Qa{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:s}=this;v.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:t})),s&&s.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{v.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{v.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:s}=this;t&&t.src!==s&&v.error(`Media element src was set while attaching MediaSource (${s} > ${t.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Xa(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,v.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const s=this.media=t.media;if(s&&Wi){const i=this.mediaSource=new Wi;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),s.src=self.URL.createObjectURL(i),this._objectUrl=s.src,s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:s}=this;if(t){if(v.log("[buffer-controller]: media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(i){v.warn(`[buffer-controller]: onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),e.src===s?(e.removeAttribute("src"),e.load()):v.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(m.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(s){v.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,s)}}),this._initSourceBuffer()}onBufferCodecs(e,t){const s=this.getSourceBufferTypes().length;Object.keys(t).forEach(i=>{if(s){const r=this.tracks[i];if(r&&typeof r.buffer.changeType=="function"){const{id:n,codec:o,levelCodec:l,container:c,metadata:d}=t[i],h=(r.levelCodec||r.codec).replace(Yi,"$1"),u=(l||o).replace(Yi,"$1");if(h!==u){const f=`${c};codecs=${l||o}`;this.appendChangeType(i,f),v.log(`[buffer-controller]: switching codec ${h} to ${u}`),this.tracks[i]={buffer:r.buffer,codec:o,container:c,levelCodec:l,metadata:d,id:n}}}}else this.pendingTracks[i]=t[i]}),!s&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:s}=this,i={execute:()=>{const r=this.sourceBuffer[e];r&&(v.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),s.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{v.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,r)}};s.append(i,e)}onBufferAppending(e,t){const{hls:s,operationQueue:i,tracks:r}=this,{data:n,type:o,frag:l,part:c,chunkMeta:d}=t,h=d.buffering[o],u=self.performance.now();h.start=u;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=u),g&&g.start===0&&(g.start=u);const p=r.audio;let y=!1;o==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const E=l.start,S={execute:()=>{if(h.executeStart=self.performance.now(),y){const x=this.sourceBuffer[o];if(x){const R=E-x.timestampOffset;Math.abs(R)>=.1&&(v.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${E} (delta: ${R}) sn: ${l.sn})`),x.timestampOffset=E)}}this.appendExecutor(n,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();h.executeEnd=h.end=x,f.first===0&&(f.first=x),g&&g.first===0&&(g.first=x);const{sourceBuffer:R}=this,L={};for(const _ in R)L[_]=Q.getBuffered(R[_]);this.appendError=0,this.hls.trigger(m.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:d,parent:l.type,timeRanges:L})},onError:x=>{v.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,x);const R={type:G.MEDIA_ERROR,parent:l.type,details:I.BUFFER_APPEND_ERROR,frag:l,part:c,chunkMeta:d,error:x,err:x,fatal:!1};x.code===DOMException.QUOTA_EXCEEDED_ERR?R.details=I.BUFFER_FULL_ERROR:(this.appendError++,R.details=I.BUFFER_APPEND_ERROR,this.appendError>s.config.appendErrorMaxRetry&&(v.error(`[buffer-controller]: Failed ${s.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),R.fatal=!0)),s.trigger(m.ERROR,R)}};i.append(S,o)}onBufferFlushing(e,t){const{operationQueue:s}=this,i=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:r})},onError:n=>{v.warn(`[buffer-controller]: Failed to remove from ${r} SourceBuffer`,n)}});t.type?s.append(i(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{s.append(i(r),r)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[z.AUDIOVIDEO]?r.push("audiovideo"):(n[z.AUDIO]&&r.push("audio"),n[z.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();s.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:c,id:s.type})};r.length===0&&v.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((i,r)=>{const n=this.sourceBuffer[r];return n&&(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,v.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),i&&!!(!n||n.ended)},!0)&&(v.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const n=this.sourceBuffer[r];n&&(n.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&v.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}v.log("[buffer-controller]: Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:s,sourceBuffer:i}=this;if(!s||t===null)return;const r=this.getSourceBufferTypes();if(!r.length)return;const n=t.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!B(n)||n<0)return;const o=s.currentTime,l=t.levelTargetDuration,c=Math.max(n,l),d=Math.floor(o/l)*l-c;r.forEach(h=>{const u=i[h];if(u){const f=Q.getBuffered(u);if(f.length>0&&d>f.start(0)){if(e.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:d}),t.live)e.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(u.ended&&f.end(f.length-1)-o<l*2){v.info(`[buffer-controller]: Cannot flush ${h} back buffer while SourceBuffer is in ended state`);return}e.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:h})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:s,mediaSource:i}=this,r=e.fragments[0].start+e.totalduration,n=s.duration,o=B(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(v.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>n||!B(n))&&(v.log(`[buffer-controller]: Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(e){const t=this.mediaSource,s=e.fragments;if(s.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,s[0].start),n=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&!e||i===2){this.createSourceBuffers(s),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(m.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(n=>{t.executeNext(n)});else{const n=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:n,reason:n.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const i in e)if(!t[i]){const r=e[i];if(!r)throw Error(`source buffer exists for track ${i}, however track does not`);const n=r.levelCodec||r.codec,o=`${r.container};codecs=${n}`;v.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const l=t[i]=s.addSourceBuffer(o),c=i;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[i]={buffer:l,codec:n,container:r.container,levelCodec:r.levelCodec,metadata:r.metadata,id:r.id}}catch(l){v.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:o})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const s=new Error(`${e} SourceBuffer error`);v.error(`[buffer-controller]: ${s}`,t),this.hls.trigger(m.ERROR,{type:G.MEDIA_ERROR,details:I.BUFFER_APPENDING_ERROR,error:s,fatal:!1});const i=this.operationQueue.current(e);i&&i.onError(t)}removeExecutor(e,t,s){const{media:i,mediaSource:r,operationQueue:n,sourceBuffer:o}=this,l=o[e];if(!i||!r||!l){v.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(e);return}const c=B(i.duration)?i.duration:1/0,d=B(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,d);u>h&&!l.ending?(l.ended=!1,v.log(`[buffer-controller]: Removing [${h},${u}] from the ${e} SourceBuffer`),l.remove(h,u)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:s,sourceBuffer:i}=this,r=i[t];if(!r){v.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),s.shiftAndExecuteNext(t);return}r.ended=!1,r.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){v.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:s}=this,i=t.map(r=>s.appendBlocker(r));Promise.all(i).then(()=>{e(),t.forEach(r=>{const n=this.sourceBuffer[r];n!=null&&n.updating||s.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,s){const i=this.sourceBuffer[e];if(!i)return;const r=s.bind(this,e);this.listeners[e].push({event:t,listener:r}),i.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(s=>{t.removeEventListener(s.event,s.listener)})}}const qi={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},zi=function(e){let t=e;return qi.hasOwnProperty(e)&&(t=qi[e]),String.fromCharCode(t)},Te=15,be=100,Ja={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Za={17:2,18:4,21:6,22:8,23:10,19:13,20:15},eo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},to={25:2,26:4,29:6,30:8,31:10,27:13,28:15},so=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class io{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;v.log(`${this.time} [${e}] ${s}`)}}}const Oe=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class ji{constructor(e,t,s,i,r){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=s||!1,this.background=i||"black",this.flash=r||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class ro{constructor(e,t,s,i,r,n){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new ji(t,s,i,r,n)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class no{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<be;t++)this.chars.push(new ro);this.logger=e,this.pos=0,this.currPenState=new ji}equals(e){let t=!0;for(let s=0;s<be;s++)if(!this.chars[s].equals(e.chars[s])){t=!1;break}return t}copy(e){for(let t=0;t<be;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<be;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>be&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=be)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;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=zi(e);if(this.pos>=be){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<be;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<be;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 as{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<Te;t++)this.rows.push(new no(e));this.logger=e,this.currRow=Te-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<Te;e++)this.rows[e].clear();this.currRow=Te-1}equals(e){let t=!0;for(let s=0;s<Te;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Te;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Te;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 = "+JSON.stringify(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<Te;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,l=this.logger.time;if(o&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(n.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].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 = "+JSON.stringify(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<Te;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
`)),s}getTextAndFormat(){return this.rows}}class Xi{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 as(s),this.nonDisplayedMemory=new as(s),this.lastOutputScreen=new as(s),this.currRollUpRow=this.displayedMemory.rows[Te-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[Te-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: "+JSON.stringify(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 Qi{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const i=new io;this.channels=[null,new Xi(e,t,i),new Xi(e+1,s,i)],this.cmdHistory=Zi(),this.logger=i}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let s,i,r,n=!1;this.logger.time=e;for(let o=0;o<t.length;o+=2)if(i=t[o]&127,r=t[o+1]&127,!(i===0&&r===0)){if(this.logger.log(3,"["+Oe([t[o],t[o+1]])+"] -> ("+Oe([i,r])+")"),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r)),!s&&(n=this.parseChars(i,r),n)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!s&&!n&&this.logger.log(2,"Couldn't parse cleaned data "+Oe([i,r])+" orig: "+Oe([t[o],t[o+1]]))}}parseCmd(e,t){const{cmdHistory:s}=this,i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return!1;if(Ji(e,t,s))return Ve(null,null,s),this.logger.log(3,"Repeated command ("+Oe([e,t])+") is dropped"),!0;const n=e===20||e===21||e===23?1:2,o=this.channels[n];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),Ve(e,t,s),this.currentChannel=n,!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 ("+Oe([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=this.cmdHistory,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;if(Ji(e,t,i))return Ve(null,null,i),!0;const o=e<=23?1:2;t>=64&&t<=95?s=o===1?Ja[e]:eo[e]:s=o===1?Za[e]:to[e];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(s,t)),Ve(e,t,i),this.currentChannel=o,!0):!1}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 n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,"Special char '"+zi(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);if(i){const n=Oe(i);this.logger.log(3,"Char codes = "+n.join(",")),Ve(e,t,this.cmdHistory)}return 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 n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=so[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),Ve(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory=Zi()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Ve(a,e,t){t.a=a,t.b=e}function Ji(a,e,t){return t.a===a&&t.b===e}function Zi(){return{a:null,b:null}}class Tt{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}}var os=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const a=["","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(a,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const d=arguments[c];for(const h in d)o[h]=d[h]}return o}function n(o,l,c){const d=this,h={enumerable:!0};d.hasBeenReset=!1;let u="",f=!1,g=o,p=l,y=c,E=null,S="",x=!0,R="auto",L="start",_=50,D="middle",k=50,P="middle";Object.defineProperty(d,"id",r({},h,{get:function(){return u},set:function(b){u=""+b}})),Object.defineProperty(d,"pauseOnExit",r({},h,{get:function(){return f},set:function(b){f=!!b}})),Object.defineProperty(d,"startTime",r({},h,{get:function(){return g},set:function(b){if(typeof b!="number")throw new TypeError("Start time must be set to a number.");g=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",r({},h,{get:function(){return p},set:function(b){if(typeof b!="number")throw new TypeError("End time must be set to a number.");p=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",r({},h,{get:function(){return y},set:function(b){y=""+b,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",r({},h,{get:function(){return E},set:function(b){E=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",r({},h,{get:function(){return S},set:function(b){const U=s(b);if(U===!1)throw new SyntaxError("An invalid or illegal string was specified.");S=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",r({},h,{get:function(){return x},set:function(b){x=!!b,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",r({},h,{get:function(){return R},set:function(b){if(typeof b!="number"&&b!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");R=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",r({},h,{get:function(){return L},set:function(b){const U=i(b);if(!U)throw new SyntaxError("An invalid or illegal string was specified.");L=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",r({},h,{get:function(){return _},set:function(b){if(b<0||b>100)throw new Error("Position must be between 0 and 100.");_=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",r({},h,{get:function(){return D},set:function(b){const U=i(b);if(!U)throw new SyntaxError("An invalid or illegal string was specified.");D=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",r({},h,{get:function(){return k},set:function(b){if(b<0||b>100)throw new Error("Size must be between 0 and 100.");k=b,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",r({},h,{get:function(){return P},set:function(b){const U=i(b);if(!U)throw new SyntaxError("An invalid or illegal string was specified.");P=U,this.hasBeenReset=!0}})),d.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class ao{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function er(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.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 oo{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 tr(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],l=n[1];e(o,l)}}const ls=new os(0,0,""),Et=ls.align==="middle"?"middle":"center";function lo(a,e,t){const s=a;function i(){const o=er(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new oo;tr(o,function(u,f){let g;switch(u){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){c.set(u,t[p].region);break}break;case"vertical":c.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(u,g[0]),c.percent(u,g[0])&&c.set("snapToLines",!1),c.alt(u,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",Et,"end"]);break;case"position":g=f.split(","),c.percent(u,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",Et,"end","line-left","line-right","auto"]);break;case"size":c.percent(u,f);break;case"align":c.alt(u,f,["start",Et,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let d=c.get("line","auto");d==="auto"&&ls.line===-1&&(d=-1),l.line=d,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Et);let h=c.get("position","auto");h==="auto"&&ls.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function sr(a){return a.replace(/<br(?: \/)?>/gi,`
`)}class co{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ao,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,n=0;for(r=sr(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
`;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
`&&++n,t.buffer=r.slice(n),o}function i(r){tr(r,function(n,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 n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!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 os(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{lo(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&&(n=!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+=`
`),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+=`
`,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}}const ho=/\r\n|\n\r|\n|\r/g,cs=function(e,t,s=0){return e.slice(s,s+t.length)===t},uo=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+=60*60*1e3*r,t},ds=function(e){let t=5381,s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return(t>>>0).toString()};function hs(a,e,t){return ds(a.toString())+ds(e.toString())+ds(t)}const fo=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function go(a,e,t,s,i,r,n){const o=new co,l=xe(new Uint8Array(a)).trim().replace(ho,`
`).split(`
`),c=[],d=e?Aa(e.baseTime,e.timescale):0;let h="00:00.000",u=0,f=0,g,p=!0;o.oncue=function(y){const E=t[s];let S=t.ccOffset;const x=(u-d)/9e4;if(E!=null&&E.new&&(f!==void 0?S=t.ccOffset=E.start:fo(t,s,x)),x){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}S=x-t.presentationOffset}const R=y.endTime-y.startTime,L=fe((y.startTime+S-f)*9e4,i*9e4)/9e4;y.startTime=Math.max(L,0),y.endTime=Math.max(L+R,0);const _=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(_)),y.id||(y.id=hs(y.startTime,y.endTime,_)),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){n(g);return}r(c)},l.forEach(y=>{if(p)if(cs(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{cs(E,"LOCAL:")?h=E.slice(6):cs(E,"MPEGTS:")&&(u=parseInt(E.slice(7)))});try{f=uo(h)/1e3}catch(E){g=E}return}else y===""&&(p=!1);o.parse(y+`
`)}),o.flush()}const us="stpp.ttml.im1t",ir=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,rr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,mo={left:"start",center:"center",right:"end",start:"start",end:"end"};function nr(a,e,t,s){const i=H(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>xe(o)),n=La(e.baseTime,1,e.timescale);try{r.forEach(o=>t(po(o,n)))}catch(o){s(o)}}function po(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((h,u)=>(h[u]=i.getAttribute(`ttp:${u}`)||r[u],h),{}),o=i.getAttribute("xml:space")!=="preserve",l=ar(fs(i,"styling","style")),c=ar(fs(i,"layout","region")),d=fs(i,"body","[begin]");return[].map.call(d,h=>{const u=or(h,o);if(!u||!h.hasAttribute("begin"))return null;const f=ms(h.getAttribute("begin"),n),g=ms(h.getAttribute("dur"),n);let p=ms(h.getAttribute("end"),n);if(f===null)throw lr(h);if(p===null){if(g===null)throw lr(h);p=f+g}const y=new os(f-e,p-e,u);y.id=hs(y.startTime,y.endTime,y.text);const E=c[h.getAttribute("region")],S=l[h.getAttribute("style")],x=yo(E,S,l),{textAlign:R}=x;if(R){const L=mo[R];L&&(y.lineAlign=L),y.align=R}return te(y,x),y}).filter(h=>h!==null)}function fs(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function ar(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function or(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
`:(r=s.childNodes)!=null&&r.length?or(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function yo(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,l)=>{const c=gs(e,s,l)||gs(a,s,l)||gs(i,s,l);return c&&(o[l]=c),o},{})}function gs(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function lr(a){return new Error(`Could not parse ttml timestamp ${a}`)}function ms(a,e){if(!a)return null;let t=er(a);return t===null&&(ir.test(a)?t=To(a,e):rr.test(a)&&(t=Eo(a,e))),t}function To(a,e){const t=ir.exec(a),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 Eo(a,e){const t=rr.exec(a),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}class xo{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cr(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const t=new Tt(this,"textTrack1"),s=new Tt(this,"textTrack2"),i=new Tt(this,"textTrack3"),r=new Tt(this,"textTrack4");this.cea608Parser1=new Qi(1,t,s),this.cea608Parser2=new Qi(3,i,r)}e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const l=r[o],c=vo(l[0],l[1],t,s);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),n=!0,c/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;s==="main"&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach(o=>{this.onFragLoaded(m.FRAG_LOADED,o)}))}getExistingTrack(e){const{media:t}=this;if(t)for(let s=0;s<t.textTracks.length;s++){const i=t.textTracks[s];if(i[e])return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(e);if(o)s[e]=o,Be(s[e]),ii(s[e],i);else{const l=this.createTextTrack("captions",r,n);l&&(l[e]=!0,s[e]=l)}}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(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Be(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cr(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)Be(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===us);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ki(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media?this.media.textTracks:null;this.tracks.forEach((o,l)=>{let c;if(n&&l<n.length){let d=null;for(let h=0;h<n.length;h++)if(So(n[h],o)){d=n[h];break}d&&(c=d)}if(c)Be(c);else{const d=this._captionsOrSubtitlesFromCharacteristics(o);c=this.createTextTrack(d,o.name,o.lang),c&&(c.mode="disabled")}c&&(c.groupId=o.groupId,this.textTracks.push(c))})}else if(this.tracks.length){const n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),s=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&s)return"captions"}return"subtitles"}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]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:s,cea608Parser2:i,lastSn:r,lastPartIndex:n}=this;if(!(!this.enabled||!(s&&i))&&t.frag.type===V.MAIN){var o,l;const c=t.frag.sn,d=(o=t==null||(l=t.part)==null?void 0:l.index)!=null?o:-1;c===r+1||c===r&&d===n+1||(s.reset(),i.reset()),this.lastSn=c,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===V.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===us?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;nr(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{v.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const l=this.hls,c=(t=s.initSegment)!=null&&t.data?Fe(s.initSegment.data,new Uint8Array(i)):i;go(c,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,d=>{this._appendCues(d,s.level),l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},d=>{const h=d.message==="Missing initPTS for VTT MPEGTS";h?n.push(e):this._fallbackToIMSC1(s,i),v.log(`Failed to parse VTT cue: ${d}`),!(h&&o>s.cc)&&l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:d})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||nr(t,this.initPTS[e.cc],()=>{s.textCodec=us,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>ri(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===V.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!(s&&i))return;const{frag:r,samples:n}=t;if(!(r.type===V.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;o<n.length;o++){const l=n[o].bytes;if(l){const c=this.extractCea608Data(l);s.addData(n[o].pts,c[0]),i.addData(n[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Ft(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Ft(o[l],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&n)!==0){const d=3&n;(d===0||d===1)&&(t[d].push(o),t[d].push(l))}}return t}}function So(a,e){return!!a&&a.label===e.name&&!(a.textTrack1||a.textTrack2)}function vo(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function cr(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class ps{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){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){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,ps.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const 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.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}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=(n,o)=>o?n.width!==o.width||n.height!==o.height:!0;let r=e.length-1;for(let n=0;n<e.length;n+=1){const o=e[n];if((o.width>=t||o.height>=s)&&i(o,e[n+1])){r=n;break}}return r}}class Lo{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(m.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,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)}}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*n/r,c=this.hls;if(c.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),l>0&&n>c.config.fpsDroppedMonitoringThreshold*o){let d=c.currentLevel;v.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=d)&&(d=d-1,c.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:c.currentLevel}),c.autoLevelCapping=d,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)}}const xt="[eme]";class Ke{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Ke.CDMCleanupPromise?[Ke.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=v.debug.bind(v,xt),this.log=v.log.bind(v,xt),this.warn=v.warn.bind(v,xt),this.error=v.error.bind(v,xt),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===ee.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,l)=>!!n&&l.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const l=c=>{const d=c.shift();this.getMediaKeysPromise(d,i,r).then(h=>n({keySystem:d,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof ge?o(h):o(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.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 ks===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){const i=Or(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let n=r==null?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),n.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(d,e,h):d))),o.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),o.mediaKeys})}return n.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Se.hexDump(e.keyId||[])}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Se.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Se.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])}
} (data length: ${t&&t.byteLength})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,s)=>{const i=bt(this.config),r=e.map(Ds).filter(n=>!!n&&i.indexOf(n)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:n})=>{const o=_s(n);o?t(o):s(new Error(`Unable to find format for key-system "${n}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(n,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:n,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),r.catch(n=>this.handleError(n))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ge?this.hls.trigger(m.ERROR,e.data):this.hls.trigger(m.ERROR,{type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ds(e.keyFormat),r=i?[i]:bt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=bt(this.config)),e.length===0)throw new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:s}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),s===null)return;let i,r;if(t==="sinf"&&this.config.drmSystems[ee.FAIRPLAY]){const d=ie(new Uint8Array(s));try{const h=Rt(JSON.parse(d).sinf),u=Us(new Uint8Array(h));if(!u)return;i=u.subarray(8,24),r=ee.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const d=an(s);if(d===null)return;d.version===0&&d.systemId===Cs.WIDEVINE&&d.data&&(i=d.data.subarray(8,24)),r=Fr(d.systemId)}if(!r||!i)return;const n=Se.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[n];for(let d=0;d<l.length;d++){const h=l[d],u=h.decryptdata;if(u.pssh||!u.keyId)continue;const f=Se.hexDump(u.keyId);if(n===f||u.uri.replace(/-/g,"").indexOf(n)!==-1){c=o[f],delete o[f],u.pssh=new Uint8Array(s),u.keyId=i,c=o[n]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,s,"encrypted-event-key-match"));break}}c||(c=o[n]=this.getKeySystemSelectionPromise([r]).then(({keySystem:d,mediaKeys:h})=>{var u;this.throwIfDestroyed();const f=new We("ISO-23001-7",n,(u=_s(d))!=null?u:"");return f.pssh=new Uint8Array(s),f.keyId=i,this.attemptSetMediaKeys(d,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:d,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,s,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return 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)})}generateRequestWithPreferredKeySession(e,t,s,i){var r,n;const o=(r=this.config.drmSystems)==null||(n=r[e.keySystem])==null?void 0:n.generateRequest;if(o)try{const u=o.call(this.hls,t,s,e);if(!u)throw new Error("Invalid response from configured generateRequest filter");t=u.initDataType,s=e.decryptdata.pssh=u.initData?new Uint8Array(u.initData):null}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${t} length: ${s?s.byteLength:null})`);const d=new ss;e.mediaKeysSession.onmessage=u=>{const f=e.mediaKeysSession;if(!f){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:p}=u;this.log(`"${g}" message event for session "${f.sessionId}" message size: ${p.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,p).catch(y=>{this.handleError(y),d.emit("error",y)}):g==="license-release"?e.keySystem===ee.FAIRPLAY&&(this.updateKeySession(e,bs("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${g}"`)},e.mediaKeysSession.onkeystatuseschange=u=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const g=e.keyStatus;d.emit("keyStatus",g),g==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};const h=new Promise((u,f)=>{d.on("error",f),d.on("keyStatus",g=>{g.startsWith("usable")?u():g==="output-restricted"?f(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?f(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var u;this.log(`Request generated for key-session "${(u=e.mediaKeysSession)==null?void 0:u.sessionId}" keyId: ${c}`)}).catch(u=>{throw new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:u,fatal:!1},`Error generating key-session request: ${u}`)}).then(()=>h).catch(u=>{throw d.removeAllListeners(),this.removeSession(e),u}).then(()=>(d.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Se.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Se.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((n,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,p)=>{n(u.data)},onError:(u,f,g,p)=>{o(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:oe({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};i.load(l,d,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s==null?void 0:s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,n,e)}catch(d){this.error(d)}i(l)}else{const l=s.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new ge({type:G.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const d=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},We.clearKeyUriToKeyIdMap();const s=t.length;Ke.CDMCleanupPromise=Promise.all(t.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){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)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Ke.CDMCleanupPromise=void 0;class ge 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}}const Ao=1;var de={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const Io="h";class ke{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:de.MANIFEST,su:!this.initialized})}catch(r){v.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,n=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===de.VIDEO||o===de.AUDIO||o==de.MUXED)&&(l.br=n.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){v.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||ke.uuid(),this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:Ao,sf:Io,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){te(t,this.createData());const s=t.ot===de.INIT||t.ot===de.VIDEO||t.ot===de.MUXED;if(this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){const i=ke.toHeaders(t);if(!Object.keys(i).length)return;e.headers||(e.headers={}),te(e.headers,i)}else{const i=ke.toQuery(t);if(!i)return;e.url=ke.appendQueryToUri(e.url,i)}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return de.TIMED_TEXT;if(e.sn==="initSegment")return de.INIT;if(t==="audio")return de.AUDIO;if(t==="main")return this.hls.audioTracks.length?de.VIDEO:de.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===de.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,s=e===de.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}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,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,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,n,o){t(r),this.loader.load(r,n,o)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],s=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,i=c=>Math.round(c),r=c=>i(c/100)*100,o={br:i,d:i,bl:r,dl:r,mtp:r,nor:c=>encodeURIComponent(c),rtp:r,tb:i},l=Object.keys(e||{}).sort();for(const c of l){let d=e[c];if(!s(d)||c==="v"&&d===1||c=="pr"&&d===1)continue;const h=o[c];h&&(d=h(d));const u=typeof d;let f;c==="ot"||c==="sf"||c==="st"?f=`${c}=${d}`:u==="boolean"?f=c:u==="number"?f=`${c}=${d}`:f=`${c}=${JSON.stringify(d)}`,t.push(f)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),s={},i=["Object","Request","Session","Status"],r=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const o of t){const l=n[o]!=null?n[o]:1;r[l][o]=e[o]}for(let o=0;o<r.length;o++){const l=ke.serialize(r[o]);l&&(s[`CMCD-${i[o]}`]=l)}return s}static toQuery(e){return`CMCD=${encodeURIComponent(ke.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const s=e.includes("?")?"&":"?";return`${e}${s}${t}`}}const Ro=3e5;class bo{constructor(e){this.hls=void 0,this.log=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.log=v.log.bind(v,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}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==null?void 0:s.action)===ne.SendAlternateToPenaltyBox&&s.flags===ue.MoveAllAlternatesMatchingHost){let i=this.pathwayPriority;const r=this.pathwayId;this.penalizedPathways[r]||(this.penalizedPathways[r]=performance.now()),!i&&this.levels&&(i=this.levels.reduce((n,o)=>(n.indexOf(o.pathwayId)===-1&&n.push(o.pathwayId),n),[])),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r)}}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):e}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]>Ro&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(s[n])continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,this.hls.trigger(m.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}}}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(d=>d.pathwayId===n))return;const c=this.getLevelsForPathway(o).map(d=>{const h=te({},d);h.details=void 0,h.url=hr(d.uri,d.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const u=new Z(d.attrs);u["PATHWAY-ID"]=n;const f=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;f&&(s[u.AUDIO]=f,u.AUDIO=f),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g),h.attrs=u;const p=new qe(h);return dt(p,"audio",f),dt(p,"text",g),p});t.push(...c),dr(this.audioTracks,s,l,n),dr(this.subtitleTracks,i,l,n)})}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 d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(d,h,u,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=d.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":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),y&&this.clonePathways(y),E&&this.updatePathwayPriority(E)},onError:(d,h,u,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(d,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}}function dr(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=te({},n);return o.details=void 0,o.attrs=new Z(o.attrs),o.url=o.attrs.URI=hr(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function hr(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n==null?void 0:n[e],o&&(a=o));const l=new self.URL(a);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const Do=/^age:\s*[\d.]+\s*$/im;class ur{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new tt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=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()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(s,t.url)}).catch(n=>(s.open("GET",t.url,!0),r(s,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{this.callbacks.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=this.context.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=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:n,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 n=t.status,o=t.responseType!=="text";if(n>=200&&n<300&&(o&&t.response||t.responseText!==null)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(s.loaded=s.total=c,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(s,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:n};this.callbacks.onSuccess(h,s,e,t)}else{const l=r.loadPolicy.errorRetry,c=s.retry;ct(l,c,!1,n)?this.retry(l):(v.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,s))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,s=this.stats.retry;if(ct(t,s,!0))this.retry(t);else{v.warn(`timeout while loading ${this.context.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=$t(e,s.retry),s.retry++,v.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Do.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}}function Co(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const _o=/(\d+)-(\d+)\/(\d+)/;class fr{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Fo,this.controller=new self.AbortController,this.stats=new tt}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}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();const r=ko(e,this.controller.signal),n=s.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&B(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const u=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},d-(u-i.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new Oo(g||"fetch, bad network response",f,h)}return i.loading.first=u,i.total=Po(h.headers)||i.total,n&&B(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,n):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const{response:u}=this;self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const f=h[l];f&&(i.loaded=i.total=f);const g={url:u.url,data:h,code:u.status};n&&!B(t.highWaterMark)&&n(i,e,h,u),s.onSuccess(g,i,e,u)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const u=h&&h.code||0,f=h?h.message:null;s.onError({code:u,text:f},e,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,s,i=0,r){const n=new Gi,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return n.dataLength&&r(t,s,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const d=c.value,h=d.length;return t.loaded+=h,h<i||n.dataLength?(n.push(d),n.dataLength>=i&&r(t,s,n.flush(),e)):r(t,s,d,e),l()}).catch(()=>Promise.reject());return l()}}function ko(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(te({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function wo(a){const e=_o.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Po(a){const e=a.get("Content-Range");if(e){const s=wo(e);if(B(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function Fo(a,e){return new self.Request(a.url,e)}class Oo extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const No=/\s/,Mo={newCue(a,e,t,s){const i=[];let r,n,o,l,c;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,l=0,c="",!r.isEmpty()){var h;for(let p=0;p<r.chars.length;p++)No.test(r.chars[p].uchar)&&o?l++:(c+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=sr(c.trim()),g=hs(e,t,f);a!=null&&(h=a.cues)!=null&&h.getCueById(g)||(n=new d(e,t,f),n.id=g,n.line=u+1,n.align="left",n.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),i.forEach(u=>ri(a,u))),i}},Bo={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Uo=oe(oe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ur,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Va,bufferController:Qa,capLevelController:ps,errorController:Fn,fpsController:Lo,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ks,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:Bo},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},$o()),{},{subtitleStreamController:qa,subtitleTrackController:ja,timelineController:xo,audioStreamController:Ha,audioTrackController:Wa,emeController:Ke,cmcdController:ke,contentSteeringController:bo});function $o(){return{cueHandler:Mo,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Go(a,e){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"');const t=ys(a),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const n=`${r==="level"?"playlist":r}LoadPolicy`,o=e[n]===void 0,l=[];i.forEach(c=>{const d=`${r}Loading${c}`,h=e[d];if(h!==void 0&&o){l.push(d);const u=t[n].default;switch(e[n]={default:u},c){case"TimeOut":u.maxLoadTimeMs=h,u.maxTimeToFirstByteMs=h;break;case"MaxRetry":u.errorRetry.maxNumRetry=h,u.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":u.errorRetry.retryDelayMs=h,u.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=h,u.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&v.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)}),oe(oe({},t),e)}function ys(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(ys):Object.keys(a).reduce((e,t)=>(e[t]=ys(a[t]),e),{}):a}function Vo(a){const e=a.loader;e!==fr&&e!==ur?(v.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Co()&&(a.loader=fr,a.progressive=!0,a.enableSoftwareAES=!0,v.log("[config]: Progressive streaming enabled, using FetchLoader"))}class De{static get version(){return"1.4.12"}static isSupported(){return Zn()}static get Events(){return m}static get ErrorTypes(){return G}static get ErrorDetails(){return I}static get DefaultConfig(){return De.defaultConfig?De.defaultConfig:Uo}static set DefaultConfig(e){De.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ss,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,Ar(e.debug||!1,"Hls instance");const t=this.config=Go(De.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Vo(t);const{abrController:s,bufferController:i,capLevelController:r,errorController:n,fpsController:o}=t,l=new n(this),c=this.abrController=new s(this),d=this.bufferController=new i(this),h=this.capLevelController=new r(this),u=new o(this),f=new mn(this),g=new xn(this),p=t.contentSteeringController,y=p?new p(this):null,E=this.levelController=new Nn(this,y),S=new Mn(this),x=new Un(this.config),R=this.streamController=new $a(this,S,x);h.setStreamController(R),u.setStreamController(R);const L=[f,E,R];y&&L.splice(1,0,y),this.networkControllers=L;const _=[c,d,h,u,g,S];this.audioTrackController=this.createController(t.audioTrackController,L);const D=t.audioStreamController;D&&L.push(new D(this,S,x)),this.subtitleTrackController=this.createController(t.subtitleTrackController,L);const k=t.subtitleStreamController;k&&L.push(new k(this,S,x)),this.createController(t.timelineController,_),x.emeController=this.emeController=this.createController(t.emeController,_),this.cmcdController=this.createController(t.cmcdController,_),this.latencyController=this.createController(Sn,_),this.coreComponents=_,L.push(l);const P=l.onErrorOut;typeof P=="function"&&this.on(m.ERROR,P,l)}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){v.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),this.trigger(m.ERROR,{type:G.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:e,error:s})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){v.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){v.log("attachMedia"),this._media=e,this.trigger(m.MEDIA_ATTACHING,{media:e})}detachMedia(){v.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,s=this.url,i=this.url=Lt.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});v.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}startLoad(e=-1){v.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){v.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){v.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){v.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){v.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){v.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){v.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){v.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){v.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=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(v.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Mt.indexOf(e)>-1&&(this._maxHdcpLevel=e)}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&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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 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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}De.defaultConfig=void 0;const zl="",Ne=(a,e)=>{const t=a.__vccOpts||a;for(const[s,i]of e)t[s]=i;return t},Le=Ne(Object.assign({name:"d-icon"},{props:{icon:String,size:[Number,String]},setup(a){const e=a,t=T.computed(()=>({fontSize:/^\d+$/.test(e.size)?e.size+"px":e.size}));return(s,i)=>(T.openBlock(),T.createElementBlock("i",{class:T.normalizeClass(["d-icon iconfont",a.icon]),style:T.normalizeStyle(t.value)},null,6))}}),[["__scopeId","data-v-23a64927"]]),Ql="",Ko={class:"d-player-top"},Ho={class:"top-title"},Wo={class:"top-title"},Yo=Ne({__name:"d-player-top",props:{title:{default:""}},setup(a){Date.prototype.format=function(s){let i={"h+":this.getHours(),"m+":this.getMinutes(),"s+":this.getSeconds()};for(var r in i)new RegExp("("+r+")").test(s)&&(s=s.replace(RegExp.$1,RegExp.$1.length==1?i[r]:("00"+i[r]).substr((""+i[r]).length)));return s};let e=T.ref("00:00:00");e.value=new Date().format("hh:mm:ss");let t=null;return t=setInterval(()=>{e.value=new Date().format("hh:mm:ss")},1e3),T.onUnmounted(()=>{clearInterval(t)}),(s,i)=>(T.openBlock(),T.createElementBlock("div",Ko,[T.createElementVNode("p",Ho,T.toDisplayString(a.title||""),1),T.createElementVNode("p",Wo,T.toDisplayString(T.unref(e)),1)]))}},[["__scopeId","data-v-2b918c6e"]]),qo={class:"d-status"},zo={class:"d-flex-center"},jo={class:"d-flex-center"},Xo=T.defineComponent({__name:"d-status",props:["state"],setup(a){return(e,t)=>T.withDirectives((T.openBlock(),T.createElementBlock("div",qo,[T.withDirectives(T.createElementVNode("li",zo,[T.createVNode(Le,{size:"18",class:"d-status-icon",icon:`icon-volume-${a.state.volume==0?"mute":a.state.volume>.5?"up":"down"}`},null,8,["icon"]),T.createTextVNode(" "+T.toDisplayString(~~(a.state.volume*100))+"% ",1)],512),[[T.vShow,a.state.handleType=="volume"]]),T.withDirectives(T.createElementVNode("li",jo,[T.createVNode(Le,{size:"12",icon:"icon-play"}),T.createVNode(Le,{size:"12",icon:"icon-play",style:{"margin-right":"5px"}}),T.createTextVNode("5倍速播放中 ")],512),[[T.vShow,a.state.handleType=="playbackRate"||a.state.isMultiplesPlay]])],512)),[[T.vShow,a.state.handleType||a.state.isMultiplesPlay]])}}),Zl="",Qo=Ne(Xo,[["__scopeId","data-v-a513aa28"]]),Jo=a=>(T.pushScopeId("data-v-cdd5271b"),a=a(),T.popScopeId(),a),Zo=["checked","true-value","false-value"],el=Jo(()=>T.createElementVNode("span",{class:"d-switch_action"},null,-1)),tl=T.defineComponent({__name:"d-switch",props:{modelValue:{type:[Number,String,Boolean]},width:{type:String,default:"40px"},trueValue:{type:[Number,String,Boolean],default:!0},falseValue:{type:[Number,String,Boolean],default:!0},activeColor:{type:[String],default:"#409EFF"}},emits:["update:modelValue","change"],setup(a,{emit:e}){T.useCssVars(o=>({"691633c8":a.width,"615d9f02":a.activeColor}));const t=a,s=e,i=T.ref(null),r=T.computed(()=>t.modelValue===t.trueValue),n=()=>{T.nextTick(()=>{const o=i.value.checked;s("update:modelValue",o),s("change",o)})};return(o,l)=>(T.openBlock(),T.createElementBlock("div",{class:T.normalizeClass(["d-switch",{"is-checked":r.value}])},[T.createElementVNode("input",{class:"d-switch__input",ref_key:"input",ref:i,type:"checkbox",checked:r.value,onChange:n,"true-value":a.trueValue,"false-value":a.falseValue},null,40,Zo),el],2))}}),ec="",Ts=Ne(tl,[["__scopeId","data-v-cdd5271b"]]),Qe=a=>(T.pushScopeId("data-v-6207422a"),a=a(),T.popScopeId(),a),sl={key:0},il=Qe(()=>T.createElementVNode("i",{class:"rotating iconfont icon-loading f50"},null,-1)),rl=[Qe(()=>T.createElementVNode("i",{class:"rotating iconfont icon-loading f50"},null,-1)),Qe(()=>T.createElementVNode("p",null,"正在缓冲...",-1))],nl=Qe(()=>T.createElementVNode("i",{class:"iconfont icon-replay f24 mr5"},null,-1)),al=Qe(()=>T.createElementVNode("i",{class:"iconfont icon-replay f24 mr5"},null,-1)),ol=T.defineComponent({__name:"d-loading",props:{loadType:String,text:{type:String,default:""}},setup(a){const{proxy:e}=T.getCurrentInstance(),t=["loadstart","waiting","ended","error","stalled"],s=a,i=()=>{e.$parent.play()},r=T.computed(()=>{let n="background: rgba(0, 0, 0, .1);z-index:1";return s.loadType=="loadstart"&&(n="background: rgba(0, 0, 0, 1);;z-index:3"),n});return(n,o)=>T.withDirectives((T.openBlock(),T.createElementBlock("div",{class:"d-loading",style:T.normalizeStyle(r.value)},[T.createElementVNode("div",null,[a.loadType=="loadstart"?(T.openBlock(),T.createElementBlock("span",sl,[il,T.createElementVNode("p",null,T.toDisplayString(a.text),1)])):T.createCommentVNode("",!0),T.withDirectives(T.createElementVNode("span",null,rl,512),[[T.vShow,a.loadType=="waiting"]]),T.withDirectives(T.createElementVNode("span",null,[T.createElementVNode("p",{onClick:i,class:"d-flex-x d-pointer"},[nl,T.createTextVNode("重新播放 ")])],512),[[T.vShow,a.loadType=="ended"]]),T.withDirectives(T.createElementVNode("span",null,[T.createElementVNode("p",{onClick:i,class:"d-flex-x d-pointer"},[al,T.createTextVNode("请求错误 ")])],512),[[T.vShow,a.loadType=="error"||a.loadType=="stalled"]])])],4)),[[T.vShow,t.includes(a.loadType)]])}}),ic="",ll=Ne(ol,[["__scopeId","data-v-6207422a"]]),St=function(a,e,t,s=!1){a&&e&&t&&a.addEventListener(e,t,s)},Je=function(a,e,t,s=!1){a&&e&&t&&a.removeEventListener(e,t,s)},cl=["onMousedown"],dl={name:"DSlider"},hl=T.defineComponent({...dl,props:{modelValue:{required:!0,type:Number,default:0},disabled:{type:Boolean,default:!1},vertical:{type:Boolean,default:!1},hover:{type:Boolean,default:!0},hoverText:{type:String,default:""},preload:{type:Number,default:0},size:{type:String,default:"10px"}},emits:["update:modelValue","change","onMousemove"],setup(a,{emit:e}){T.useCssVars(E=>({"230a335c":a.size}));const t=T.ref(null),s=T.ref(null),i=a,r=e,n=T.reactive({dragging:!1,hoverPosition:0,hoverTipsLeft:"50%"}),o=T.computed(()=>{let E=i.modelValue<0?0:i.modelValue>1?1:i.modelValue;return i.vertical?`height:${E*100}%`:`width:${E*100}%`}),l=T.computed(()=>{let E=i.preload<0?0:i.preload>1?1:i.preload;return i.vertical?`height:${E*100}%`:`width:${E*100}%`}),c=T.computed(()=>{let E=n.hoverPosition<0?0:n.hoverPosition>1?1:n.hoverPosition;return i.vertical?`bottom:${E*100}%`:`left:${E*100}%`}),d=E=>{E.preventDefault()},h=E=>{i.disabled||(E.preventDefault(),n.dragging=!0,f(E),St(window,"mousemove",p),St(window,"touchmove",p),St(window,"mouseup",y),St(window,"touchend",y))},u=E=>{if(!i.hover)return;let S=g(E);if(r("onMousemove",E,S),n.hoverPosition=S,i.vertical)return;let x=t.value,R=s.value.clientWidth/2,L=E.clientX-x.getBoundingClientRect().left;L<R?n.hoverTipsLeft=R-L+"px":x.clientWidth-L<R?n.hoverTipsLeft=x.clientWidth-L-R+"px":n.hoverTipsLeft="50%"},f=E=>{let S=g(E);r("update:modelValue",S),r("change",E,S)},g=E=>{let S=t.value,x=0;if(i.vertical){let R=S.clientHeight;x=(S.getBoundingClientRect().bottom-E.clientY)/R}else x=(E.clientX-S.getBoundingClientRect().left)/S.clientWidth;return x<0?0:x>1?1:x},p=E=>{f(E)},y=E=>{n.dragging&&(Je(window,"mousemove",p),Je(window,"touchmove",p),Je(window,"mouseup",y),Je(window,"touchend",y),Je(window,"contextmenu",y),setTimeout(()=>{n.dragging=!1},0))};return(E,S)=>(T.openBlock(),T.createElementBlock("div",{ref_key:"refSlider",ref:t,class:T.normalizeClass(["d-slider",{"is-vertical":i.vertical}]),onMousedown:T.withModifiers(h,["stop"]),onContextmenu:d},[T.createElementVNode("div",{class:"d-slider__runway",onMousemove:u},[T.withDirectives(T.createElementVNode("div",{class:"d-slider__cursor",style:T.normalizeStyle(c.value)},[T.withDirectives(T.createElementVNode("div",{class:"d-slider__tips",ref_key:"refTips",ref:s,style:T.normalizeStyle({left:n.hoverTipsLeft})},T.toDisplayString(i.hoverText),5),[[T.vShow,i.hoverText]])],4),[[T.vShow,i.hover]]),T.createElementVNode("div",{class:"d-slider__preload",style:T.normalizeStyle(l.value)},null,4),T.createElementVNode("div",{class:"d-slider__bar",style:T.normalizeStyle(o.value)},null,4)],32)],42,cl))}}),rc="",gr=Ne(hl,[["__scopeId","data-v-aa7c3172"]]),ul=a=>`${parseInt("0x"+a.slice(1,3))},${parseInt("0x"+a.slice(3,5))},${parseInt("0x"+a.slice(5,7))}`,fl=a=>a.charAt(0).toUpperCase()+a.slice(1),Es=a=>{let e=~~(a/3600),t=~~(a%3600/60),s=~~(a%60);return e=e<10?"0"+e:e,t=t<10?"0"+t:t,s=s<10?"0"+s:s,`${e}:${t}:${s}`},Ze="ontouchstart"in window,gl=a=>{let e=document,t=e.webkitIsFullScreen||e.fullscreen;return t?(document.exitFullscreen||e.webkitExitFullScreen).call(e):(a.requestFullscreen||a.webkitRequestFullScreen).call(a),!t},ml=a=>{document.pictureInPictureElement?document.exitPictureInPicture().catch(e=>{console.log(e,"Video failed to leave Picture-in-Picture mode.")}):a.requestPictureInPicture().catch(e=>{console.log(e,"Video failed to enter Picture-in-Picture mode.")})},mr=["loadstart","play","pause","playing","seeking","seeked","waiting","durationchange","progress","canplay","timeupdate","ended","error","stalled"],pl={width:{type:String,default:"800px"},height:{type:String,default:"450px"},color:{type:String,default:"#409eff"},src:{required:!0,type:String,default:""},title:{type:String,default:""},type:{type:String,default:"video/mp4"},poster:{type:String,default:""},webFullScreen:{type:Boolean,default:!1},speed:{type:Boolean,default:!0},currentTime:{type:Number,default:0},playsinline:{type:Boolean,default:!1},muted:{type:Boolean,default:!1},speedRate:{type:Array,default:()=>["2.0","1.5","1.25","1.0","0.75","0.5"]},autoPlay:{type:Boolean,default:!1},loop:{type:Boolean,default:!1},mirror:{type:Boolean,default:!1},ligthOff:{type:Boolean,default:!1},volume:{type:[String,Number],default:.3},control:{type:Boolean,default:!0},controlBtns:{type:Array,default:["audioTrack","quality","speedRate","volume","setting","pip","pageFullScreen","fullScreen"]},preload:{type:String,default:"auto"}},vt=a=>(T.pushScopeId("data-v-41c217ff"),a=a(),T.popScopeId(),a),yl={class:"d-player-video",id:"dPlayerVideo"},Tl=["controls","webkit-playsinline","playsinline","volume","muted","loop","preload","src","poster"],El={class:"d-player-lightoff"},xl={key:1,class:"d-player-state"},Sl={class:"d-play-btn"},vl=["onKeyup","onKeydown"],Ll={class:"d-control-progress"},Al={class:"d-tool-bar"},Il={key:0,class:"d-tool-item d-tool-time audioTrack-btn"},Rl=vt(()=>T.createElementVNode("span",{style:{margin:"0 3px"}},"/",-1)),bl={class:"total-time"},Dl={class:"d-tool-bar"},Cl={key:0,class:"d-tool-item quality-btn"},_l={class:"d-tool-item-main"},kl={class:"speed-main",style:{"text-align":"center"}},wl=["onClick"],Pl={key:1,class:"d-tool-item speedRate-btn"},Fl={class:"d-tool-item-main"},Ol={class:"speed-main"},Nl=["onClick"],Ml={key:2,class:"d-tool-item volume-btn"},Bl={class:"d-tool-item-main volume-box",style:{width:"52px"}},Ul={class:"volume-text-size"},$l={key:3,class:"d-tool-item setting-btn"},Gl={class:"d-tool-item-main"},Vl={class:"speed-main"},Kl=vt(()=>T.createElementVNode("div",{class:"d-tool-item-main"},"画中画",-1)),Hl=vt(()=>T.createElementVNode("div",{class:"d-tool-item-main"},"网页全屏",-1)),Wl=vt(()=>T.createElementVNode("div",{class:"d-tool-item-main"},"全屏",-1)),Yl={name:"vue3VideoPlay",inheritAttrs:!1},ql=T.defineComponent({...Yl,props:pl,emits:[...mr,"mirrorChange","loopChange","lightOffChange"],setup(a,{expose:e,emit:t}){T.useCssVars(w=>({b96309fe:T.unref(g),"0b1c41fe":w.width,"3e9d03ef":w.height}));const s=new De({fragLoadingTimeOut:2e3}),i=a,r=t,n=T.ref(null),o=T.ref(null),l=T.ref(null),c=T.ref(null),d=T.reactive({dVideo:null,...i,muted:i.muted,playBtnState:i.autoPlay?"pause":"play",loadStateType:"loadstart",fullScreen:!1,handleType:"",currentTime:"00:00:00",preloadBar:0,totalTime:"00:00:00",isVideoHovering:!0,speedActive:"1.0",playProgress:0,isMultiplesPlay:!1,longPressTimeout:null,progressCursorTime:"00:00:00",qualityLevels:[],currentLevel:0}),h=(...w)=>F=>w.reverse().reduce((M,q)=>q(M),F),u=mr.reduce((w,F)=>{let M=`on${fl(F)}`;return w[M]=q=>{d.loadStateType=F,r(F,q)},w},{});u.onCanplay=h(u.onCanplay,()=>{d.playBtnState!="play"&&d.dVideo.play(),d.autoPlay&&(d.dVideo.play(),d.playBtnState="pause")}),u.onEnded=h(u.onEnded,()=>{d.playBtnState="replay"}),u.onDurationchange=w=>{r("durationchange",w),i.currentTime!=0&&(d.dVideo.currentTime=i.currentTime),u.onTimeupdate(w)},u.onProgress=w=>{console.log("缓冲中..."),r("progress",w);let F=w.target.duration,M=w.target.buffered,q=w.target.buffered.length&&w.target.buffered.end(M-1);d.preloadBar=q/F},u.onTimeupdate=w=>{r("timeupdate",w);let F=w.duration||w.target.duration||0,M=w.currentTime||w.target.currentTime;d.playProgress=M/F,d.currentTime=Es(M),d.totalTime=Es(F)},u.onError=h(u.onError,()=>{d.playBtnState="replay"});let f=T.useAttrs();for(let w in f)u[w]=f[w];const g=ul(d.color),p=Ss(500,()=>{d.handleType=""}),y=w=>{w.preventDefault(),w.code=="ArrowUp"?d.volume=d.volume+.1>1?1:d.volume+.1:d.volume=d.volume-.1<0?0:d.volume-.1,d.muted=!1,d.handleType="volume",p()},E=w=>{i.speed&&(d.dVideo.currentTime=d.dVideo.currentTime<10?.1:d.dVideo.currentTime-10,u.onTimeupdate(d.dVideo),R())},S=w=>{w.preventDefault();let F=w.type;if(w.key=="ArrowRight"){if(R(),F=="keyup"){if(clearTimeout(d.longPressTimeout),!i.speed&&!d.longPressTimeout)return;d.isMultiplesPlay?(d.dVideo.playbackRate=d.speedActive,d.isMultiplesPlay=!1):(d.dVideo.currentTime=d.dVideo.currentTime+10,u.onTimeupdate(d.dVideo))}else if(F=="keydown"){if(!i.speed)return;d.isMultiplesPlay&&clearTimeout(d.longPressTimeout),d.longPressTimeout=setTimeout(()=>{d.isMultiplesPlay=!0,d.dVideo.playbackRate=5,d.handleType="playbackRate",p()},500)}}},x=()=>{Ze||c.value.focus()},R=()=>{d.loadStateType="play",d.dVideo.play().catch(()=>{d.dVideo.load(),setTimeout(()=>{d.dVideo.play().catch(()=>{d.playBtnState="replay",d.loadStateType="error"})},200)}),d.playBtnState="pause"},L=()=>{d.dVideo.pause(),d.playBtnState="play"},_=w=>{w&&w.preventDefault(),d.playBtnState=="play"||d.playBtnState=="replay"?R():d.playBtnState=="pause"&&L()},D=()=>{d.muted=!d.muted,d.volume==0&&(d.volume=.05)},k=(w,F)=>{let M=d.dVideo.duration||d.dVideo.target.duration;d.dVideo.currentTime=M*F,d.playBtnState=="play"&&(d.dVideo.play(),d.playBtnState="pause")},P=(w,F)=>{d.progressCursorTime=Es(d.dVideo.duration*F)},b=Ss(2500,()=>{d.isVideoHovering=!1}),U=w=>{d.isVideoHovering=!0,b()},O=(w,F)=>{s.currentLevel=F,d.currentLevel=F},Y=w=>{d.speedActive=w,d.dVideo.playbackRate=w},re=w=>{r("mirrorChange",w,d.dVideo)},j=w=>{r("loopChange",w,d.dVideo)},J=w=>{r("lightOffChange",w,d.dVideo)},X=()=>{ml(d.dVideo)},N=()=>{d.fullScreen=gl(n.value)},$=()=>{d.dVideo.canPlayType(i.type)||console.error("vue3-video-play: Format not supported,Check the [type] parameter"),d.dVideo.canPlayType(i.type)||d.dVideo.canPlayType("application/vnd.apple.mpegurl")?d.muted=i.autoPlay:De.isSupported()&&(s.detachMedia(),s.attachMedia(d.dVideo),s.on(De.Events.MEDIA_ATTACHED,()=>{s.loadSource(i.src),s.on("hlsManifestParsed",(w,F)=>{console.log(F),d.currentLevel=F.level,d.qualityLevels=F.levels||[]})}),s.on("hlsLevelSwitching",(w,F)=>{console.log(F),console.log("LEVEL_SWITCHING")}),s.on("hlsLevelSwitched",(w,F)=>{d.currentLevel=F.level,console.log("LEVEL_SWITCHED")}))};return T.watch(()=>i.src,()=>{T.nextTick(()=>{$()})},{immediate:!0}),T.onMounted(()=>{d.dVideo=o,x()}),e({play:R,pause:L,togglePlay:_}),(w,F)=>(T.openBlock(),T.createElementBlock("div",{ref_key:"refPlayerWrap",ref:n,id:"refPlayerWrap",class:T.normalizeClass(["d-player-wrap",{"web-full-screen":d.webFullScreen,"is-lightoff":d.lightOff,"d-player-wrap-hover":d.playBtnState=="play"||d.isVideoHovering}]),onMousemove:U,onContextmenu:F[8]||(F[8]=T.withModifiers(()=>{},["prevent"]))},[T.createElementVNode("div",yl,[T.createElementVNode("video",T.mergeProps({ref_key:"refdVideo",ref:o,class:["d-player-video-main",{"video-mirror":d.mirror}],id:"dPlayerVideoMain",controls:!!(T.unref(Ze)&&d.speed),"webkit-playsinline":i.playsinline,playsinline:i.playsinline},T.unref(u),{volume:d.volume,muted:d.muted,loop:d.loop,preload:w.preload,width:"100%",height:"100%",src:i.src,poster:i.poster})," 您的浏览器不支持Video标签。 ",16,Tl)]),T.createVNode(T.Transition,{name:"d-fade-in"},{default:T.withCtx(()=>[T.withDirectives(T.createElementVNode("div",El,null,512),[[T.vShow,d.lightOff]])]),_:1}),d.fullScreen?(T.openBlock(),T.createBlock(Yo,{key:0,title:i.title},null,8,["title"])):T.createCommentVNode("",!0),T.unref(Ze)?T.createCommentVNode("",!0):(T.openBlock(),T.createElementBlock("div",xl,[T.createVNode(T.Transition,{name:"d-scale-out"},{default:T.withCtx(()=>[T.withDirectives(T.createElementVNode("div",Sl,[T.createVNode(Le,{icon:"icon-play",size:40})],512),[[T.vShow,d.playBtnState=="play"]])]),_:1}),T.createVNode(Qo,{state:d},null,8,["state"])])),T.unref(Ze)?T.createCommentVNode("",!0):(T.openBlock(),T.createElementBlock("input",{key:2,type:"input",readonly:"readonly",ref_key:"refInput",ref:c,onDblclick:N,onKeyup:[T.withKeys(N,["f"]),F[0]||(F[0]=T.withKeys(M=>d.webFullScreen=!1,["esc"])),S],onClick:_,onKeydown:[T.withKeys(_,["space"]),T.withKeys(E,["arrow-left"]),T.withKeys(y,["arrow-up","arrow-down"]),S],class:"d-player-input",maxlength:"0"},null,40,vl)),T.createVNode(ll,{loadType:d.loadStateType},null,8,["loadType"]),!T.unref(Ze)&&d.control?(T.openBlock(),T.createElementBlock("div",{key:3,class:"d-player-control",ref_key:"refPlayerControl",ref:l},[T.createElementVNode("div",Ll,[T.createVNode(gr,{class:"d-progress-bar",onOnMousemove:P,onChange:k,disabled:!d.speed,hoverText:d.progressCursorTime,modelValue:d.playProgress,"onUpdate:modelValue":F[1]||(F[1]=M=>d.playProgress=M),preload:d.preloadBar},null,8,["disabled","hoverText","modelValue","preload"])]),T.createElementVNode("div",{class:"d-control-tool",onClick:x},[T.createElementVNode("div",Al,[T.createElementVNode("div",{class:"d-tool-item",onClick:_},[T.createVNode(Le,{size:"24",icon:`icon-${d.playBtnState}`},null,8,["icon"])]),i.controlBtns.includes("audioTrack")?(T.openBlock(),T.createElementBlock("div",Il,[T.createElementVNode("span",null,T.toDisplayString(d.currentTime),1),Rl,T.createElementVNode("span",bl,T.toDisplayString(d.totalTime),1)])):T.createCommentVNode("",!0)]),T.createElementVNode("div",Dl,[d.qualityLevels.length&&i.controlBtns.includes("quality")?(T.openBlock(),T.createElementBlock("div",Cl,[T.createTextVNode(T.toDisplayString(d.qualityLevels.length&&(d.qualityLevels[d.currentLevel]||{}).height)+"P ",1),T.createElementVNode("div",_l,[T.createElementVNode("ul",kl,[(T.openBlock(!0),T.createElementBlock(T.Fragment,null,T.renderList(d.qualityLevels,(M,q)=>(T.openBlock(),T.createElementBlock("li",{class:T.normalizeClass({"speed-active":d.currentLevel==q}),onClick:he=>O(M,q),key:M},T.toDisplayString(M.height)+"P ",11,wl))),128))])])])):T.createCommentVNode("",!0),i.controlBtns.includes("speedRate")?(T.openBlock(),T.createElementBlock("div",Pl,[T.createTextVNode(T.toDisplayString(d.speedActive=="1.0"?"倍速":d.speedActive+"x")+" ",1),T.createElementVNode("div",Fl,[T.createElementVNode("ul",Ol,[(T.openBlock(!0),T.createElementBlock(T.Fragment,null,T.renderList(d.speedRate,M=>(T.openBlock(),T.createElementBlock("li",{class:T.normalizeClass({"speed-active":d.speedActive==M}),onClick:q=>Y(M),key:M},T.toDisplayString(M)+"x ",11,Nl))),128))])])])):T.createCommentVNode("",!0),i.controlBtns.includes("volume")?(T.openBlock(),T.createElementBlock("div",Ml,[T.createElementVNode("div",Bl,[T.createElementVNode("div",{class:T.normalizeClass(["volume-main",{"is-muted":d.muted}])},[T.createElementVNode("span",Ul,T.toDisplayString(d.muted?0:~~(d.volume*100))+"%",1),T.createVNode(gr,{onChange:F[2]||(F[2]=M=>d.muted=!1),hover:!1,size:"5px",vertical:!0,modelValue:d.volume,"onUpdate:modelValue":F[3]||(F[3]=M=>d.volume=M)},null,8,["modelValue"])],2)]),T.createElementVNode("span",{onClick:D,style:{display:"flex"}},[T.createVNode(Le,{size:"20",icon:`icon-volume-${d.volume==0||d.muted?"mute":d.volume>.5?"up":"down"}`},null,8,["icon"])])])):T.createCommentVNode("",!0),i.controlBtns.includes("setting")?(T.openBlock(),T.createElementBlock("div",$l,[T.createVNode(Le,{size:"20",class:"rotateHover",icon:"icon-settings"}),T.createElementVNode("div",Gl,[T.createElementVNode("ul",Vl,[T.createElementVNode("li",null,[T.createTextVNode(" 镜像画面 "),T.createVNode(Ts,{onChange:re,modelValue:d.mirror,"onUpdate:modelValue":F[4]||(F[4]=M=>d.mirror=M)},null,8,["modelValue"])]),T.createElementVNode("li",null,[T.createTextVNode(" 循环播放 "),T.createVNode(Ts,{onChange:j,modelValue:d.loop,"onUpdate:modelValue":F[5]||(F[5]=M=>d.loop=M)},null,8,["modelValue"])]),T.createElementVNode("li",null,[T.createTextVNode(" 关灯模式 "),T.createVNode(Ts,{onChange:J,modelValue:d.lightOff,"onUpdate:modelValue":F[6]||(F[6]=M=>d.lightOff=M)},null,8,["modelValue"])])])])])):T.createCommentVNode("",!0),i.controlBtns.includes("pip")?(T.openBlock(),T.createElementBlock("div",{key:4,class:"d-tool-item pip-btn",onClick:X},[T.createVNode(Le,{size:"20",icon:"icon-pip"}),Kl])):T.createCommentVNode("",!0),i.controlBtns.includes("pageFullScreen")?(T.openBlock(),T.createElementBlock("div",{key:5,class:"d-tool-item pip-btn",onClick:F[7]||(F[7]=M=>d.webFullScreen=!d.webFullScreen)},[T.createVNode(Le,{size:"20",icon:"icon-web-screen"}),Hl])):T.createCommentVNode("",!0),i.controlBtns.includes("fullScreen")?(T.openBlock(),T.createElementBlock("div",{key:6,class:"d-tool-item fullScreen-btn",onClick:N},[Wl,T.createVNode(Le,{size:"20",icon:"icon-screen"})])):T.createCommentVNode("",!0)])])],512)):T.createCommentVNode("",!0)],34))}}),nc="",et=Ne(ql,[["__scopeId","data-v-41c217ff"]]);function pr(a){a.component(et.name,et)}et.install=pr,Ae.default=et,Ae.install=pr,Ae.videoPlay=et,Object.defineProperties(Ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});