1import{_ as hn}from"./client-only.CdBPenLZ.js";import{a as cn,_ as dn}from"./EntireResize.x4YkSxw8.js";import{k as un,_ as fn,e as ut,a as gn}from"./entry.2ehg4ZD6.js";import{d as mn,G as Z,H as pn,P as ft,Q as Wt,_ as qi,W as Le,T as yn,I as Yt,V as Tn,L as ee,M as fe,J as jt}from"./swiper-vue.iPC35nDh.js";const ze={huge:2560,large:1920,big:1366,medium:1024,small:768,tiny:320,thumbnail:245},En=["jpeg","png","webp","tiff","gif","jpg"],Lt=["mp4","3gp","mov","avi","m4v"];function Pe(r,e,t){var g,m,y,T,E;const i=Lt.includes(e.ext.toLowerCase().replace(".","")),s=`${t}_${e.hash}`,n=i||t.includes("poster")?".png":e.ext,a=i||t.includes("poster")?"image/png":e.mime,o=`${s}${n}`,l=un().public,h=l!=null&&l.cloudFolder?l.cloudFolder:l!=null&&l.cloudName?l.cloudName:(m=(g=e.provider_metadata)==null?void 0:g.bunnycdn)!=null&&m.url?e.provider_metadata.bunnycdn.url.replace("https://","").replace(/\.b-cdn\.net.*/gm,""):"local",c=l!=null&&l.cloudName?l.cloudName:l!=null&&l.cloudFolder?l.cloudFolder:(T=(y=e.provider_metadata)==null?void 0:y.bunnycdn)!=null&&T.url?e.provider_metadata.bunnycdn.url.replace("https://","").replace(/\.b-cdn\.net.*/gm,""):"local",d=`${h}/${o}`,u=(l==null?void 0:l.strapiURL)||"/cms",f=(l==null?void 0:l.bunnycdnProxyUrl)||(l==null?void 0:l.bunnycdnUrl)||`https://${c}.b-cdn.net`;r[t]={width:t.includes("original")?e.width:Math.min(e.width*ze[t.replace("-webp","").replace("-poster","")]/e.height,ze[t.replace("-webp","").replace("-poster","")])||e.width,height:t.includes("original")?e.height:Math.min(e.height*ze[t.replace("-webp","").replace("-poster","")]/e.width,ze[t.replace("-webp","").replace("-poster","")])||e.height,hash:s,name:o,ext:n,mime:a,url:u+"/uploads/"+o,provider_metadata:(E=e.provider_metadata)!=null&&E.bunnycdn?{bunnycdn:{id:d,url:`${f}/${d}`}}:void 0}}function Sn(r,e=!0){if(!r.url||!En.concat(Lt).includes(r.ext.toLowerCase().replace(".","")))return;const t={};return e?(Object.keys(ze).forEach(i=>{ze[i]<r.width&&(Lt.includes(r.ext.toLowerCase().replace(".",""))?(Pe(t,r,i+"-poster"),Pe(t,r,i+"-poster-webp")):(Pe(t,r,i),Pe(t,r,i+"-webp")))}),Lt.includes(r.ext.toLowerCase().replace(".",""))?(Pe(t,r,"original-poster"),Pe(t,r,"original-poster-webp")):(Pe(t,r,"original"),Pe(t,r,"original-webp"))):Pe(t,r,"thumbnail"),t}function xn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Zs={exports:{}};(function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,c){if(c=c||{},l=l.trim(),h=h.trim(),!h){if(!c.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var u=o.parseURL(h);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):h;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=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(m.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)m.path=f.path,u.params||(m.params=f.params,u.query||(m.query=f.query));else{var y=f.path,T=y.substring(0,y.lastIndexOf("/")+1)+u.path;m.path=o.normalizePath(T)}return m.path===null&&(m.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(m)},parseURL:function(l){var h=i.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};r.exports=o})()})(Zs);var wi=Zs.exports;function zi(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function he(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};
vendor: 6,036 bytes, line 1
1e%2?zi(Object(t),!0).forEach(function(i){Ln(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):zi(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function vn(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function An(r){var e=vn(r,"string");return typeof e=="symbol"?e:String(e)}function Ln(r,e,t){return e=An(e),e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function re(){return re=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},re.apply(this,arguments)}const O=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Rn=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=bn},bn=Number.MAX_SAFE_INTEGER||9007199254740991;let p=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r}({}),$=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),L=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r}({});const $e=function(){},mi={trace:$e,debug:$e,log:$e,warn:$e,info:$e,error:$e};let ot=mi;function In(r){const e=self.console[r];return e?e.bind(self.console,`[${r}] >`):$e}function Dn(r,...e){e.forEach(function(t){ot[t]=r[t]?r[t].bind(r):In(t)})}function Cn(r,e){if(typeof console=="object"&&r===!0||typeof r=="object"){Dn(r,"debug","log","info","warn","error");try{ot.log(`Debug logs enabled for "${e}
1" in hls.js version 1.5.6`)}catch{ot=mi}}else ot=mi}const v=ot,wn=/^(\d+)x(\d+)$/,Xi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ie{constructor(e){typeof e=="string"&&(e=ie.parseAttrList(e)),re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}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 i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=wn.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},s='"';for(Xi.lastIndex=0;(t=Xi.exec(e))!==null;){let n=t[2];n.indexOf(s)===0&&n.lastIndexOf(s)===n.length-1&&(n=n.slice(1,-1));const a=t[1].trim();i[a]=n}return i}}function kn(r){return r!=="ID"&&r!=="CLASS"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Pn(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"}class er{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==i[s]){v.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=s;break}e=re(new ie({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);O(i.getTime())&&(this._endDate=i)}}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(O(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&&O(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Ht{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 X={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class tr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[X.AUDIO]:null,[X.VIDEO]:null,[X.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=(t==null?void 0:t.byteRangeEndOffset)||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}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=wi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class qt extends tr{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 Ht,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get 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 i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!O(this.programDateTime))return null;const e=O(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;
vendor: 12,790 bytes, line 1
1if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===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,i,s,n,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[X.AUDIO]=null,e[X.VIDEO]=null,e[X.AUDIOVIDEO]=null}}class _n extends tr{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Ht,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.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 Fn=10;class On{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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?O(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Fn}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 ki(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function Mn(r){const e=pi(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Nn(r){const e=function(i,s,n){const a=i[s];i[s]=i[n],i[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function Un(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=ki(a)):t=Mn(a)}}return t}function pi(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}const Ze=typeof self<"u"?self:void 0;var te={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Qi(r){switch(r){case me.FAIRPLAY:return te.FAIRPLAY;case me.PLAYREADY:return te.PLAYREADY;case me.WIDEVINE:return te.WIDEVINE;case me.CLEARKEY:return te.CLEARKEY}}var ir={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Bn(r){if(r===ir.WIDEVINE)return te.WIDEVINE}function Ji(r){switch(r){case te.FAIRPLAY:return me.FAIRPLAY;case te.PLAYREADY:return me.PLAYREADY;case te.WIDEVINE:return me.WIDEVINE;case te.CLEARKEY:return me.CLEARKEY}}function zt(r){const{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[te.FAIRPLAY,te.WIDEVINE,te.PLAYREADY,te.CLEARKEY].filter(s=>!!e[s]):[];return!i[te.WIDEVINE]&&t&&i.push(te.WIDEVINE),i}const sr=function(r){return Ze!=null&&(r=Ze.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function $n(r,e,t,i){let s;switch(r){case te.FAIRPLAY:s=["cenc","sinf"];break;case te.WIDEVINE:case te.PLAYREADY:s=["cenc"];break;case te.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Gn(s,e,t,i)}function Gn(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs="${n}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs="${n}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function He(r,e,t){return Uint8Array.prototype.slice?r.slice(e,t):new Uint8Array(Array.prototype.slice.call(r,e,t))}const Pi=(r,e)=>e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,rr=(r,e)=>e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128,ht=(r,e)=>{const t=e;let i=0;for(;Pi(r,e);){i+=10;const s=Kt(r,e+6);i+=s,rr(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)},Kt=(r,e)=>{let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t},Hn=(r,e)=>Pi(r,e)&&Kt(r,e+6)+10<=r.length-e,_i=r=>{const e=ar(r);for(let t=0;t<e.length;t++){const i=e[t];if(nr(i))return qn(i)}},nr=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",Kn=r=>{const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Kt(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}},ar=r=>{let e=0;const t=[];for(;Pi(r,e);){const i=Kt(r,e+6);e+=10;const s=e+i;for(;e+8<s;){const n=Kn(r.subarray(e)),a=Vn(n);a&&t.push(a),e+=n.size+10}rr(r,e)&&(e+=10)}return t},Vn=r=>r.type==="PRIV"?Wn(r):r.type[0]==="W"?jn(r):Yn(r),Wn=r=>{if(r.size<2)return;const e=we(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}},Yn=r=>{if(r.size<2)return;if(r.type==="TXXX"){let t=1;const i=we(r.data.subarray(t),!0);t+=i.length+1;const s=we(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=we(r.data.subarray(1));return{key:r.type,data:e}},jn=r=>{if(r.type==="WXXX"){if(r.size<2)return;let t=1;const i=we(r.data.subarray(t),!0);t+=i.length+1;const s=we(r.data.subarray(t));return{key:r.type,info:i,data:s}}const e=we(r.data);return{key:r.type,data:e}},qn=r=>{if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},we=(r,e=!1)=>{const t=zn();if(t){const h=t.decode(r);if(e){const c=h.indexOf("\0");return c!==-1?h.substring(0,c):h}return h.replace(/\0/g,"")}const i=r.length;let s,n,a,o="",l=0;for(;l<i;){if(s=r[l++],s===0&&e)return o;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],o+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],a=r[l++],o+=String.fromCharCode((s&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o};let Xt;function zn(){if(!navigator.userAgent.includes("PlayStation 4"))return!Xt&&typeof self.TextDecoder<"u"&&(Xt=new self.TextDecoder("utf-8")),Xt}const be={hexDump:function(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},Pt=Math.pow(2,32)-1,Xn=[].push,or={video:1,audio:2,id3:3,text:4};function ne(r){return String.fromCharCode.apply(null,r)}function lr(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function N(r,e){const t=hr(r,e);return t<0?4294967296+t:t}function Zi(r,e){let t=N(r,e);return t*=Math.pow(2,32),t+=N(r,e+4),t}function hr(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Qt(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function Qn(r){const e=r.byteLength;for(let t=0;t<e;){const i=N(r,t);if(i>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=i>1?t+i:e}return!1}function V(r,e){const t=[];if(!e.length)return t;const i=r.byteLength;for(let s=0;s<i;){const n=N(r,s),a=ne(r.subarray(s+4,s+8)),o=n>1?s+n:i;if(a===e[0])if(e.length===1)t.push(r.subarray(s+8,o));else{const l=V(r.subarray(s+8,o),e.slice(1));l.length&&Xn.apply(t,l)}s=o}return t}function Jn(r){const e=[],t=r[0];let i=8;const s=N(r,i);i+=4;let n=0,a=0;t===0?(n=N(r,i),a=N(r,i+4),i+=8):(n=Zi(r,i),a=Zi(r,i+8),i+=16),i+=2;let o=r.length+a;const l=lr(r,i);i+=2;for(let h=0;h<l;h++){let c=i;const d=N(r,c);c+=4;const u=d&2147483647;if((d&2147483648)>>>31===1)return v.warn("SIDX has hierarchical references (not supported)"),null;const g=N(r,c);c+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+u-1}}),o+=u,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function cr(r){const e=[],t=V(r,["moov","trak"]);for(let s=0;s<t.length;s++){const n=t[s],a=V(n,["tkhd"])[0];if(a){let o=a[0];const l=N(a,o===0?12:20),h=V(n,["mdia","mdhd"])[0];if(h){o=h[0];const c=N(h,o===0?12:20),d=V(n,["mdia","hdlr"])[0];if(d){const u=ne(d.subarray(8,12)),f={soun:X.AUDIO,vide:X.VIDEO}[u];if(f){const g=V(n,["mdia","minf","stbl","stsd"])[0],m=Zn(g);e[l]={timescale:c,type:f},e[f]=he({timescale:c,id:l},m)}}}}}return V(r,["moov","mvex","trex"]).forEach(s=>{const n=N(s,4),a=e[n];a&&(a.default={duration:N(s,12),flags:N(s,20)})}),e}function Zn(r){const e=r.subarray(8),t=e.subarray(86),i=ne(e.subarray(4,8));let s=i;const n=i==="enca"||i==="encv";if(n){const o=V(e,[i])[0].subarray(i==="enca"?28:78);V(o,["sinf"]).forEach(h=>{const c=V(h,["schm"])[0];if(c){const d=ne(c.subarray(4,8));if(d==="cbcs"||d==="cenc"){const u=V(h,["frma"])[0];u&&(s=ne(u))}}})}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const a=V(t,["avcC"])[0];s+="."+gt(a[1])+gt(a[2])+gt(a[3]);break}case"mp4a":{const a=V(e,[i])[0],o=V(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=Jt(o,l),l+=2;const h=o[l++];if(h&128&&(l+=2),h&64&&(l+=o[l++]),o[l++]!==4)break;l=Jt(o,l);const c=o[l++];if(c===64)s+="."+gt(c);else break;if(l+=12,o[l++]!==5)break;l=Jt(o,l);const d=o[l++];let u=(d&248)>>3;u===31&&(u+=1+((d&7)<<3)+((o[l]&224)>>5)),s+="."+u}break}case"hvc1":case"hev1":{const a=V(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],h=o&31,c=N(a,2),d=(o&32)>>5?"H":"L",u=a[12],f=a.subarray(6,12);s+="."+l+h,s+="."+c.toString(16).toUpperCase(),s+="."+d+u;let g="";for(let m=f.length;m--;){const y=f[m];(y||g)&&(g="."+y.toString(16).toUpperCase()+g)}s+=g;break}case"dvh1":case"dvhe":{const a=V(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;s+="."+Re(o)+"."+Re(l);break}case"vp09":{const a=V(t,["vpcC"])[0],o=a[4],l=a[5],h=a[6]>>4&15;s+="."+Re(o)+"."+Re(l)+"."+Re(h);break}case"av01":{const a=V(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,h=a[2]>>>7?"H":"M",c=(a[2]&64)>>6,d=(a[2]&32)>>5,u=o===2&&c?d?12:10:c?10:8,f=(a[2]&16)>>4,g=(a[2]&8)>>3,m=(a[2]&4)>>2,y=a[2]&3;s+="."+o+"."+Re(l)+h+"."+Re(u)+"."+f+"."+g+m+y+"."+Re(1)+"."+Re(1)+"."+Re(1)+"."+0;break}}return{codec:s,encrypted:n}}function Jt(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function gt(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function Re(r){return(r<10?"0":"")+r}function ea(r,e){if(!r||!e)return r;const t=e.keyId;
vendor: 2,765 bytes, line 1
1return t&&e.isCommonEncryption&&V(r,["moov","trak"]).forEach(s=>{const a=V(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=V(a,["enca"]);const l=o.length>0;l||(o=V(a,["encv"])),o.forEach(h=>{const c=l?h.subarray(28):h.subarray(78);V(c,["sinf"]).forEach(u=>{const f=dr(u);if(f){const g=f.subarray(8,24);g.some(m=>m!==0)||(v.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${be.hexDump(g)} -> ${be.hexDump(t)}`),f.set(t,8))}})})}),r}function dr(r){const e=V(r,["schm"])[0];if(e){const t=ne(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return V(r,["schi","tenc"])[0]}return v.error("[eme] missing 'schm' box"),null}function ta(r,e){return V(e,["moof","traf"]).reduce((t,i)=>{const s=V(i,["tfdt"])[0],n=s[0],a=V(i,["tfhd"]).reduce((o,l)=>{const h=N(l,4),c=r[h];if(c){let d=N(s,4);if(n===1){if(d===Pt)return v.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;d*=Pt+1,d+=N(s,8)}const u=c.timescale||9e4,f=d/u;if(O(f)&&(o===null||f<o))return f}return o},null);return a!==null&&O(a)&&(t===null||a<t)?a:t},null)}function ia(r,e){let t=0,i=0,s=0;const n=V(r,["moof","traf"]);for(let a=0;a<n.length;a++){const o=n[a],l=V(o,["tfhd"])[0],h=N(l,4),c=e[h];if(!c)continue;const d=c.default,u=N(l,0)|(d==null?void 0:d.flags);let f=d==null?void 0:d.duration;u&8&&(u&2?f=N(l,12):f=N(l,8));const g=c.timescale||9e4,m=V(o,["trun"]);for(let y=0;y<m.length;y++){if(t=sa(m[y]),!t&&f){const T=N(m[y],4);t=f*T}c.type===X.VIDEO?i+=t/g:c.type===X.AUDIO&&(s+=t/g)}}if(i===0&&s===0){let a=1/0,o=0,l=0;const h=V(r,["sidx"]);for(let c=0;c<h.length;c++){const d=Jn(h[c]);if(d!=null&&d.references){a=Math.min(a,d.earliestPresentationTime/d.timescale);const u=d.references.reduce((f,g)=>f+g.info.duration||0,0);o=Math.max(o,u+d.earliestPresentationTime/d.timescale),l=o-a}}if(l&&O(l))return l}return i||s}function sa(r){const e=N(r,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=N(r,4);for(let n=0;n<s;n++){if(e&256){const a=N(r,t);i+=a,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function ra(r,e,t){V(e,["moof","traf"]).forEach(i=>{V(i,["tfhd"]).forEach(s=>{const n=N(s,4),a=r[n];if(!a)return;const o=a.timescale||9e4;V(i,["tfdt"]).forEach(l=>{const h=l[0],c=t*o;if(c){let d=N(l,4);if(h===0)d-=c,d=Math.max(d,0),Qt(l,4,d);else{d*=Math.pow(2,32),d+=N(l,8),d-=c,d=Math.max(d,0);const u=Math.floor(d/(Pt+1)),f=Math.floor(d%(Pt+1));Qt(l,4,u),Qt(l,8,f)}}})})})}function na(r){const e={valid:null,remainder:null},t=V(r,["moof"]);if(t.length<2)return e.remainder=r,e;const i=t[t.length-1];return e.valid=He(r,0,i.byteOffset-8),e.remainder=He(r,i.byteOffset-8),e}function Ee(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function es(r,e){const t=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;
vendor: 71,985 bytes, lines 1-8
1return V(i,["moof"]).map(l=>{const h=l.byteOffset-8;V(l,["traf"]).map(d=>{const u=V(d,["tfdt"]).map(f=>{const g=f[0];let m=N(f,4);return g===1&&(m*=Math.pow(2,32),m+=N(f,8)),m/s})[0];return u!==void 0&&(r=u),V(d,["tfhd"]).map(f=>{const g=N(f,4),m=N(f,0)&16777215,y=(m&1)!==0,T=(m&2)!==0,E=(m&8)!==0;let S=0;const b=(m&16)!==0;let x=0;const D=(m&32)!==0;let R=8;g===n&&(y&&(R+=8),T&&(R+=4),E&&(S=N(f,R),R+=4),b&&(x=N(f,R),R+=4),D&&(R+=4),e.type==="video"&&(a=aa(e.codec)),V(d,["trun"]).map(w=>{const P=w[0],I=N(w,0)&16777215,k=(I&1)!==0;let K=0;const _=(I&4)!==0,H=(I&256)!==0;let G=0;const B=(I&512)!==0;let j=0;const Q=(I&1024)!==0,M=(I&2048)!==0;let F=0;const q=N(w,4);let W=8;k&&(K=N(w,W),W+=4),_&&(W+=4);let z=K+h;for(let se=0;se<q;se++){if(H?(G=N(w,W),W+=4):G=S,B?(j=N(w,W),W+=4):j=x,Q&&(W+=4),M&&(P===0?F=N(w,W):F=hr(w,W),W+=4),e.type===X.VIDEO){let ae=0;for(;ae<j;){const ce=N(i,z);if(z+=4,oa(a,i[z])){const pe=i.subarray(z,z+ce);ur(pe,a?2:1,r+F/s,t)}z+=ce,ae+=ce+4}}r+=G/s}}))})})}),t}function aa(r){if(!r)return!1;const e=r.indexOf("."),t=e<0?r:r.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function oa(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ur(r,e,t,i){const s=fr(r);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(l===255);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(l===255);const h=s.length-n;let c=n;if(o<h)n+=o;else if(o>h){v.error(`Malformed SEI payload. ${o} is too small, only ${h} bytes left to parse.`);break}if(a===4){if(s[c++]===181){const u=lr(s,c);if(c+=2,u===49){const f=N(s,c);if(c+=4,f===1195456820){const g=s[c++];if(g===3){const m=s[c++],y=31&m,T=64&m,E=T?2+y*3:0,S=new Uint8Array(E);if(T){S[0]=m;for(let b=1;b<E;b++)S[b]=s[c++]}i.push({type:g,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const d=[];for(let g=0;g<16;g++){const m=s[c++].toString(16);d.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&d.push("-")}const u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[c++];i.push({payloadType:a,pts:t,uuid:d.join(""),userData:we(f),userDataBytes:f})}}}function fr(r){const e=r.byteLength,t=[];let i=1;for(;i<e-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return r;const s=e-t.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=r[a];return n}function la(r){const e=r[0];let t="",i="",s=0,n=0,a=0,o=0,l=0,h=0;if(e===0){for(;ne(r.subarray(h,h+1))!=="\0";)t+=ne(r.subarray(h,h+1)),h+=1;for(t+=ne(r.subarray(h,h+1)),h+=1;ne(r.subarray(h,h+1))!=="\0";)i+=ne(r.subarray(h,h+1)),h+=1;i+=ne(r.subarray(h,h+1)),h+=1,s=N(r,12),n=N(r,16),o=N(r,20),l=N(r,24),h=28}else if(e===1){h+=4,s=N(r,h),h+=4;const d=N(r,h);h+=4;const u=N(r,h);for(h+=4,a=2**32*d+u,Rn(a)||(a=Number.MAX_SAFE_INTEGER,v.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=N(r,h),h+=4,l=N(r,h),h+=4;ne(r.subarray(h,h+1))!=="\0";)t+=ne(r.subarray(h,h+1)),h+=1;for(t+=ne(r.subarray(h,h+1)),h+=1;ne(r.subarray(h,h+1))!=="\0";)i+=ne(r.subarray(h,h+1)),h+=1;i+=ne(r.subarray(h,h+1)),h+=1}const c=r.subarray(h,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function ha(r,...e){const t=e.length;let i=8,s=t;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function ca(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;if(e){i=1,s=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");s.set(l,o*16)}}else i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),ha([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t||new Uint8Array)}function da(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(r),i=t.getUint32(0);if(r.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=be.hexDump(new Uint8Array(r,12,16));const n=t.getUint32(28);if(e.version===0){if(i-32<n)return null;e.data=new Uint8Array(r,32,n)}else if(e.version===1){e.kids=[];for(let a=0;a<n;a++)e.kids.push(new Uint8Array(r,32+a*16,16))}return e}let mt={};class ct{static clearKeyUriToKeyIdMap(){mt={}}constructor(e,t,i,s=[1],n=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,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 me.FAIRPLAY:case me.WIDEVINE:case me.PLAYREADY:case me.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 i=ua(e);return new ct(this.method,this.uri,"identity",this.keyFormatVersions,i)}const t=Un(this.uri);if(t)switch(this.keyFormat){case me.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case me.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ca(i,null,t);const s=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(s)),a=n.substring(n.indexOf("<"),n.length),h=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(h){const c=h.childNodes[0]?h.childNodes[0].nodeValue:h.getAttribute("VALUE");if(c){const d=ki(c).subarray(0,16);Nn(d),this.keyId=d}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=mt[this.uri];if(!i){const s=Object.keys(mt).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),mt[this.uri]=i}this.keyId=i}return this}}function ua(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const gr=/\{\$([a-zA-Z0-9-_]+)\}/g;function ts(r){return gr.test(r)}function ge(r,e,t){if(r.variableList!==null||r.hasVariableRefs)for(let i=t.length;i--;){const s=t[i],n=e[s];n&&(e[s]=yi(r,n))}}function yi(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(gr,i=>{const s=i.substring(2,i.length-1),n=t==null?void 0:t[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function is(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function fa(r,e,t){const i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function st(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const _t={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ga(r,e){const t=_t[e];return!!t&&!!t[r.slice(0,4)]}function Zt(r,e,t=!0){return!r.split(",").some(i=>!mr(i,e,t))}function mr(r,e,t=!0){var i;const s=st(t);return(i=s==null?void 0:s.isTypeSupported(dt(r,e)))!=null?i:!1}function dt(r,e){return`${e}/mp4;codecs="${r}"`}function ss(r){if(r){const e=r.substring(0,4);return _t.video[e]}return 2}function Ft(r){return r.split(",").reduce((e,t)=>{const i=_t.video[t];return i?(i*2+e)/(e?3:2):(_t.audio[t]+e)/(e?2:1)},0)}const ei={};function ma(r,e=!0){if(ei[r])return ei[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[r];for(let i=0;i<t.length;i++)if(mr(t[i],"audio",e))return ei[r]=t[i],t[i];return r}const pa=/flac|opus/i;function Ot(r,e=!0){return r.replace(pa,t=>ma(t.toLowerCase(),e))}function rs(r,e){return r&&r!=="mp4a"?r:e}function ya(r){const e=r.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return r}const ns=/#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,as=/#EXT-X-MEDIA:(.*)/g,Ta=/^#EXT(?:INF|-X-TARGETDURATION):/m,os=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Ea=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|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class De{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return wi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Ta.test(e)}static parseMasterPlaylist(e,t){const i=ts(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];ns.lastIndex=0;let a;for(;(a=ns.exec(e))!=null;)if(a[1]){var o;const h=new ie(a[1]);ge(s,h,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const c=yi(s,a[2]),d={attrs:h,bitrate:h.decimalInteger("BANDWIDTH")||h.decimalInteger("AVERAGE-BANDWIDTH"),name:h.NAME,url:De.resolve(c,t)},u=h.decimalResolution("RESOLUTION");u&&(d.width=u.width,d.height=u.height),Sa(h.CODECS,d),(o=d.unknownCodecs)!=null&&o.length||n.push(d),s.levels.push(d)}else if(a[3]){const h=a[3],c=a[4];switch(h){case"SESSION-DATA":{const d=new ie(c);ge(s,d,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=d["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=d);break}case"SESSION-KEY":{const d=ls(c,t,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):v.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const d=new ie(c);ge(s,d,["NAME","VALUE","QUERYPARAM"]),is(s,d,t)}break}case"CONTENT-STEERING":{const d=new ie(c);ge(s,d,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:De.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=hs(c);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const n={},a=i.levels,o={AUDIO:a.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:a.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(as.lastIndex=0;(s=as.exec(e))!==null;){const h=new ie(s[1]),c=h.TYPE;if(c){const d=o[c],u=n[c]||[];n[c]=u,ge(i,h,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],m=h.CHANNELS,y=h.CHARACTERISTICS,T=h["INSTREAM-ID"],E={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:c,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?De.resolve(h.URI,t):""};if(g&&(E.assocLang=g),m&&(E.channels=m),y&&(E.characteristics=y),T&&(E.instreamId=T),d!=null&&d.length){const S=De.findGroup(d,E.groupId)||d[0];cs(E,S,"audioCodec"),cs(E,S,"textCodec")}u.push(E)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){const o=new On(t),l=o.fragments;let h=null,c=0,d=0,u=0,f=0,g=null,m=new qt(s,t),y,T,E,S=-1,b=!1,x=null;for(os.lastIndex=0,o.m3u8=e,o.hasVariableRefs=ts(e);(y=os.exec(e))!==null;){b&&(b=!1,m=new qt(s,t),m.start=u,m.sn=c,m.cc=f,m.level=i,h&&(m.initSegment=h,m.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null,x&&(m.setByteRange(x),x=null)));const P=y[1];if(P){m.duration=parseFloat(P);const I=(" "+y[2]).slice(1);m.title=I||null,m.tagList.push(I?["INF",P,I]:["INF",P])}else if(y[3]){if(O(m.duration)){m.start=u,E&&fs(m,E,o),m.sn=c,m.level=i,m.cc=f,l.push(m);const I=(" "+y[3]).slice(1);m.relurl=yi(o,I),ds(m,g),g=m,u+=m.duration,c++,d=0,b=!0}}else if(y[4]){const I=(" "+y[4]).slice(1);g?m.setByteRange(I,g):m.setByteRange(I)}else if(y[5])m.rawProgramDateTime=(" "+y[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),S===-1&&(S=l.length);else{if(y=y[0].match(Ea),!y){v.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<y.length&&!(typeof y[T]<"u");T++);const I=(" "+y[T]).slice(1),k=(" "+y[T+1]).slice(1),K=y[T+2]?(" "+y[T+2]).slice(1):"";switch(I){case"PLAYLIST-TYPE":o.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":c=o.startSN=parseInt(k);break;case"SKIP":{const _=new ie(k);ge(o,_,["RECENTLY-REMOVED-DATERANGES"]);const H=_.decimalInteger("SKIPPED-SEGMENTS");if(O(H)){o.skippedSegments=H;for(let B=H;B--;)l.unshift(null);c+=H}const G=_.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(o.recentlyRemovedDateranges=G.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(k),1);break;case"VERSION":o.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(k||K)&&m.tagList.push(K?[k,K]:[k]);break;case"DISCONTINUITY":f++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([I]);break;case"BITRATE":m.tagList.push([I,k]);break;case"DATERANGE":{const _=new ie(k);ge(o,_,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ge(o,_,_.clientAttrs);const H=new er(_,o.dateRanges[_.ID]);H.isValid||o.skippedSegments?o.dateRanges[H.id]=H:v.warn(`Ignoring invalid DATERANGE tag: "${k}"`),m.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const _=new ie(k);ge(o,_,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in _?fa(o,_,a):is(o,_,t)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(k);break;case"KEY":{const _=ls(k,t,o);if(_.isSupported()){if(_.method==="NONE"){E=void 0;break}E||(E={}),E[_.keyFormat]&&(E=re({},E)),E[_.keyFormat]=_}else v.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${k}"`);break}case"START":o.startTimeOffset=hs(k);break;case"MAP":{const _=new ie(k);if(ge(o,_,["BYTERANGE","URI"]),m.duration){const H=new qt(s,t);us(H,_,i,E),h=H,m.initSegment=h,h.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=h.rawProgramDateTime)}else{const H=m.byteRangeEndOffset;if(H){const G=m.byteRangeStartOffset;x=`${H-G}@${G}`}else x=null;us(m,_,i,E),h=m,b=!0}break}case"SERVER-CONTROL":{const _=new ie(k);o.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),o.holdBack=_.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const _=new ie(k);o.partTarget=_.decimalFloatingPoint("PART-TARGET");break}case"PART":{let _=o.partList;_||(_=o.partList=[]);const H=d>0?_[_.length-1]:void 0,G=d++,B=new ie(k);ge(o,B,["BYTERANGE","URI"]);const j=new _n(B,m,t,G,H);_.push(j),m.duration+=j.duration;break}case"PRELOAD-HINT":{const _=new ie(k);ge(o,_,["URI"]),o.preloadHint=_;break}case"RENDITION-REPORT":{const _=new ie(k);ge(o,_,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(_);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&&(ds(m,g),m.cc=f,o.fragmentHint=m,E&&fs(m,E,o));const D=l.length,R=l[0],w=l[D-1];if(u+=o.skippedSegments*o.targetduration,u>0&&D&&w){o.averagetargetduration=u/D;const P=w.sn;o.endSN=P!=="initSegment"?P:0,o.live||(w.endList=!0),R&&(o.startCC=R.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(u+=o.fragmentHint.duration),o.totalduration=u,o.endCC=f,S>0&&xa(l,S),o}}function ls(r,e,t){var i,s;const n=new ie(r);ge(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&v.error(`Invalid IV: ${n.IV}`);const d=o?De.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ct(a,d,c,u,l)}function hs(r){const t=new ie(r).decimalFloatingPoint("TIME-OFFSET");return O(t)?t:null}function Sa(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=t.filter(n=>ga(n,i));s.length&&(e[`${i}Codec`]=s.join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function cs(r,e,t){const i=e[t];i&&(r[t]=i)}function xa(r,e){let t=r[e];for(let i=e;i--;){const s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function ds(r,e){r.rawProgramDateTime?r.programDateTime=Date.parse(r.rawProgramDateTime):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime),O(r.programDateTime)||(r.programDateTime=null,r.rawProgramDateTime=null)}function us(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function fs(r,e,t){r.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}var Y={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function gs(r){const{type:e}=r;switch(e){case Y.AUDIO_TRACK:return U.AUDIO;case Y.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function ti(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class va{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Y.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:Y.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:Y.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:Y.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const h=s.context;if(h&&h.url===e.url&&h.level===e.level){v.trace("[playlist-loader]: playlist request ongoing");return}v.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===Y.MANIFEST?n=i.manifestLoadPolicy.default:n=re({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),O((t=e.deliveryDirectives)==null?void 0:t.part)){let h;if(e.type===Y.LEVEL&&e.level!==null?h=this.hls.levels[e.level].details:e.type===Y.AUDIO_TRACK&&e.id!==null?h=this.hls.audioTracks[e.id].details:e.type===Y.SUBTITLE_TRACK&&e.id!==null&&(h=this.hls.subtitleTracks[e.id].details),h){const c=h.partTarget,d=h.targetduration;if(c&&d){const u=Math.max(c*3,d*.8)*1e3;n=re({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(h,c,d,u)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const g=h.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(h,d,new Error("no EXTM3U delimiter"),u||null,c);return}c.parsing.start=performance.now(),De.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(h,c,d,u||null,f):this.handleMasterPlaylist(h,c,d,u)},onError:(h,c,d,u)=>{this.handleNetworkError(c,d,!1,h,u)},onTimeout:(h,c,d)=>{this.handleNetworkError(c,d,!0,void 0,h)}};s.load(e,o,l)}handleMasterPlaylist(e,t,i,s){const n=this.hls,a=e.data,o=ti(e,i),l=De.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:h,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:m=[],SUBTITLES:y,"CLOSED-CAPTIONS":T}=De.parseMasterPlaylistMedia(a,o,l);m.length&&!m.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(v.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ie({}),bitrate:0,url:""})),n.trigger(p.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:y,captions:T,contentSteering:h,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,s,n){const a=this.hls,{id:o,level:l,type:h}=i,c=ti(e,i),d=0,u=O(l)?l:O(o)?o:0,f=gs(i),g=De.parseLevelPlaylist(e.data,c,u,f,d,this.variableList);if(h===Y.MANIFEST){const m={attrs:new ie({}),bitrate:0,details:g,name:"",url:c};a.trigger(p.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===Y.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===Y.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Y.AUDIO_TRACK||e.type===Y.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);v.warn(`[playlist-loader]: ${a}`);let l=L.UNKNOWN,h=!1;const c=this.getInternalLoader(e);switch(e.type){case Y.MANIFEST:l=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,h=!0;break;case Y.LEVEL:l=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,h=!1;break;case Y.AUDIO_TRACK:l=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case Y.SUBTITLE_TRACK:l=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,h=!1;break}c&&this.resetInternalLoader(e.type);const d={type:$.NETWORK_ERROR,details:l,fatal:h,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){const u=(t==null?void 0:t.url)||e.url;d.response=he({url:u,data:void 0},s)}this.hls.trigger(p.ERROR,d)}handlePlaylistLoaded(e,t,i,s,n,a){const o=this.hls,{type:l,level:h,id:c,groupId:d,deliveryDirectives:u}=s,f=ti(t,s),g=gs(s),m=typeof s.level=="number"&&g===U.MAIN?h:void 0;if(!e.fragments.length){const T=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:T,reason:T.message,response:t,context:s,level:m,parent:g,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y){o.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:s,level:m,parent:g,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Y.MANIFEST:case Y.LEVEL:o.trigger(p.LEVEL_LOADED,{details:e,level:m||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case Y.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case Y.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:u});break}}}function pr(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function yr(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){v.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){v.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function Xe(r){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues)for(let t=r.cues.length;t--;)r.removeCue(r.cues[t]);e==="disabled"&&(r.mode=e)}function Ti(r,e,t,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=La(r.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function Aa(r,e){if(e<r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t;for(;i<=s;){const n=Math.floor((s+i)/2);if(e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n}return r[i].startTime-e<e-r[s].startTime?i:s}function La(r,e,t){const i=[],s=Aa(r,e);if(s>-1)for(let n=s,a=r.length;n<a;n++){const o=r[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Rt(r){const e=[];for(let t=0;t<r.length;t++){const i=r[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(r[t])}return e}var ve={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const Ra=.25;function Ei(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ms(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,JSON.stringify(s?he({type:s},i):i))}return n}const pt=(()=>{const r=Ei();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ii(r,e){return r.getTime()/1e3-e}function ba(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Ia{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(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Xe(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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return pr(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Ei();if(a)for(let o=0;o<n.length;o++){const l=n[o].type;if(l===ve.emsg&&!i||!s)continue;const h=ar(n[o].data);if(h){const c=n[o].pts;let d=c+n[o].duration;d>pt&&(d=pt),d-c<=0&&(d=c+Ra);for(let f=0;f<h.length;f++){const g=h[f];if(!nr(g)){this.updateId3CueEnds(c,l);const m=ms(a,c,d,g,l);m&&this.id3Track.addCue(m)}}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===t&&a.startTime<e&&a.endTime===pt&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let h;s==="audio"?h=c=>c.type===ve.audioId3&&l:s==="video"?h=c=>c.type===ve.emsg&&o:h=c=>c.type===ve.audioId3&&l||c.type===ve.emsg&&o,Ti(n,t,i,h)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:n}=t,a=Object.keys(n);if(s){const c=Object.keys(i).filter(d=>!a.includes(d));for(let d=c.length;d--;){const u=c[d];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!O(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,h=Ei();for(let c=0;c<a.length;c++){const d=a[c],u=n[d],f=ii(u.startDate,l),g=i[d],m=(g==null?void 0:g.cues)||{};let y=(g==null?void 0:g.durationKnown)||!1,T=pt;const E=u.endDate;if(E)T=ii(E,l),y=!0;else if(u.endOnNext&&!y){const b=a.reduce((x,D)=>{if(D!==u.id){const R=n[D];if(R.class===u.class&&R.startDate>u.startDate&&(!x||u.startDate<x.startDate))return R}return x},null);b&&(T=ii(b.startDate,l),y=!0)}const S=Object.keys(u.attr);for(let b=0;b<S.length;b++){const x=S[b];if(!kn(x))continue;const D=m[x];if(D)y&&!g.durationKnown&&(D.endTime=T);else if(h){let R=u.attr[x];Pn(x)&&(R=ba(R));const w=ms(h,f,T,{key:x,data:R},ve.dateRange);w&&(w.id=d,this.id3Track.addCue(w),m[x]=w)}}i[d]={cues:m,dateRange:u,durationKnown:y}}}}class Da{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:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let h=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||h===0)&&(h=n!==void 0?n:a*s);const c=s;return h+Math.min(this.stallCount*1,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),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 i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.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 i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.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 i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||n===1||!t.live)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(c,Math.max(1,d))}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 Si=["NONE","TYPE-0","TYPE-1",null];function Ca(r){return Si.indexOf(r)>-1}const Mt=["SDR","PQ","HLG"];function wa(r){return!!r&&Mt.indexOf(r)>-1}var lt={No:"",Yes:"YES",v2:"v2"};function ka(r,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:s}=r,n=e!==void 0?e-s:0;return t&&n<t?i?lt.v2:lt.Yes:lt.No}class ps{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&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 et{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return ys(this._audioGroups,e)}hasSubtitleGroup(e){return ys(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function ys(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function si(r,e){const t=e.startPTS;if(O(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&(s.duration=i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.start=r.start+(r.minEndPTS-r.start):e.start=r.start+r.duration:e.start=Math.max(r.start-e.duration,0)}function Tr(r,e,t,i,s,n){i-t<=0&&(v.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let o=t,l=i;const h=e.startPTS,c=e.endPTS;if(O(h)){const y=Math.abs(h-t);O(e.deltaPTS)?e.deltaPTS=Math.max(y,e.deltaPTS):e.deltaPTS=y,o=Math.max(t,h),t=Math.min(t,h),s=Math.min(s,e.startDTS),l=Math.min(i,c),i=Math.max(i,c),n=Math.max(n,e.endDTS)}const d=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;const u=e.sn;if(!r||u<r.startSN||u>r.endSN)return 0;let f;const g=u-r.startSN,m=r.fragments;for(m[g]=e,f=g;f>0;f--)si(m[f],m[f-1]);for(f=g;f<m.length-1;f++)si(m[f],m[f+1]);return r.fragmentHint&&si(m[m.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,d}function Pa(r,e){let t=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const h=i[l].initSegment;if(h){t=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s=0,n;if(Oa(r,e,(l,h)=>{l.relurl&&(s=l.cc-h.cc),O(l.startPTS)&&O(l.endPTS)&&(h.start=h.startPTS=l.startPTS,h.startDTS=l.startDTS,h.maxStartPTS=l.maxStartPTS,h.endPTS=l.endPTS,h.endDTS=l.endDTS,h.minEndPTS=l.minEndPTS,h.duration=l.endPTS-l.startPTS,h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),h.elementaryStreams=l.elementaryStreams,h.loader=l.loader,h.stats=l.stats,l.initSegment&&(h.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(h=>{var c;h&&(!h.initSegment||h.initSegment.relurl===((c=t)==null?void 0:c.relurl))&&(h.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=_a(r.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(s){v.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Fa(r.partList,e.partList,(l,h)=>{h.elementaryStreams=l.elementaryStreams,h.stats=l.stats}),n?Tr(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Er(r,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.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=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime}function _a(r,e,t){const i=re({},r);return t&&t.forEach(s=>{delete i[s]}),Object.keys(e).forEach(s=>{const n=new er(e[s].attr,i[s]);n.isValid?i[s]=n:v.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[s].attr)}"`)}),i}function Fa(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<=n;s++){const a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Oa(r,e,t){const i=e.skippedSegments,s=Math.max(r.startSN,e.startSN)-e.startSN,n=(r.fragmentHint?1:0)+(i?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,a=e.startSN-r.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let h=s;h<=n;h++){const c=l[a+h];let d=o[h];i&&!d&&h<i&&(d=e.fragments[h]=c),c&&d&&t(c,d)}}function Er(r,e){const t=e.startSN+e.skippedSegments-r.startSN,i=r.fragments;t<0||t>=i.length||xi(e,i[t].start)}function xi(r,e){if(e){const t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].start+=e;r.fragmentHint&&(r.fragmentHint.start+=e)}}function Ma(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const i=r.fragments;if(i.length&&t*4>e){const n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Na(r,e,t){if(!(r!=null&&r.details))return null;const i=r.details;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function Ts(r,e,t){var i;return r!=null&&r.details?Sr((i=r.details)==null?void 0:i.partList,e,t):null}function Sr(r,e,t){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function xr(r){r.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(s=>{s.level=t})})}function Nt(r){switch(r.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Es(r,e){const t=Nt(e);return r.default[`${t?"timeout":"error"}Retry`]}function Fi(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ss(r){return he(he({},r),{errorRetry:null,timeoutRetry:null})}function Ut(r,e,t,i){if(!r)return!1;const s=i==null?void 0:i.code,n=e<r.maxNumRetry&&(Ua(s)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,n):n}function Ua(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}const vr={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];const a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function Ba(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!O(e))return null;const i=r[0].programDateTime;if(e<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let n=0;n<r.length;++n){const a=r[n];if($a(e,t,a))return a}return null}function Bt(r,e,t=0,i=0){let s=null;if(r){s=e[r.sn-e[0].sn+1]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&(!r||r.level===s.level)&&vi(t,i,s)===0)return s;const n=vr.search(e,vi.bind(null,t,i));return n&&(n!==r||!s)?n:s}function vi(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function $a(r,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Ga(r,e){return vr.search(r,t=>t.cc<e?1:t.cc>e?-1:0)}var de={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Se={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Ha{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(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===U.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,s;if(t.fatal)return;const n=this.hls,a=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:de.DoNothing,flags:Se.None};return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=de.SendAlternateToPenaltyBox;return}case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var o,l;const h=t.parent===U.MAIN?t.level:n.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,h):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,h))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const h=n.levels[n.loadLevel];if(h&&(a.type===Y.AUDIO_TRACK&&h.hasAudioGroup(a.groupId)||a.type===Y.SUBTITLE_TRACK&&h.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=de.SendAlternateToPenaltyBox,t.errorAction.flags=Se.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const h=n.levels[n.loadLevel],c=h==null?void 0:h.attrs["HDCP-LEVEL"];c?t.errorAction={action:de.SendAlternateToPenaltyBox,flags:Se.MoveAllAlternatesMatchingHDCP,hdcpLevel:c}:this.keySystemError(t)}return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(s=t.level)!=null?s:n.loadLevel);return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction={action:de.DoNothing,flags:Se.None};return}t.type===$.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=Es(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Ut(s,n,Nt(e),e.response))return{action:de.RetryRequest,flags:Se.None,retryConfig:s,retryCount:n};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Es(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((c,d)=>c+d.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,Ut(o,l,Nt(e),e.response)))return{action:de.RetryRequest,flags:Se.None,retryConfig:o,retryCount:l};const h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var n,a;const h=e.details;s.loadError++,h===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1;const{levels:d,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=i;i.autoLevelEnabled||(i.loadLevel=-1);const m=(n=e.frag)==null?void 0:n.type,T=(m===U.AUDIO&&h===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(h===L.BUFFER_ADD_CODEC_ERROR||h===L.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:D})=>s.audioCodec!==D),S=e.sourceBufferName==="video"&&(h===L.BUFFER_ADD_CODEC_ERROR||h===L.BUFFER_APPEND_ERROR)&&d.some(({codecSet:D,audioCodec:R})=>s.codecSet!==D&&s.audioCodec===R),{type:b,groupId:x}=(a=e.context)!=null?a:{};for(let D=d.length;D--;){const R=(D+u)%d.length;if(R!==u&&R>=f&&R<=g&&d[R].loadError===0){var o,l;const w=d[R];if(h===L.FRAG_GAP&&e.frag){const P=d[R].details;if(P){const I=Bt(e.frag,P.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(b===Y.AUDIO_TRACK&&w.hasAudioGroup(x)||b===Y.SUBTITLE_TRACK&&w.hasSubtitleGroup(x))continue;if(m===U.AUDIO&&(o=s.audioGroups)!=null&&o.some(P=>w.hasAudioGroup(P))||m===U.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(P=>w.hasSubtitleGroup(P))||T&&s.audioCodec===w.audioCodec||!T&&s.audioCodec!==w.audioCodec||S&&s.codecSet===w.codecSet)continue}c=R;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:de.SendAlternateToPenaltyBox,flags:Se.None,nextAutoLevel:c}}return{action:de.SendAlternateToPenaltyBox,flags:Se.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case de.DoNothing:break;case de.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:a}=i;switch(s){case Se.None:this.switchLevel(e,a);break;case Se.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=Si[Si.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}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)}}class Oi{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(){this.timer!==-1&&(self.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 i=t==null?void 0:t.renditionReports;if(i){let s=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){v.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){s=n;break}else o===e.substring(0,o.length)&&(s=n)}if(s!==-1){const n=i[s],a=parseInt(n["LAST-MSN"])||(t==null?void 0:t.lastPartSn);let o=parseInt(n["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 ps(a,o>=0?o:void 0,lt.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,i){const{details:s,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&Pa(i,s),!this.canLoad||!s.live)return;let l,h,c;if(s.canBlockReload&&s.endSN&&s.advanced){const y=this.hls.config.lowLatencyMode,T=s.lastPartSn,E=s.endSN,S=s.lastPartIndex,b=S!==-1,x=T===E,D=y?0:S;b?(h=x?E+1:T,c=x?D:S+1):h=E+1;const R=s.age,w=R+s.ageHeader;let P=Math.min(w-s.partTarget,s.targetduration*1.5);if(P>0){if(i&&P>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${P} with playlist age: ${s.age}`),P=0;else{const I=Math.floor(P/s.targetduration);if(h+=I,c!==void 0){const k=Math.round(P%s.targetduration/s.partTarget);c+=k}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${P} skip sn ${I} to part ${c}`)}s.tuneInGoal=P}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,h,c),y||!x){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,h,c));const d=this.hls.mainForwardBufferInfo,u=d?d.end-d.len:0,f=(s.edge-u)*1e3,g=Ma(s,f);s.updated&&a>this.requestScheduled+g&&(this.requestScheduled=n.loading.start),h!==void 0&&s.canBlockReload?this.requestScheduled=n.loading.first+g-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=g);let m=this.requestScheduled-a;m=Math.max(0,m),this.log(`reload live playlist ${e} in ${Math.round(m)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),m)}else this.clearTimer()}getDeliveryDirectives(e,t,i,s){let n=ka(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=lt.No),new ps(i,s,n)}checkRetry(e){const t=e.details,i=Nt(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===de.RetryRequest||!s.resolved&&n===de.SendAlternateToPenaltyBox);if(l){var h;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(h=e.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const c=Fi(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${c}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}class Ke{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Ka{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ke(e),this.fast_=new Ke(t),this.defaultTTFB_=s,this.ttfb_=new Ke(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new Ke(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Ke(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Ke(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const Ar={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},xs={};function Va(r,e,t,i,s,n){const a=r.audioCodec?r.audioGroups:null,o=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let c=null;if(a!=null&&a.length)try{a.length===1&&a[0]?c=e.groups[a[0]].channels:c=a.reduce((d,u)=>{if(u){const f=e.groups[u];if(!f)throw new Error(`Audio track group ${u} not found`);Object.keys(f.channels).forEach(g=>{d[g]=(d[g]||0)+f.channels[g]})}return d},{2:0})}catch{return!0}return r.videoCodec!==void 0&&(r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(i,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(s,8e6))||!!c&&O(h)&&Object.keys(c).some(d=>parseInt(d)>h)}function Wa(r,e,t){const i=r.videoCodec,s=r.audioCodec;if(!i||!s||!t)return Promise.resolve(Ar);const n={width:r.width,height:r.height,bitrate:Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)),framerate:r.frameRate||30},a=r.videoRange;a!=="SDR"&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map(l=>({type:"media-source",video:he(he({},n),{},{contentType:dt(l,"video")})}));return s&&r.audioGroups&&r.audioGroups.forEach(l=>{var h;l&&((h=e.groups[l])==null||h.tracks.forEach(c=>{if(c.groupId===l){const d=c.channels||"",u=parseFloat(d);O(u)&&u>2&&o.push.apply(o,s.split(",").map(f=>({type:"media-source",audio:{contentType:dt(f,"audio"),channels:""+u}})))}}))}),Promise.all(o.map(l=>{const h=Ya(l);return xs[h]||(xs[h]=t.decodingInfo(l))})).then(l=>({supported:!l.some(h=>!h.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function Ya(r){const{audio:e,video:t}=r,i=t||e;if(i){const s=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${s}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${s}`}return""}function ja(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function qa(r,e){let t=!1,i=[];return r&&(t=r!=="SDR",i=[r]),e&&(i=e.allowedVideoRanges||Mt.slice(0),t=e.preferHDR!==void 0?e.preferHDR:ja(),t?i=i.filter(s=>s!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function za(r,e,t,i,s){const n=Object.keys(r),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2;let h=!0,c=!1,d=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:y,allowedVideoRanges:T}=qa(e,s);for(let x=n.length;x--;){const D=r[n[x]];h=D.channels[2]>0,d=Math.min(d,D.minHeight),u=Math.min(u,D.minFramerate),f=Math.min(f,D.minBitrate);const R=T.filter(w=>D.videoRanges[w]>0);R.length>0&&(c=!0,m=R)}d=O(d)?d:0,u=O(u)?u:0;const E=Math.max(1080,d),S=Math.max(30,u);return f=O(f)?f:t,t=Math.max(f,t),c||(e=void 0,m=[]),{codecSet:n.reduce((x,D)=>{const R=r[D];if(D===x)return x;if(R.minBitrate>t)return _e(D,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),x;if(!R.hasDefaultAudio)return _e(D,"no renditions with default or auto-select sound found"),x;if(o&&D.indexOf(o.substring(0,4))%5!==0)return _e(D,`audio codec preference "${o}" not found`),x;if(a&&!l){if(!R.channels[a])return _e(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),x}else if((!o||l)&&h&&R.channels[2]===0)return _e(D,"no renditions with stereo sound found"),x;return R.minHeight>E?(_e(D,`min resolution of ${R.minHeight} > maximum of ${E}`),x):R.minFramerate>S?(_e(D,`min framerate of ${R.minFramerate} > maximum of ${S}`),x):m.some(w=>R.videoRanges[w]>0)?R.maxScore<g?(_e(D,`max score of ${R.maxScore} < selected max of ${g}`),x):x&&(Ft(D)>=Ft(x)||R.fragmentError>r[x].fragmentError)?x:(g=R.maxScore,D):(_e(D,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),x)},void 0),videoRanges:m,preferHDR:y,minFramerate:u,minBitrate:f}}function _e(r,e){v.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Xa(r){return r.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Qa(r,e,t,i){return r.slice(t,i+1).reduce((s,n)=>{if(!n.codecSet)return s;const a=n.audioGroups;let o=s[n.codecSet];o||(s[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,a&&a.forEach(h=>{if(!h)return;const c=e.groups[h];o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(d=>{o.channels[d]=(o.channels[d]||0)+c.channels[d]})}),s},{})}function Ce(r,e,t){if("attrs"in r){const i=e.indexOf(r);if(i!==-1)return i}for(let i=0;i<e.length;i++){const s=e[i];if(Qe(r,s,t))return i}return-1}function Qe(r,e,t){const{groupId:i,name:s,lang:n,assocLang:a,characteristics:o,default:l}=r,h=r.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||e.lang===n)&&(n===void 0||e.assocLang===a)&&(l===void 0||e.default===l)&&(h===void 0||e.forced===h)&&(o===void 0||Ja(o,e.characteristics))&&(t===void 0||t(r,e))}function Ja(r,e=""){const t=r.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function Ve(r,e){const{audioCodec:t,channels:i}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Za(r,e,t,i,s){const n=e[i],o=e.reduce((u,f,g)=>{const m=f.uri;return(u[m]||(u[m]=[])).push(g),u},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));const l=n.videoRange,h=n.frameRate,c=n.codecSet.substring(0,4),d=vs(e,i,u=>{if(u.videoRange!==l||u.frameRate!==h||u.codecSet.substring(0,4)!==c)return!1;const f=u.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ce(r,g,s)>-1});return d>-1?d:vs(e,i,u=>{const f=u.audioGroups,g=t.filter(m=>!f||f.indexOf(m.groupId)!==-1);return Ce(r,g,s)>-1})}function vs(r,e,t){for(let i=e;i;i--)if(t(r[i]))return i;for(let i=e+1;i<r.length;i++)if(t(r[i]))return i;return-1}class eo{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:i,hls:s}=this,{autoLevelEnabled:n,media:a}=s;if(!t||!a)return;const o=performance.now(),l=i?i.stats:t.stats,h=i?i.duration:t.duration,c=o-l.loading.start,d=s.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=d){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||a.paused||!a.playbackRate||!a.readyState)return;const u=s.mainForwardBufferInfo;if(u===null)return;const f=this.bwEstimator.getEstimateTTFB(),g=Math.abs(a.playbackRate);if(c<=Math.max(f,1e3*(h/(g*2))))return;const m=u.len/g,y=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&y>-1,E=this.getBwEstimate(),S=s.levels,b=S[t.level],x=l.total||Math.max(l.loaded,Math.round(h*b.averageBitrate/8));let D=T?c-y:c;D<1&&T&&(D=Math.min(c,l.loaded*8/E));const R=T?l.loaded*1e3/D:0,w=R?(x-l.loaded)/R:x*8/E+f/1e3;if(w<=m)return;const P=R?R*8:E;let I=Number.POSITIVE_INFINITY,k;for(k=t.level-1;k>d;k--){const _=S[k].maxBitrate;if(I=this.getTimeToLoadFrag(f/1e3,P,h*_,!S[k].details),I<m)break}if(I>=w||I>h*10)return;s.nextLoadLevel=s.nextAutoLevel=k,T?this.bwEstimator.sample(c-Math.min(f,y),l.loaded):this.bwEstimator.sampleTTFB(c);const K=S[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>K&&this.resetEstimator(K),this.clearTimer(),v.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly; 2 Time to underbuffer: ${m.toFixed(3)} s 3 Estimated load time for current fragment: ${w.toFixed(3)} s 4 Estimated load time for down switch fragment: ${I.toFixed(3)} s 5 TTFB estimate: ${y|0} ms 6 Current BW estimate: ${O(E)?E|0:"Unknown"} bps 7 New BW estimate: ${this.getBwEstimate()|0} bps 8 Switching to level ${k} @ ${K|0} bps`),s.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(v.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Ka(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,h=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&h>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,h),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){const n=e+i/t,a=s?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,n=s.end-s.start;O(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===U.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const n={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==U.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,s,1,1);if(n>-1)return n;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return v.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}
8_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),h=this.getStarvationDelay();let c=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(h){const y=this.findBestLevel(l,a,s,h,0,c,d);if(y>=0)return y}let u=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!h){const y=this.bitrateTestDelay;y&&(u=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-y,v.info(`[abr] bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),c=d=1)}const f=this.findBestLevel(l,a,s,h,u,c,d);if(v.info(`[abr] ${h?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const g=i.levels[a],m=i.levels[i.loadLevel];return(g==null?void 0:g.bitrate)<(m==null?void 0:m.bitrate)?a:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,n,a,o){var l;const h=s+n,c=this.lastLoadedFragLevel,d=c===-1?this.hls.firstLevel:c,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:y,config:T}=this.hls;if(g.length===1)return 0;const E=g[d],S=!!(E!=null&&(l=E.details)!=null&&l.live),b=y===-1||c===-1;let x,D="SDR",R=(E==null?void 0:E.frameRate)||0;const{audioPreference:w,videoPreference:P}=T,I=this.audioTracksByGroup||(this.audioTracksByGroup=Xa(m));if(b){if(this.firstSelection!==-1)return this.firstSelection;const G=this.codecTiers||(this.codecTiers=Qa(g,I,t,i)),B=za(G,D,e,w,P),{codecSet:j,videoRanges:Q,minFramerate:M,minBitrate:F,preferHDR:q}=B;x=j,D=q?Q[Q.length-1]:Q[0],R=M,e=Math.max(e,F),v.log(`[abr] picked start tier ${JSON.stringify(B)}`)}else x=E==null?void 0:E.codecSet,D=E==null?void 0:E.videoRange;const k=f?f.duration:u?u.duration:0,K=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let G=i;G>=t;G--){var H;const B=g[G],j=G>d;if(!B)continue;if(T.useMediaCapabilities&&!B.supportedResult&&!B.supportedPromise){const se=navigator.mediaCapabilities;typeof(se==null?void 0:se.decodingInfo)=="function"&&Va(B,I,D,R,e,w)?(B.supportedPromise=Wa(B,I,se),B.supportedPromise.then(ae=>{if(!this.hls)return;B.supportedResult=ae;const ce=this.hls.levels,pe=ce.indexOf(B);ae.error?v.warn(`[abr] MediaCapabilities decodingInfo error: "${ae.error}" for level ${pe} ${JSON.stringify(ae)}`):ae.supported||(v.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${pe} ${JSON.stringify(ae)}`),pe>-1&&ce.length>1&&(v.log(`[abr] Removing unsupported level ${pe}`),this.hls.removeLevel(pe)))})):B.supportedResult=Ar}if(x&&B.codecSet!==x||D&&B.videoRange!==D||j&&R>B.frameRate||!j&&R>0&&R<B.frameRate||B.supportedResult&&!((H=B.supportedResult.decodingInfoResults)!=null&&H[0].smooth)){_.push(G);continue}const Q=B.details,M=(f?Q==null?void 0:Q.partTarget:Q==null?void 0:Q.averagetargetduration)||k;let F;j?F=o*e:F=a*e;const q=k&&s>=k*2&&n===0?g[G].averageBitrate:g[G].maxBitrate,W=this.getTimeToLoadFrag(K,F,q*M,Q===void 0);if(F>=q&&(G===c||B.loadError===0&&B.fragmentError===0)&&(W<=K||!O(W)||S&&!this.bitrateTestDelay||W<h)){const se=this.forcedAutoLevel;return G!==y&&(se===-1||se!==y)&&(_.length&&v.trace(`[abr] Skipped level(s) ${_.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[_[0]].codecs}" ${g[_[0]].videoRange}; not compatible with "${E.codecs}" ${D}`),v.info(`[abr] switch candidate:${d}->${G} adjustedbw(${Math.round(F)})-bitrate=${Math.round(F-q)} ttfb:${K.toFixed(1)} avgDuration:${M.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${W.toFixed(1)} firstSelection:${b} codecSet:${x} videoRange:${D} hls.loadLevel:${y}`)),b&&(this.firstSelection=G),G}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,s=Math.min(Math.max(e,i),t);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}class to{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(){}}var le={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class io{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(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const a=n.end;if(n.start<=e&&a!==null&&e<=a)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,s){this.timeRanges&&(this.timeRanges[e]=t);const n=(s==null?void 0:s.fragment.sn)||-1;
vendor: 162,113 bytes, lines 8-15
8Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(h=>{const c=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return c&&this.removeFragment(o.body),c})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s}=e;if(!t||i.sn==="initSegment")return;const n=We(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const h=i.elementaryStreams[l];if(!h)return;const c=t[l],d=o||h.partial===!0;a.range[l]=this.getBufferedTimes(i,s,d,c)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),yt(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=We(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,h=e.maxStartPTS||a;for(let c=0;c<s.length;c++){const d=s.start(c)-this.bufferPadding,u=s.end(c)+this.bufferPadding;if(h>=d&&l<=u){n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(a<u&&o>d){const f=Math.max(a,s.start(c)),g=Math.min(o,s.end(c));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=d)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const c=l[h];c&&yt(c)&&(s=c.body.start-o,n=c.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=c.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||yt(t))}getState(e){const t=We(e),i=this.fragments[t];return i?i.buffered?yt(i)?le.PARTIAL:le.OK:le.APPENDING:le.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:s}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const n=s?null:t,a=We(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:n}=t;if(i.sn==="initSegment")return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n,Object.keys(n).forEach(o=>{const l=n[o];this.detectEvictedFragments(o,l,a,s)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=We(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){const t=We(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==s)}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 yt(r){var e,t,i;return r.buffered&&(r.body.gap||((e=r.range.video)==null?void 0:e.partial)||((t=r.range.audio)==null?void 0:t.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function We(r){return`${r.type}_${r.level}_${r.sn}`}const so={length:0,start:()=>0,end:()=>0};class J{static isBuffered(e,t){try{if(e){const i=J.getBuffered(e);for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const s=J.getBuffered(e),n=[];let a;for(a=0;a<s.length;a++)n.push({start:s.start(a),end:s.end(a)});return this.bufferedInfo(n,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(h,c){const d=h.start-c.start;return d||c.end-h.end});let s=[];if(i)for(let h=0;h<e.length;h++){const c=s.length;if(c){const d=s[c-1].end;e[h].start-d<i?e[h].end>d&&(s[c-1].end=e[h].end):s.push(e[h])}else s.push(e[h])}else s=e;let n=0,a,o=t,l=t;for(let h=0;h<s.length;h++){const c=s[h].start,d=s[h].end;if(t+i>=c&&t<d)o=c,l=d,n=l-t;else if(t+i<c){a=c;break}}return{len:n,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return v.log("failed to get media.buffered",t),so}}}class Mi{constructor(e,t,i,s=0,n=-1,a=!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=Tt(),this.buffering={audio:Tt(),video:Tt(),audiovideo:Tt()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a}}function Tt(){return{start:0,executeStart:0,executeEnd:0,end:0}}function bt(r,e){for(let i=0,s=r.length;i<s;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function ro(r,e,t){return!!(e&&(t.endCC>t.startCC||r&&r.cc<t.startCC))}function no(r,e){const t=r.fragments,i=e.fragments;if(!i.length||!t.length){v.log("No fragments to align");return}const s=bt(t,i[0].cc);if(!s||s&&!s.startPTS){v.log("No frag in previous level to align on");return}return s}function As(r,e){if(r){const t=r.start+e;r.start=r.startPTS=t,r.endPTS=t+r.duration}}function Lr(r,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)As(t[i],r);e.fragmentHint&&As(e.fragmentHint,r),e.alignedSliding=!0}function ao(r,e,t){e&&(oo(r,t,e),!t.alignedSliding&&e&&$t(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&Er(e,t))}function oo(r,e,t){if(ro(r,t,e)){const i=no(t,e);i&&O(i.start)&&(v.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Lr(i.start,e))}}function $t(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,i=e.fragments;if(!t.length||!i.length)return;let s,n;const a=Math.min(e.endCC,r.endCC);e.startCC<a&&r.startCC<a&&(s=bt(i,a),n=bt(t,a)),(!s||!n)&&(s=i[Math.floor(i.length/2)],n=bt(t,s.cc)||t[Math.floor(t.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;const h=(l-o)/1e3-(n.start-s.start);Lr(h,r)}const Ls=Math.pow(2,17);class lo{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Oe({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(bs(e));return}else e.gap=!1;const h=this.loader=e.loader=n?new n(s):new a(s),c=Rs(e),d=Ss(s.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ls};e.stats=h.stats,h.load(c,u,{onSuccess:(f,g,m,y)=>{this.resetLoader(e,h);let T=f.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:y})},onError:(f,g,m,y)=>{this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:he({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:y}))},onAbort:(f,g,m)=>{this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:f}))},onProgress:(f,g,m,y)=>{t&&t({frag:e,part:null,payload:m,networkDetails:y})}})})}loadPart(e,t,i){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(bs(e,t));return}const h=this.loader=e.loader=n?new n(s):new a(s),c=Rs(e,t),d=Ss(s.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ls};t.stats=h.stats,h.load(c,u,{onSuccess:(f,g,m,y)=>{this.resetLoader(e,h),this.updateStatsFromPart(e,t);const T={frag:e,part:t,payload:f.data,networkDetails:y};i(T),o(T)},onError:(f,g,m,y)=>{this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:he({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:y}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,h),l(new Oe({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(e.duration/t.duration),h=Math.min(Math.round(i.loaded/n),l),d=(l-h)*Math.round(i.loaded/h);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Rs(r,e=null){const t=e||r,i={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(O(s)&&O(n)){var a;let o=s,l=n;if(r.sn==="initSegment"&&((a=r.decryptdata)==null?void 0:a.method)==="AES-128"){const h=n-s;h%16&&(l=n+(16-h%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function bs(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:$.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new Oe(i)}class Oe extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class ho{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 co{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 uo(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?He(r,0,e-t):r}class fo{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,h=l[0],c=l[1],d=l[2],u=l[3],f=new Uint32Array(256);let g=0,m=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 T=m^m<<1^m<<2^m<<3^m<<4;T=T>>>8^T&255^99,e[g]=T,t[T]=g;const E=f[g],S=f[E],b=f[S];let x=f[T]*257^T*16843008;s[g]=x<<24|x>>>8,n[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=b*16843009^S*65537^E*257^g*16843008,h[T]=x<<24|x>>>8,c[T]=x<<16|x>>>16,d[T]=x<<8|x>>>24,u[T]=x,g?(g=E^f[f[f[b^E]]],m^=f[f[m]]):g=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),d=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],m=f[1],y=f[2],T=f[3];let E,S;for(o=0;o<a;o++){if(o<n){E=h[o]=t[o];continue}S=E,o%n===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=u[o/n|0]<<24):n>6&&o%n===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),h[o]=E=(h[o-n]^S)>>>0}for(l=0;l<a;l++)o=a-l,l&3?S=h[o]:S=h[o-4],l<4||o<=4?c[l]=S:c[l]=g[d[S>>>24]]^m[d[S>>>16&255]]^y[d[S>>>8&255]]^T[d[S&255]],c[l]=c[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],c=o[2],d=o[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],g=u[1],m=u[2],y=u[3];const T=new Int32Array(e),E=new Int32Array(T.length);let S,b,x,D,R,w,P,I,k,K,_,H,G,B;const j=this.networkToHostOrderSwap;for(;t<T.length;){for(k=j(T[t]),K=j(T[t+1]),_=j(T[t+2]),H=j(T[t+3]),R=k^n[0],w=H^n[1],P=_^n[2],I=K^n[3],G=4,B=1;B<s;B++)S=l[R>>>24]^h[w>>16&255]^c[P>>8&255]^d[I&255]^n[G],b=l[w>>>24]^h[P>>16&255]^c[I>>8&255]^d[R&255]^n[G+1],x=l[P>>>24]^h[I>>16&255]^c[R>>8&255]^d[w&255]^n[G+2],D=l[I>>>24]^h[R>>16&255]^c[w>>8&255]^d[P&255]^n[G+3],R=S,w=b,P=x,I=D,G=G+4;S=a[R>>>24]<<24^a[w>>16&255]<<16^a[P>>8&255]<<8^a[I&255]^n[G],b=a[w>>>24]<<24^a[P>>16&255]<<16^a[I>>8&255]<<8^a[R&255]^n[G+1],x=a[P>>>24]<<24^a[I>>16&255]<<16^a[R>>8&255]<<8^a[w&255]^n[G+2],D=a[I>>>24]<<24^a[R>>16&255]<<16^a[w>>8&255]<<8^a[P&255]^n[G+3],E[t]=j(S^f),E[t+1]=j(D^g),E[t+2]=j(x^m),E[t+3]=j(b^y),f=k,g=K,m=_,y=H,t=t+4}return E.buffer}}const go=16;class Ni{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 i=self.crypto;i&&(this.subtle=i.subtle||i.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 i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?uo(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((s,n)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const a=this.flush();a?s(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:s,currentResult:n,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=Ee(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new fo),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=He(o,-16).buffer,h||null}webCryptoDecrypt(e,t,i){const s=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new co(s,t)),this.fastAesKey.expandKey().then(n=>s?(this.logOnce("WebCrypto AES decrypt"),new ho(s,new Uint8Array(i)).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(v.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%go;return i!==e.length&&(t=He(e,0,i),this.remainderData=He(e,i)),t}logOnce(e){this.logEnabled&&(v.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const mo={toString:function(r){let e="";const t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).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 Ui extends to{constructor(e,t,i,s,n){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=n,this.logPrefix=s,this.log=v.log.bind(v,`${s}:`),this.warn=v.warn.bind(v,`${s}:`),this.hls=e,this.fragmentLoader=new lo(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ni(e.config),e.on(p.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 i=t.partList;if(i!=null&&i.length){const n=i[i.length-1];return J.isBuffered(this.media,n.start+n.duration/2)}const s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(s.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:i,mediaBuffer:s,state:n}=this,a=i?i.currentTime:0,o=J.bufferInfo(s||i,a,e.maxBufferHole);if(this.log(`media seeking to ${O(a)?a.toFixed(3):a}, state: ${n}`),this.state===C.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,h=t.start-l,c=t.start+t.duration+l;if(!o.len||c<o.start||h>o.end){const d=a>c;(a<h||d)&&(d&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}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,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=n=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;const a=this.state;if(this.fragContextChanged(e)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(p.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===le.APPENDING){const n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===le.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:n}=i,a=e.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw s.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const h=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:h}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=C.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,s,n,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===U.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((s=e.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?mo.toString(J.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==U.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(d=>!!c[d])){this.state=C.IDLE;return}}const h=(l=this.levels)==null?void 0:l[e.level];h!=null&&h.fragmentError&&(this.log(`Resetting level fragment error count of ${h.fragmentError} on frag buffered`),h.fragmentError=0)}this.state=C.IDLE,o&&(!this.loadedmetadata&&e.type==U.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Mi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var n;const a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(p.KEY_LOADED,c),this.state===C.KEY_LOADING&&(this.state=C.IDLE),c}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const c=a.partList;if(c&&s){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const d=this.getNextPart(c,e,i);if(d>-1){const u=c[d];this.log(`Loading part sn: ${e.sn} p: ${u.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${d}-${c.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.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,s)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,u,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),O(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const l=this.config.progressive;let h;return l&&o?h=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,s)).catch(c=>this.handleFragLoadError(c)):h=Promise.all([this.fragmentLoader.load(e,l?s:void 0),o]).then(([c])=>(!l&&c&&s&&s(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;const l=[],h=(o=i.details)==null?void 0:o.partList,c=d=>{this.fragmentLoader.loadPart(e,d,s).then(u=>{l[d.index]=u;const f=u.part;this.hls.trigger(p.FRAG_LOADED,u);const g=Ts(i,e.sn,d.index+1)||Sr(h,e.sn,d.index+1);if(g)c(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};c(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.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:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a),this.updateLevelTiming(i,s,n,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${s}. The current chunk will not be buffered.`),null;const o=t[s],l=a>-1?Ts(o,n,a):null,h=l?l.fragment:Na(o,n,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,i,s,n){var a;if(!e||this.state!==C.PARSING)return;const{data1:o,data2:l}=e;let h=o;if(o&&l&&(h=Ee(o,l)),!((a=h)!=null&&a.length))return;const c={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:h};if(this.hls.trigger(p.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=J.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return O(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:s}}=this,n=J.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&n.nextStart<a.end)return J.bufferInfo(e,t,Math.max(n.nextStart,s))}return n}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=U.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,U.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:n}=this,a=i[0].start;let o;if(t.live){const l=n.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a)&&(o=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=i[0]);if(!o){const l=n.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===le.OK||i===le.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,n){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${s}" 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,i){let s=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const h=e[o];if(a=a&&!h.independent,s>-1&&i<h.start)break;const c=h.loaded;c?s=-1:(n||h.independent||a)&&h.fragment===t&&(s=o),n=c}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Ba(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Ga(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,h=s.maxFragLookUpTolerance,c=i.partList,d=!!(s.lowLatencyMode&&c!=null&&c.length&&l);d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let u;if(e<t){const f=e>t-h?0:h;u=Bt(n,a,e,f)}else u=a[a.length-1];if(u){const f=u.sn-i.startSN,g=this.fragmentTracker.getState(u);if((g===le.OK||g===le.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!d||c[0].fragment.sn>u.sn)&&n&&u.level===n.level){const y=a[f+1];u.sn<o&&this.fragmentTracker.getState(y)!==le.OK?u=y:u=null}}return u}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=i.currentTime,a=e.fragments[0].start,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||n<o-h)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=e.fragments[0].start,a=!t,o=e.alignedSliding&&O(n);if(a||!o&&!n){const{fragPrevious:l}=this;ao(l,i,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: ${l?l.sn:"na"} fragments: ${s}`),h}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,n=s?this.startTimeOffset:e.startTimeOffset;n!==null&&O(n)?(i=t+n,n<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${n} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}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 c=this.getCurrentContext(t.chunkMeta);c&&(t.frag=c.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=t.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:h}=a||{};if(a&&o===de.RetryRequest&&h){this.resetStartWhenNotLoaded(this.levelLastLoaded);const c=Fi(h,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${c}ms`),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=C.FRAG_LOADING_WAITING_RETRY}else if(h&&a)if(this.resetFragmentErrors(e),l<h.maxNumRetry)!n&&o!==de.RemoveAlternatePermanently&&(a.resolved=!0);else{v.warn(`${t.details} reached or exceeded max retry (${l})`);return}else(a==null?void 0:a.action)===de.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,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const n=!s;return n&&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(),n}return!1}resetFragmentErrors(e){e===U.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),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=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){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(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){var n;const a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,h)=>{const c=e.elementaryStreams[h];if(c){const d=c.endPTS-c.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${h} duration reliably (${d})`),l||!1;const u=s?0:Tr(a,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:a,level:i,drift:u,type:h,frag:e,start:c.startPTS,end:c.endPTS}),!0}return l},!1)&&((n=this.transmuxer)==null?void 0:n.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(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=C.PARSED,this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class Rr{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=po(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function po(r,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<r.length;s++){const n=r[s];t.set(n,i),i+=n.length}return t}function yo(){return typeof __HLS_WORKER_BUNDLE__=="function"}function To(){const r=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(r);return{worker:new self.Worker(e),objectURL:e}}function Eo(r){const e=new self.URL(r,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function Ie(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Bi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ee(this.cachedData,e),this.cachedData=null);let i=ht(e,0),s=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?_i(i):void 0,h=e.length;for((this.basePTS===null||this.frameIndex===0&&O(l))&&(this.basePTS=So(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ve.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(e,s)){const c=this.appendFrame(a,e,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=h}else Hn(e,s)?(i=ht(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ve.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===h&&n!==h){const c=He(e,n);this.cachedData?this.cachedData=Ee(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:Ie(),id3Track:o,textTrack:Ie()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ie(),id3Track:this._id3Track,textTrack:Ie()}}destroy(){}}const So=(r,e,t)=>{if(O(r))return r*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function xo(r,e,t,i){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((e[t+2]&192)>>>6)+1;const d=(e[t+2]&60)>>>2;if(d>c.length-1){const u=new Error(`invalid ADTS sampling index:${d}`);r.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:u,reason:u.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,v.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,o=new Array(4),n=d-3):(s=2,o=new Array(2),n=d):l.indexOf("android")!==-1?(s=2,o=new Array(2),n=d):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&d>=6?n=d-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(d>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(s=2,o=new Array(2)),n=d)),o[0]=s<<3,o[0]|=(d&14)>>1,o[1]|=(d&1)<<7,o[1]|=a<<3,s===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h}}function br(r,e){return r[e]===255&&(r[e+1]&246)===240}function Ir(r,e){return r[e+1]&1?7:9}function $i(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function vo(r,e){return e+5<r.length}function Gt(r,e){return e+1<r.length&&br(r,e)}function Ao(r,e){return vo(r,e)&&br(r,e)&&$i(r,e)<=r.length-e}function Lo(r,e){if(Gt(r,e)){const t=Ir(r,e);if(e+t>=r.length)return!1;const i=$i(r,e);if(i<=t)return!1;const s=e+i;return s===r.length||Gt(r,s)}return!1}function Dr(r,e,t,i,s){if(!r.samplerate){const n=xo(e,t,i,s);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,v.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Cr(r){return 1024*9e4/r}function Ro(r,e){const t=Ir(r,e);if(e+t<=r.length){const i=$i(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function wr(r,e,t,i,s){const n=Cr(r.samplerate),a=i+s*n,o=Ro(e,t);let l;if(o){const{frameLength:d,headerLength:u}=o,f=u+d,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 m={unit:l,pts:a};return g||r.samples.push(m),{sample:m,length:f,missing:g}}const h=e.length-t;return l=new Uint8Array(h),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:h,missing:-1}}let Et=null;const bo=[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],Io=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Do=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Co=[0,1,1,4];function kr(r,e,t,i,s){if(t+24>e.length)return;const n=Pr(e,t);if(n&&t+n.frameLength<=e.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Pr(r,e){const t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){const a=r[e+2]>>1&1,o=r[e+3]>>6,l=t===3?3-i:i===3?3:4,h=bo[l*14+s-1]*1e3,d=Io[(t===3?0:t===2?1:2)*3+n],u=o===3?1:2,f=Do[t][i],g=Co[i],m=f*8*g,y=Math.floor(f*h/d+a)*g;if(Et===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Et=S?parseInt(S[1]):0}return!!Et&&Et<=87&&i===2&&h>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:d,channelCount:u,frameLength:y,samplesPerFrame:m}}}function Gi(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function _r(r,e){return e+1<r.length&&Gi(r,e)}function wo(r,e){return Gi(r,e)&&4<=r.length-e}function Fr(r,e){if(e+1<r.length&&Gi(r,e)){const i=Pr(r,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===r.length||_r(r,n)}return!1}class ko extends Bi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ht(e,0);let i=(t==null?void 0:t.length)||0;if(Fr(e,i))return!1;for(let s=e.length;i<s;i++)if(Lo(e,i))return v.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ao(e,t)}appendFrame(e,t,i){Dr(e,this.observer,t,i,e.manifestCodec);const s=wr(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const Po=/\/emsg[-/]ID3/i;class _o{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const n=this.videoTrack=Ie("video",1),a=this.audioTrack=Ie("audio",1),o=this.txtTrack=Ie("text",1);if(this.id3Track=Ie("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=cr(e);if(l.video){const{id:h,timescale:c,codec:d}=l.video;n.id=h,n.timescale=o.timescale=c,n.codec=d}if(l.audio){const{id:h,timescale:c,codec:d}=l.audio;a.id=h,a.timescale=c,a.codec=d}o.id=or.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Qn(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Ee(this.remainderData,e));const o=na(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,t);return n.samples=es(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=es(e,t),{videoTrack:t,audioTrack:Ie(),id3Track:s,textTrack:Ie()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=V(e.samples,["emsg"]);s&&s.forEach(n=>{const a=la(n);if(Po.test(a.schemeIdUri)){const o=O(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=a.payload;i.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:ve.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const Or=(r,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class Fo extends Bi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Mr(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=ht(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&_i(t)!==void 0&&Or(e,i)<16}}function Mr(r,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const o=[48e3,44100,32e3][n],l=e[t+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+c>e.length)return-1;const d=e[t+6]>>5;let u=0;d===2?u+=2:(d&1&&d!==1&&(u+=2),d&4&&(u+=2));const f=(e[t+6]<<8|e[t+7])>>12-u&1,m=[2,1,2,3,3,4,4,5][d]+f,y=e[t+5]>>3,T=e[t+5]&7,E=new Uint8Array([n<<6|y<<1|T>>2,(T&3)<<6|d<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,b=i+s*S,x=e.subarray(t,t+c);return r.config=E,r.channelCount=m,r.samplerate=o,r.samples.push({unit:x,pts:b}),c}class Oo{constructor(){this.VideoSample=null}createVideoSample(e,t,i,s){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:s,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&v.log(e.pts+"/"+e.dts+":"+e.debug)}}class Is{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&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?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8,s;for(let n=0;n<e;n++)i!==0&&(s=this.readEG(),i=(t+s+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,s=0,n,a,o;const l=this.readUByte.bind(this),h=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);l();const y=l();if(h(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=c();if(D===3&&u(1),g(),g(),u(1),d())for(a=D!==3?8:12,o=0;o<a;o++)d()&&(o<6?m(16):m(64))}g();const T=c();if(T===0)c();else if(T===1)for(u(1),f(),f(),n=c(),o=0;o<n;o++)f();g(),u(1);const E=c(),S=c(),b=h(1);b===0&&u(1),u(1),d()&&(e=c(),t=c(),i=c(),s=c());let x=[1,1];if(d()&&d())switch(l()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((E+1)*16-e*2-t*2),height:(2-b)*(S+1)*16-(b?2:4)*(i+s),pixelRatio:x}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Mo extends Oo{parseAVCPES(e,t,i,s,n){const a=this.parseAVCNALu(e,i.data);let o=this.VideoSample,l,h=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach(c=>{var d;switch(c.type){case 1:{let m=!1;l=!0;const y=c.data;if(h&&y.length>4){const T=new Is(y).readSliceType();(T===2||T===4||T===7||T===9)&&(m=!0)}if(m){var u;(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=m;break}case 5:l=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,ur(c.data,1,i.pts,t.samples);break}case 7:{var f,g;l=!0,h=!0;const m=c.data,T=new Is(m).readSPS();if(!e.sps||e.width!==T.width||e.height!==T.height||((f=e.pixelRatio)==null?void 0:f[0])!==T.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[m],e.duration=n;const E=m.subarray(1,4);let S="avc1.";for(let b=0;b<3;b++){let x=E[b].toString(16);x.length<2&&(x="0"+x),S+=x}e.codec=S}break}case 8:l=!0,e.pps=[c.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&l&&o.units.push(c)}),s&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let s=e.naluState||0;const n=s,a=[];let o=0,l,h,c,d=-1,u=0;for(s===-1&&(d=0,u=t[0]&31,s=0,o=1);o<i;){if(l=t[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(h=o-s-1,d>=0){const f={data:t.subarray(d,h),type:u};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=Ee(f.data,t.subarray(0,h)),f.state=0))}o<i?(c=t[o]&31,d=o,u=c,s=0):s=-1}else s=0}if(d>=0&&s>=0){const f={data:t.subarray(d,i),type:u,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Ee(f.data,t))}return e.naluState=s,a}}class No{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ni(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){const a=fr(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const n=e[t].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}}const oe=188;class Ue{constructor(e,t,i){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._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new Mo}static probe(e){const t=Ue.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 i=Math.min(oe*5,t-oe)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<t;l+=oe)if(e[l]===71&&(t-l===oe||e[l+oe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+oe*99,e.length-oe)+1)),n||(n=Ai(e,l)===0),n&&o>1&&(a===0&&o>2||l+oe>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:or[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ue.createTrack("video"),this._audioTrack=Ue.createTrack("audio",s),this._id3Track=Ue.createTrack("id3"),this._txtTrack=Ue.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack;let c=a.pid,d=a.pesData,u=o.pid,f=l.pid,g=o.pesData,m=l.pesData,y=null,T=this.pmtParsed,E=this._pmtId,S=e.length;if(this.remainderData&&(e=Ee(this.remainderData,e),S=e.length,this.remainderData=null),S<oe&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};const b=Math.max(0,Ue.syncOffset(e));S-=(S-b)%oe,S<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let x=0;for(let R=b;R<S;R+=oe)if(e[R]===71){const w=!!(e[R+1]&64),P=Ai(e,R),I=(e[R+3]&48)>>4;let k;if(I>1){if(k=R+5+e[R+4],k===R+oe)continue}else k=R+4;switch(P){case c:w&&(d&&(n=Ye(d))&&this.videoParser.parseAVCPES(a,h,n,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(e.subarray(k,R+oe)),d.size+=R+oe-k);break;case u:if(w){if(g&&(n=Ye(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(k,R+oe)),g.size+=R+oe-k);break;case f:w&&(m&&(n=Ye(m))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,R+oe)),m.size+=R+oe-k);break;case 0:w&&(k+=e[k]+1),E=this._pmtId=Uo(e,k);break;case E:{w&&(k+=e[k]+1);const K=Bo(e,k,this.typeSupported,i);c=K.videoPid,c>0&&(a.pid=c,a.segmentCodec=K.segmentVideoCodec),u=K.audioPid,u>0&&(o.pid=u,o.segmentCodec=K.segmentAudioCodec),f=K.id3Pid,f>0&&(l.pid=f),y!==null&&!T&&(v.warn(`MPEG-TS PMT found at ${R} after unknown PID '${y}'. Backtracking to sync byte @${b} to parse all TS packets.`),y=null,R=b-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=P;break}}else x++;if(x>0){const R=new Error(`Found ${x} TS packet/s that do not start with 0x47`);this.observer.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message})}a.pesData=d,o.pesData=g,l.pesData=m;const D={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:n}=e,a=i.pesData,o=t.pesData,l=s.pesData;let h;if(a&&(h=Ye(a))?(this.videoParser.parseAVCPES(i,n,h,!0,this._duration),i.pesData=null):i.pesData=a,o&&(h=Ye(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,h);break;case"mp3":this.parseMPEGPES(t,h);break;case"ac3":this.parseAC3PES(t,h);break}t.pesData=null}else o!=null&&o.size&&v.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(h=Ye(l))?(this.parseID3PES(s,h),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new No(this.observer,this.config,t);return this.decrypt(s,n)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let n=t.data;if(s){this.aacOverFlow=null;const d=s.missing,u=s.sample.unit.byteLength;if(d===-1)n=Ee(s.sample.unit,n);else{const f=u-d;s.sample.unit.set(n.subarray(0,d),f),e.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!Gt(n,a);a++);if(a!==i){let d;const u=a<o-1;u?d=`AAC PES did not start with ADTS header,offset:${a}`:d="No ADTS header found in AAC PES";const f=new Error(d);if(v.warn(`parsing error: ${d}`),this.observer.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:d}),!u)return}Dr(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(s){const d=Cr(e.samplerate);l=s.sample.pts+d}else{v.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,c;for(;a<o;)if(c=wr(e,n,a,l,h),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(h++;a<o-1&&!Gt(n,a);a++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let n=0,a=0;const o=t.pts;if(o===void 0){v.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(_r(i,a)){const l=kr(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(s===void 0){v.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let a=0,o=0,l;for(;o<n&&(l=Mr(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){v.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=re({},t,{type:this._videoTrack?ve.emsg:ve.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Ai(r,e){return((r[e+1]&31)<<8)+r[e+2]}function Uo(r,e){return(r[e+10]&31)<<8|r[e+11]}function Bo(r,e,t,i){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=(r[e+1]&15)<<8|r[e+2],a=e+3+n-4,o=(r[e+10]&15)<<8|r[e+11];for(e+=12+o;e<a;){const l=Ai(r,e),h=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){ri("ADTS AAC");break}case 15:s.audioPid===-1&&(s.audioPid=l);break;case 21:s.id3Pid===-1&&(s.id3Pid=l);break;case 219:if(!i){ri("H.264");break}case 27:s.videoPid===-1&&(s.videoPid=l,s.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?v.log("MPEG audio found, not supported in this browser"):s.audioPid===-1&&(s.audioPid=l,s.segmentAudioCodec="mp3");break;case 193:if(!i){ri("AC-3");break}case 129:t.ac3?s.audioPid===-1&&(s.audioPid=l,s.segmentAudioCodec="ac3"):v.log("AC-3 audio found, not supported in this browser");break;case 6:if(s.audioPid===-1&&h>0){let c=e+5,d=h;for(;d>2;){switch(r[c]){case 106:t.ac3!==!0?v.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=l,s.segmentAudioCodec="ac3");break}const f=r[c+1]+2;c+=f,d-=f}}break;case 194:case 135:v.warn("Unsupported EC-3 in M2TS found");break;case 36:v.warn("Unsupported HEVC in M2TS found");break}e+=h+5}return s}function ri(r){v.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Ye(r){let e=0,t,i,s,n,a;const o=r.data;if(!r||r.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Ee(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>r.size-6)return null;const h=t[7];h&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,h&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-a>60*9e4&&(v.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=t[8];let c=s+9;if(r.size<=c)return null;r.size-=c;const d=new Uint8Array(r.size);for(let u=0,f=o.length;u<f;u++){t=o[u];let g=t.byteLength;if(c)if(c>g){c-=g;continue}else t=t.subarray(c),g-=c,c=0;d.set(t,e),e+=g}return i&&(i-=s+3),{data:d,pts:n,dts:a,len:i}}return null}class $o extends Bi{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=ht(e,0);let i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&_i(t)!==void 0&&Or(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Fr(e,i))return v.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return wo(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return kr(e,t,i,this.basePTS,this.frameIndex)}}class Ds{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 Ne=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":[],dac3:[],"ac-3":[],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]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);A.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);A.STTS=A.STSC=A.STCO=n,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 a=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,a,l,a,o),A.DINF=A.box(A.types.dinf,A.box(A.types.dref,s))}static box(e,...t){let i=8,s=t.length;const n=s;for(;s--;)i+=t[s].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),s=0,i=8;s<n;s++)a.set(t[s],i),i+=t[s].byteLength;return a}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 i=Math.floor(t/(Ne+1)),s=Math.floor(t%(Ne+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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return 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,i){return A.box(A.types.moof,A.mfhd(e),A.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trak(e[t]);return A.box.apply(null,[A.types.moov,A.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(A.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=A.trex(e[t]);return A.box.apply(null,[A.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ne+1)),s=Math.floor(t%(Ne+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return A.box(A.types.mvhd,n)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return A.box(A.types.sdtp,i)}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=[],i=[],s,n,a;for(s=0;s<e.sps.length;s++)n=e.sps[s],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));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(i))),l=e.width,h=e.height,c=e.pixelRatio[0],d=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,h>>8&255,h&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([c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&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 audioStsd(e){const t=e.samplerate;return 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 mp4a(e){return A.box(A.types.mp4a,A.audioStsd(e),A.box(A.types.esds,A.esds(e)))}static mp3(e){return A.box(A.types[".mp3"],A.audioStsd(e))}static ac3(e){return A.box(A.types["ac-3"],A.audioStsd(e),A.box(A.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?A.box(A.types.stsd,A.STSD,A.mp3(e)):e.segmentCodec==="ac3"?A.box(A.types.stsd,A.STSD,A.ac3(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,i=e.duration*e.timescale,s=e.width,n=e.height,a=Math.floor(i/(Ne+1)),o=Math.floor(i%(Ne+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,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){const i=A.sdtp(e),s=e.id,n=Math.floor(t/(Ne+1)),a=Math.floor(t%(Ne+1));return A.box(A.types.traf,A.box(A.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),A.box(A.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),A.trun(e,i.length+16+20+8+16+8+8),i)}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 i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n);let o,l,h,c,d,u;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],h=l.duration,c=l.size,d=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return A.box(A.types.trun,a)}static initSegment(e){A.types||A.init();const t=A.moov(e);return Ee(A.FTYP,t)}}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 Nr=9e4;function Hi(r,e,t=1,i=!1){const s=r*e*t;return i?Math.round(s):s}function Go(r,e,t=1,i=!1){return Hi(r,e,1/t,i)}function nt(r,e=!1){return Hi(r,1e3,1/Nr,e)}function Ho(r,e=1){return Hi(r,Nr,1/e)}const Ko=10*1e3,Cs=1024,Vo=1152,Wo=1536;let je=null,ni=null;class It{constructor(e,t,i,s=""){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.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,je===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);je=a?parseInt(a[1]):0}if(ni===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);ni=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}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,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce((s,n)=>{const a=n.pts-s;return a<-4294967296?(t=!0,Te(s,n.pts)):a>0?s:n.pts},e[0].pts);return t&&v.debug("PTS rollover detected"),i}remux(e,t,i,s,n,a,o,l){let h,c,d,u,f,g,m=n,y=n;const T=e.pid>-1,E=t.pid>-1,S=t.samples.length,b=e.samples.length>0,x=o&&S>0||S>1;if((!T||b)&&(!E||x)||this.ISGenerated||o){if(this.ISGenerated){var R,w,P,I;const H=this.videoTrackConfig;H&&(t.width!==H.width||t.height!==H.height||((R=t.pixelRatio)==null?void 0:R[0])!==((w=H.pixelRatio)==null?void 0:w[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((I=H.pixelRatio)==null?void 0:I[1]))&&this.resetInitSegment()}else d=this.generateIS(e,t,n,a);const k=this.isVideoContiguous;let K=-1,_;if(x&&(K=Yo(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,K>0){v.warn(`[mp4-remuxer]: Dropped ${K} out of ${S} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(K),t.dropped+=K,y+=(t.samples[0].pts-H)/t.inputTimeScale,_=y}else K===-1&&(v.warn(`[mp4-remuxer]: No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(b&&x){const H=this.getVideoStartPts(t.samples),B=(Te(e.samples[0].pts,H)-H)/t.inputTimeScale;m+=Math.max(0,B),y+=Math.max(0,-B)}if(b){if(e.samplerate||(v.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,m,this.isAudioContiguous,a,E||x||l===U.AUDIO?y:void 0),x){const H=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(v.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),h=this.remuxVideo(t,y,k,H)}}else x&&(h=this.remuxVideo(t,y,k,0));h&&(h.firstKeyFrame=K,h.independent=K!==-1,h.firstKeyFramePTS=_)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Ur(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Br(s,n,this._initPTS))),{audio:c,video:h,initSegment:d,independent:g,text:u,id3:f}}generateIS(e,t,i,s){const n=e.samples,a=t.samples,o=this.typeSupported,l={},h=this._initPTS;let c=!h||s,d="audio/mp4",u,f,g;if(c&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):A.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(g=e.inputTimeScale,!h||g!==h.timescale?u=f=n[0].pts-Math.round(g*i):c=!1)}if(t.sps&&t.pps&&a.length){if(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}},c)if(g=t.inputTimeScale,!h||g!==h.timescale){const m=this.getVideoStartPts(a),y=Math.round(g*i);f=Math.min(f,Te(a[0].dts,m)-y),u=Math.min(u,m-y)}else c=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c?(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,i,s){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,h=this._initPTS;let c=this.nextAvcDts,d=8,u=this.videoSampleDuration,f,g,m=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,T=!1;if(!i||c===null){const M=t*n,F=a[0].pts-Te(a[0].dts,a[0].pts);je&&c!==null&&Math.abs(M-F-c)<15e3?i=!0:c=M-F}const E=h.baseTime*n/h.timescale;for(let M=0;M<l;M++){const F=a[M];F.pts=Te(F.pts-E,c),F.dts=Te(F.dts-E,c),F.dts<a[M>0?M-1:M].dts&&(T=!0)}T&&a.sort(function(M,F){const q=M.dts-F.dts,W=M.pts-F.pts;return q||W}),f=a[0].dts,g=a[a.length-1].dts;const S=g-f,b=S?Math.round(S/(l-1)):u||e.inputTimeScale/30;if(i){const M=f-c,F=M>b,q=M<-1;if((F||q)&&(F?v.warn(`AVC: ${nt(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):v.warn(`AVC: ${nt(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!q||c>=a[0].pts||je)){f=c;const W=a[0].pts-M;if(F)a[0].dts=f,a[0].pts=W;else for(let z=0;z<a.length&&!(a[z].dts>W);z++)a[z].dts-=M,a[z].pts-=M;v.log(`Video: Initial PTS/DTS adjusted: ${nt(W,!0)}/${nt(f,!0)}, delta: ${nt(M,!0)} ms`)}}f=Math.max(0,f);let x=0,D=0,R=f;for(let M=0;M<l;M++){const F=a[M],q=F.units,W=q.length;let z=0;for(let se=0;se<W;se++)z+=q[se].data.length;D+=z,x+=W,F.length=z,F.dts<R?(F.dts=R,R+=b/4|0||1):R=F.dts,m=Math.min(F.pts,m),y=Math.max(F.pts,y)}g=a[l-1].dts;const w=D+4*x+8;let P;try{P=new Uint8Array(w)}catch(M){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:w,reason:`fail allocating video mdat ${w}`});return}const I=new DataView(P.buffer);I.setUint32(0,w),P.set(A.types.mdat,4);let k=!1,K=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,H=Number.NEGATIVE_INFINITY,G=Number.NEGATIVE_INFINITY;for(let M=0;M<l;M++){const F=a[M],q=F.units;let W=0;for(let ae=0,ce=q.length;ae<ce;ae++){const pe=q[ae],rt=pe.data,Vt=pe.data.byteLength;I.setUint32(d,Vt),d+=4,P.set(rt,d),d+=Vt,W+=4+Vt}let z;if(M<l-1)u=a[M+1].dts-F.dts,z=a[M+1].pts-F.pts;else{const ae=this.config,ce=M>0?F.dts-a[M-1].dts:b;if(z=M>0?F.pts-a[M-1].pts:b,ae.stretchShortVideoTrack&&this.nextAudioPts!==null){const pe=Math.floor(ae.maxBufferHole*n),rt=(s?m+s*n:this.nextAudioPts)-F.pts;rt>pe?(u=rt-ce,u<0?u=ce:k=!0,v.log(`[mp4-remuxer]: It is approximately ${rt/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=ce}else u=ce}const se=Math.round(F.pts-F.dts);K=Math.min(K,u),H=Math.max(H,u),_=Math.min(_,z),G=Math.max(G,z),o.push(new ws(F.key,u,W,se))}if(o.length){if(je){if(je<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(ni&&G-_<H-K&&b/H<.025&&o[0].cts===0){v.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let F=0,q=o.length;F<q;F++){const W=M+o[F].duration,z=M+o[F].cts;if(F<q-1){const se=W+o[F+1].cts;o[F].duration=se-z}else o[F].duration=F?o[F-1].duration:b;o[F].cts=0,M=W}}}u=k||!u?b:u,this.nextAvcDts=c=g+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const Q={data1:A.moof(e.sequenceNumber++,f,re({},e,{samples:o})),data2:P,startPTS:m/n,endPTS:(y+u)/n,startDTS:f/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Q}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Vo;case"ac3":return Wo;default:return Cs}}remuxAudio(e,t,i,s,n){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,h=this.getSamplesPerFrame(e),c=h*l,d=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=n!==void 0;let m=e.samples,y=u?0:8,T=this.nextAudioPts||-1;const E=t*a,S=d.baseTime*a/d.timescale;if(this.isAudioContiguous=i=i||m.length&&T>0&&(s&&Math.abs(E-T)<9e3||Math.abs(Te(m[0].pts-S,E)-T)<20*c),m.forEach(function(B){B.pts=Te(B.pts-S,E)}),!i||T<0){if(m=m.filter(B=>B.pts>=0),!m.length)return;n===0?T=0:s&&!g?T=Math.max(0,E):T=m[0].pts}if(e.segmentCodec==="aac"){const B=this.config.maxAudioFramesDrift;for(let j=0,Q=T;j<m.length;j++){const M=m[j],F=M.pts,q=F-Q,W=Math.abs(1e3*q/a);if(q<=-B*c&&g)j===0&&(v.warn(`Audio frame @ ${(F/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*q/a)} ms.`),this.nextAudioPts=T=Q=F);else if(q>=B*c&&W<Ko&&g){let z=Math.round(q/c);Q=F-z*c,Q<0&&(z--,Q+=c),j===0&&(this.nextAudioPts=T=Q),v.warn(`[mp4-remuxer]: Injecting ${z} audio frame @ ${(Q/a).toFixed(3)}s due to ${Math.round(1e3*q/a)} ms gap.`);for(let se=0;se<z;se++){const ae=Math.max(Q,0);let ce=Ds.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);ce||(v.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ce=M.unit.subarray()),m.splice(j,0,{unit:ce,pts:ae}),Q+=c,j++}}M.pts=Q,Q+=c}}let b=null,x=null,D,R=0,w=m.length;for(;w--;)R+=m[w].unit.byteLength;for(let B=0,j=m.length;B<j;B++){const Q=m[B],M=Q.unit;let F=Q.pts;if(x!==null){const W=f[B-1];W.duration=Math.round((F-x)/l)}else if(i&&e.segmentCodec==="aac"&&(F=T),b=F,R>0){R+=y;try{D=new Uint8Array(R)}catch(W){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:W,bytes:R,reason:`fail allocating audio mdat ${R}`});return}u||(new DataView(D.buffer).setUint32(0,R),D.set(A.types.mdat,4))}else return;D.set(M,y);const q=M.byteLength;y+=q,f.push(new ws(!0,h,q,0)),x=F}const P=f.length;if(!P)return;const I=f[f.length-1];this.nextAudioPts=T=x+l*I.duration;const k=u?new Uint8Array(0):A.moof(e.sequenceNumber++,b/l,re({},e,{samples:f}));e.samples=[];const K=b/a,_=T/a,G={data1:k,data2:D,startPTS:K,endPTS:_,startDTS:K,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:P};return this.isAudioContiguous=!0,G}remuxEmptyAudio(e,t,i,s){const n=e.inputTimeScale,a=e.samplerate?e.samplerate:n,o=n/a,l=this.nextAudioPts,h=this._initDTS,c=h.baseTime*9e4/h.timescale,d=(l!==null?l:s.startDTS*n)+c,u=s.endDTS*n+c,f=o*Cs,g=Math.ceil((u-d)/f),m=Ds.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(v.warn("[mp4-remuxer]: remux empty Audio"),!m){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 T=0;T<g;T++){const E=d+T*f;y.push({unit:m,pts:E,dts:E})}return e.samples=y,this.remuxAudio(e,t,i,!1)}}function Te(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function Yo(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Ur(r,e,t,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let o=0;o<s;o++){const l=r.samples[o];l.pts=Te(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Te(l.dts-i.baseTime*n/i.timescale,e*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function Br(r,e,t){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let a=0;a<i;a++){const o=r.samples[a];o.pts=Te(o.pts-t.baseTime*s/t.timescale,e*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class ws{constructor(e,t,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class jo{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,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(ea(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=cr(e);s.audio&&(t=ks(s.audio,X.AUDIO)),s.video&&(i=ks(s.video,X.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:v.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,s,n,a){var o,l;let{initPTS:h,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};O(c)||(c=this.lastEndTime=n||0);const u=t.samples;if(!(u!=null&&u.length))return d;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."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=ia(u,g),y=ta(g,u),T=y===null?n:y;(qo(h,T,n,m)||f.timescale!==h.timescale&&a)&&(f.initPTS=T-n,h&&h.timescale===1&&v.warn(`Adjusting initPTS by ${f.initPTS-h.baseTime}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});const E=e?T-h.baseTime/h.timescale:c,S=E+m;ra(g,u,h.baseTime/h.timescale),m>0?this.lastEndTime=S:(v.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!g.audio,x=!!g.video;let D="";b&&(D+="audio"),x&&(D+="video");const R={data1:u,startPTS:E,startDTS:E,endPTS:S,endDTS:S,type:D,hasAudio:b,hasVideo:x,nb:1,dropped:0};return d.audio=R.type==="audio"?R:void 0,d.video=R.type!=="audio"?R:void 0,d.initSegment=f,d.id3=Ur(i,n,h,h),s.samples.length&&(d.text=Br(s,n,h)),d}}function qo(r,e,t,i){if(r===null)return!0;const s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>s}function ks(r,e){const t=r==null?void 0:r.codec;if(t&&t.length>4)return t;if(e===X.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return Ot(t,!1);const i="mp4a.40.5";return v.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return v.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let Me;try{Me=self.performance.now.bind(self.performance)}catch{v.debug("Unable to use Performance API on this environment"),Me=Ze==null?void 0:Ze.Date.now}const Dt=[{demux:_o,remux:jo},{demux:Ue,remux:It},{demux:ko,remux:It},{demux:$o,remux:It}];Dt.splice(2,0,{demux:Fo,remux:It});class Ps{constructor(e,t,i,s,n){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=i,this.vendor=s,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const n=i.transmuxing;n.executeStart=Me();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:h,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:m,videoCodec:y,defaultInitPts:T,duration:E,initSegmentData:S}=l,b=zo(a,t);if(b&&b.method==="AES-128"){const w=this.getDecrypter();if(w.isSync()){let P=w.softwareDecrypt(a,b.key.buffer,b.iv.buffer);if(i.part>-1&&(P=w.flush()),!P)return n.executeEnd=Me(),ai(i);a=new Uint8Array(P)}else return this.decryptionPromise=w.webCryptoDecrypt(a,b.key.buffer,b.iv.buffer).then(P=>{const I=this.push(P,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const x=this.needsProbing(c,d);if(x){const w=this.configureTransmuxer(a);if(w)return v.warn(`[transmuxer] ${w.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:w,reason:w.message}),n.executeEnd=Me(),ai(i)}(c||d||g||x)&&this.resetInitSegment(S,m,y,E,t),(c||g||x)&&this.resetInitialTimestamp(T),h||this.resetContiguity();const D=this.transmux(a,b,f,u,i),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,n.executeEnd=Me(),D}flush(e){const t=e.transmuxing;t.executeStart=Me();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;if(i){const d=i.flush();d&&a.push(this.push(d,null,e))}const{demuxer:l,remuxer:h}=this;if(!l||!h)return t.executeEnd=Me(),[ai(e)];const c=l.flush(o);return Ct(c)?c.then(d=>(this.flushRemux(a,d,e),a)):(this.flushRemux(a,c,e),a)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:h}=this.currentTransmuxState;v.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const c=this.remuxer.remux(s,n,a,o,h,l,!0,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Me()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,n):a=this.transmuxUnencrypted(e,i,s,n),a}transmuxUnencrypted(e,t,i,s){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s,vendor:n}=this;let a;for(let u=0,f=Dt.length;u<f;u++){var o;if((o=Dt[u].demux)!=null&&o.probe(e)){a=Dt[u];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,h=this.remuxer,c=a.remux,d=a.demux;(!h||!(h instanceof c))&&(this.remuxer=new c(i,t,s,n)),(!l||!(l instanceof d))&&(this.demuxer=new d(i,t,s),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 Ni(this.config)),e}}function zo(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ai=r=>({remuxResult:{},chunkMeta:r});function Ct(r){return"then"in r&&r.then instanceof Function}class Xo{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class Qo{constructor(e,t,i,s,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}}var $r={exports:{}};(function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,d||l,u),g=t?t+h:h;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var h=[],c,d;if(this._eventsCount===0)return h;for(d in c=this._events)e.call(c,d)&&h.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},o.prototype.listeners=function(h){var c=t?t+h:h,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},o.prototype.listenerCount=function(h){var c=t?t+h:h,d=this._events[c];return d?d.fn?1:d.length:0},o.prototype.emit=function(h,c,d,u,f,g){var m=t?t+h:h;if(!this._events[m])return!1;var y=this._events[m],T=arguments.length,E,S;if(y.fn){switch(y.once&&this.removeListener(h,y.fn,void 0,!0),T){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,d),!0;case 4:return y.fn.call(y.context,c,d,u),!0;case 5:return y.fn.call(y.context,c,d,u,f),!0;case 6:return y.fn.call(y.context,c,d,u,f,g),!0}for(S=1,E=new Array(T-1);S<T;S++)E[S-1]=arguments[S];y.fn.apply(y.context,E)}else{var b=y.length,x;for(S=0;S<b;S++)switch(y[S].once&&this.removeListener(h,y[S].fn,void 0,!0),T){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,c);break;case 3:y[S].fn.call(y[S].context,c,d);break;case 4:y[S].fn.call(y[S].context,c,d,u);break;default:if(!E)for(x=1,E=new Array(T-1);x<T;x++)E[x-1]=arguments[x];y[S].fn.apply(y[S].context,E)}}return!0},o.prototype.on=function(h,c,d){return n(this,h,c,d,!1)},o.prototype.once=function(h,c,d){return n(this,h,c,d,!0)},o.prototype.removeListener=function(h,c,d,u){var f=t?t+h:h;if(!this._events[f])return this;if(!c)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&a(this,f);else{for(var m=0,y=[],T=g.length;m<T;m++)(g[m].fn!==c||u&&!g[m].once||d&&g[m].context!==d)&&y.push(g[m]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(h){var c;return h?(c=t?t+h:h,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o})($r);var Jo=$r.exports,Ki=xn(Jo);class Gr{constructor(e,t,i,s){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 n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(c,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,c===p.ERROR&&(this.error=d.error),this.hls.trigger(c,d)};this.observer=new Ki,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=st(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')},h=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||yo())){try{n.workerPath?(v.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Eo(n.workerPath)):(v.log(`injecting Web Worker for "${t}"`),this.workerContext=To()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:d}=this.workerContext;d.addEventListener("message",this.onwmsg),d.onerror=u=>{const f=new Error(`${u.message} (${u.filename}:${u.lineno})`);n.enableWorker=!1,v.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},d.postMessage({cmd:"init",typeSupported:l,vendor:h,id:t,config:JSON.stringify(n)})}catch(d){v.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.resetWorker(),this.error=null,this.transmuxer=new Ps(this.observer,l,n,h,t)}return}this.transmuxer=new Ps(this.observer,l,n,h,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,i,s,n,a,o,l,h,c){var d,u;h.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=a?a.start:n.start,m=n.decryptdata,y=this.frag,T=!(y&&n.cc===y.cc),E=!(y&&h.level===y.level),S=y?h.sn-y.sn:-1,b=this.part?h.part-this.part.index:-1,x=S===0&&h.id>1&&h.id===(y==null?void 0:y.stats.chunkCount),D=!E&&(S===1||S===0&&(b===1||x&&b<=0)),R=self.performance.now();(E||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(b||!D)&&(a.stats.parsing.start=R);const w=!(y&&((d=n.initSegment)==null?void 0:d.url)===((u=y.initSegment)==null?void 0:u.url)),P=new Qo(T,D,l,E,g,w);if(!D||T||w){v.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${h.sn} p: ${h.part} level: ${h.level} id: ${h.id} 9 discontinuity: ${T} 10 trackSwitch: ${E} 11 contiguous: ${D} 12 accurateTimeOffset: ${l} 13 timeOffset: ${g} 14 initSegmentChange: ${w}`);const I=new Xo(i,s,t,o,c);this.configureTransmuxer(I)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:m,chunkMeta:h,state:P},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,m,h,P);Ct(I)?(f.async=!0,I.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,h,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}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 i=t.flush(e);Ct(i)||t.async?(Ct(i)||(i=Promise.resolve(i)),i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var s;const n=(s=this.workerContext)==null?void 0:s.objectURL;n&&self.URL.revokeObjectURL(n);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,i.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)}}function Hr(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!tt(r[t].attrs,e[t].attrs))return!1;return!0}function tt(r,e,t){const i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>r[s]!==e[s])}function Li(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}const _s=100;class Zo extends Ui{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",U.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.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){if(i==="main"){const a=t.cc;this.initPTS[t.cc]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${s}`),this.videoTrackCC=a,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(_s),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:i,trackId:s}=this,n=i==null||(e=i[s])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),s=this.retryDate;if(!s||i>=s||(t=this.media)!=null&&t.seeking){const{levels:n,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[a])||null),this.state=C.IDLE}break}case C.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:n,cache:a,complete:o}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=C.FRAG_LOADING;const l=a.flush(),h={frag:s,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(h),o&&super._handleFragmentLoadComplete(h)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),h=J.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);vi(h.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${h.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:i,trackId:s}=this,n=e.config;if(!i&&(this.startFragRequested||!n.startFragPrefetch)||!(t!=null&&t[s]))return;const a=t[s],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||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,X.AUDIO,U.AUDIO));const h=this.getFwdBufferInfo(l,U.AUDIO);if(h===null)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(h,o)){e.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,U.MAIN),f=h.len,g=this.getMaxBufferLength(u==null?void 0:u.len),m=o.fragments,y=m[0].start;let T=this.flushing?this.getLoadPosition():h.end;if(d&&i){const x=this.getLoadPosition();c&&!tt(d.attrs,c.attrs)&&(T=x),o.PTSKnown&&x<y&&(h.end>y||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=y+.05)}if(f>=g&&!d&&T<m[m.length-1].start)return;let E=this.getNextFragment(T,o),S=!1;if(E&&this.isLoopLoading(E,T)&&(S=!!E.gap,E=this.getNextFragmentLoopLoading(E,o,h,U.MAIN,g)),!E){this.bufferFlushed=!0;return}const b=u&&E.start>u.end+o.targetduration;if(b||!(u!=null&&u.len)&&h.len){const x=this.getAppendedFrag(E.start,U.MAIN);if(x===null||(S||(S=!!x.gap||!!b&&u.len===0),b&&!S||S&&h.nextStart&&h.nextStart<x.end))return}this.loadFragment(E,a,T)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new et(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(_s):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=C.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=C.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!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(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:s}=this,{details:n,id:a}=t;if(!s){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const o=s[a];let l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);const c=this.mainDetails;if(n.deltaUpdateFailed||!c)return;if(!o.details&&n.hasProgramDateTime&&c.hasProgramDateTime)$t(n,c),l=n.fragments[0].start;else{var h;l=this.alignPlaylists(n,o.details,(h=this.levelLastLoaded)==null?void 0:h.details)}}o.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const h=l[o];if(!h){this.warn("Audio track is undefined on fragment load progress");return}const c=h.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const d=a.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Gr(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const y=s?s.index:-1,T=y!==-1,E=new Mi(i.level,i.sn,i.stats.chunkCount,n.byteLength,y,T);u.push(n,g,d,"",i,s,c.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Rr,complete:!1};m.push(new Uint8Array(n)),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 i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==U.AUDIO){if(!this.loadedmetadata&&i.type===U.MAIN){const n=this.videoBuffer||this.media;n&&J.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,he({},n)))}this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Y.AUDIO_TRACK&&(this.state=C.IDLE);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===L.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==X.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==X.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,U.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:c}=o,{details:d}=c,{audio:u,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const y=l.initSegment||l;this._bufferInitSegment(c,m.tracks,y,a),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:m.tracks})}if(u){const{startPTS:y,endPTS:T,startDTS:E,endDTS:S}=u;h&&(h.elementaryStreams[X.AUDIO]={startPTS:y,endPTS:T,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(X.AUDIO,y,T,E,S),this.bufferFragmentData(u,l,h,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=re({id:i,frag:l,details:d},g);s.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=re({id:i,frag:l,details:d},f);s.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,i,s){if(this.state!==C.PARSING)return;t.video&&delete t.video;const n=t.audio;if(!n)return;n.id="audio";const a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);const o=n.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||s===le.NOT_LOADED||s===le.PARTIAL){var n;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.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;const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&$t(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,s=i==null?void 0:i.attrs,n=e.attrs;t&&s&&(s.CHANNELS!==n.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,he({},e))}}class el extends Oi{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!n&&l){const u=Ce(l,o,Ve);if(u>-1)n=o[u];else{const f=Ce(l,this.tracks);n=this.tracks[f]}}let h=this.findTrackId(n);h===-1&&n&&(h=this.findTrackId(null));const c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,c);const d=this.trackId;if(h!==-1&&d===-1)this.setAudioTrack(h);else if(o.length&&d===-1){var a;const u=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(u.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===Y.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Qe(e,s,Ve))return s;const n=Ce(e,this.tracksInGroup,Ve);if(n>-1){const a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Za(e,t.levels,i,a,Ve);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Ce(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],n=s.details&&!s.details.live;if(e===this.trackId&&s===i&&n||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,he({},s)),n))return;const a=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||Qe(e,s,Ve)))return i}if(e){const{name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let h=0;h<t.length;h++){const c=t[h];if(Qe({name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l},c,Ve))return h}for(let h=0;h<t.length;h++){const c=t[h];if(tt(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return h}for(let h=0;h<t.length;h++){const c=t[h];if(tt(e.attrs,c.attrs,["LANGUAGE"]))return h}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${s}`),this.clearTimer(),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}}const Fs=500;class tl extends Ui{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=C.IDLE,this.setInterval(Fs),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:i,success:s}=t;if(this.fragPrevious=i,this.state=C.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let h=0;h<n.length;h++)if(o>=n[h].start&&o<=n[h].end){a=n[h];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,U.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===U.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const i=t.frag;(i==null?void 0:i.type)===U.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Hr(this.levels,t)){this.levels=t.map(i=>new et(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new et(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.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(Fs)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=n[s];if(o>=n.length||o!==s||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(a.live||(i=l.details)!=null&&i.live){const d=this.mainDetails;if(a.deltaUpdateFailed||!d)return;const u=d.fragments[0];if(!l.details)a.hasProgramDateTime&&d.hasProgramDateTime?($t(a,d),h=a.fragments[0].start):u&&(h=u.start,xi(a,h));else{var c;h=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),h===0&&u&&(h=u.start,xi(a,h))}}l.details=a,this.levelLastLoaded=l,!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,h),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(Bt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&s.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(o=>{throw n.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();n.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,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,i=t==null?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:s}=this,n=this.getLoadPosition(),a=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:l}=a,h=this.getFwdBufferInfo(this.media,U.MAIN),c=i.details,d=this.getMaxBufferLength(h==null?void 0:h.len)+c.levelTargetDuration;if(l>d)return;const u=c.fragments,f=u.length,g=c.edge;let m=null;const y=this.fragPrevious;if(o<g){const T=s.maxFragLookUpTolerance,E=o>g-T?0:T;m=Bt(y,u,Math.max(u[0].start,o),E),!m&&y&&y.start<u[0].start&&(m=u[0])}else m=u[f-1];if(!m)return;if(m=this.mapToInitFragWhenRequired(m),m.sn!=="initSegment"){const T=m.sn-c.startSN,E=u[T-1];E&&E.cc===m.cc&&this.fragmentTracker.getState(E)===le.NOT_LOADED&&(m=E)}this.fragmentTracker.getState(m)===le.NOT_LOADED&&this.loadFragment(m,i,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new il(this.tracksBuffered[this.currentTrackId]||[])}}class il{constructor(e){this.buffered=void 0;const t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class sl extends Oi{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Rt(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Rt(this.media.textTracks).forEach(t=>{Xe(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let n=this.currentTrack;if(!i||(s==null?void 0:s.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(s==null?void 0:s.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(c=>!i||i.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),a.forEach((c,d)=>{c.id=d});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;const c=Ce(o,a);if(c>-1)n=a[c];else{const d=Ce(o,this.tracks);n=this.tracks[d]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const h={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,h),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||Qe(n,e)))return s}if(e){for(let s=0;s<t.length;s++){const n=t[s];if(tt(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const n=t[s];if(tt(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(Li(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Y.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&Qe(e,i))return i;const s=Ce(e,this.tracksInGroup);if(s>-1){const n=this.tracksInGroup[s];return this.setSubtitleTrack(s),n}else{if(i)return null;{const n=Ce(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Rt(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(n=>Li(i,n))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==s&&(n.mode="disabled")}),s){const n=this.subtitleDisplay?"showing":"hidden";s.mode!==n&&(s.mode=n)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!O(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const n=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:l,type:h,url:c}=s;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:c});const d=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(d)}}class rl{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(n=>{t=n}),s={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(s){v.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${s}`),i.onError(s);const n=this.buffers[e];n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Os=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class nl{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.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:s}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:s})),s&&s.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&v.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=e.config.preferManagedMediaSource,this.log=v.log.bind(v,t),this.warn=v.warn.bind(v,t),this.error=v.error.bind(v,t),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,this.hls=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new rl(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,s=st(this.appendSource);if(i&&s){var n;const a=this.mediaSource=new s;this.log(`created media source: ${(n=a.constructor)==null?void 0:n.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming);const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Ms(i),al(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){this.warn(`onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Ms(e),e.load()):this.warn("media|source.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(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(s){this.warn(`onBufferReset ${e}`,s)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,s=Object.keys(t);if(s.forEach(a=>{if(i){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:h,codec:c,levelCodec:d,container:u,metadata:f}=t[a],g=rs(l.codec,l.levelCodec),m=g==null?void 0:g.replace(Os,"$1");let y=rs(c,d);const T=(o=y)==null?void 0:o.replace(Os,"$1");if(y&&m!==T){a.slice(0,5)==="audio"&&(y=Ot(y,this.hls.config.preferManagedMediaSource));const E=`${u};codecs=${y}`;this.appendChangeType(a,E),this.log(`switching codec ${g} to ${y}`),this.tracks[a]={buffer:l.buffer,codec:c,container:u,levelCodec:d,metadata:f,id:h}}}}else this.pendingTracks[a]=t[a]}),i)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,s={execute:()=>{const n=this.sourceBuffer[e];n&&(this.log(`changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};i.append(s,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:s,tracks:n}=this,{data:a,type:o,frag:l,part:h,chunkMeta:c}=t,d=c.buffering[o],u=self.performance.now();d.start=u;const f=l.stats.buffering,g=h?h.stats.buffering:null;f.start===0&&(f.start=u),g&&g.start===0&&(g.start=u);const m=n.audio;let y=!1;o==="audio"&&(m==null?void 0:m.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const T=l.start,E={execute:()=>{if(d.executeStart=self.performance.now(),y){const S=this.sourceBuffer[o];if(S){const b=T-S.timestampOffset;Math.abs(b)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${T} (delta: ${b}) sn: ${l.sn})`),S.timestampOffset=T)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();d.executeEnd=d.end=S,f.first===0&&(f.first=S),g&&g.first===0&&(g.first=S);const{sourceBuffer:b}=this,x={};for(const D in b)x[D]=J.getBuffered(b[D]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:o,frag:l,part:h,chunkMeta:c,parent:l.type,timeRanges:x})},onError:S=>{const b={type:$.MEDIA_ERROR,parent:l.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:h,chunkMeta:c,error:S,err:S,fatal:!1};if(S.code===DOMException.QUOTA_EXCEEDED_ERR)b.details=L.BUFFER_FULL_ERROR;else{const x=++this.appendErrors[o];b.details=L.BUFFER_APPEND_ERROR,this.warn(`Failed ${x}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),x>=i.config.appendErrorMaxRetry&&(b.fatal=!0)}i.trigger(p.ERROR,b)}};s.append(E,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:i}=this,s=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:n})},onError:a=>{this.warn(`Failed to remove from ${n} SourceBuffer`,a)}});t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(s(n),n)})}onFragParsed(e,t){const{frag:i,part:s}=t,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[X.AUDIOVIDEO]?n.push("audiovideo"):(a[X.AUDIO]&&n.push("audio"),a[X.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const h=s?s.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:s,stats:h,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((s,n)=>{const a=this.sourceBuffer[n];return a&&(!t.type||t.type===n)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${n} sourceBuffer now EOS`))),s&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const a=this.sourceBuffer[n];a&&(a.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const n=e.config,a=i.currentTime,o=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(O(l)&&l>0){const h=Math.max(l,o),c=Math.floor(a/o)*o-h;this.flushBackBuffer(a,o,c)}if(O(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const h=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),c=Math.max(h,o),d=Math.floor(a/o)*o+c;this.flushFrontBuffer(a,o,d)}}flushBackBuffer(e,t,i){const{details:s,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(o=>{const l=n[o];if(l){const h=J.getBuffered(l);if(h.length>0&&i>h.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i}),s!=null&&s.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&h.end(h.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(a=>{const o=s[a];if(o){const l=J.getBuffered(o),h=l.length;if(h<2)return;const c=l.start(h-1),d=l.end(h-1);if(i>c||e>=c&&e<=d)return;if(o.ended&&e-d<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:s}=this,n=e.fragments[0].start+e.totalduration,a=i.duration,o=O(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(e)):(n>o&&n>a||!O(a))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),s.duration=n)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const n=Math.max(0,i[0].start),a=Math.max(n,n+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${n}-${a}.`),t.setLiveSeekableRange(n,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&(!e||s===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=n.levelCodec||n.codec;a&&s.slice(0,5)==="audio"&&(a=Ot(a,this.hls.config.preferManagedMediaSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const l=t[s]=i.addSourceBuffer(o),h=s;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.addBufferListener(h,"bufferedchange",(c,d)=>{const u=d.removedRanges;u!=null&&u.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:s})}),this.tracks[s]={buffer:l,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){this.error(`error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var e;const t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t==null?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!s||!n||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const h=O(s.duration)?s.duration:1/0,c=O(n.duration)?n.duration:1/0,d=Math.max(0,t),u=Math.min(i,h,c);u>d&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),l.remove(d,u)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,s=t.map(n=>i.appendBlocker(n));Promise.all(s).then(()=>{e(),t.forEach(n=>{const a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const s=this.sourceBuffer[e];if(!s)return;const n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),s.addEventListener(t,n)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function Ms(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function al(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}const Ns={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},Kr=function(e){let t=e;return Ns.hasOwnProperty(e)&&(t=Ns[e]),String.fromCharCode(t)},xe=15,Fe=100,ol={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ll={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hl={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},cl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},dl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class ul{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;v.log(`${this.time} [${e}] ${i}`)}}}const Be=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class Vr{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return 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 fl{constructor(){this.uchar=" ",this.penState=new Vr}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 gl{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Vr,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Fe;t++)this.chars.push(new fl);this.logger=e}equals(e){for(let t=0;t<Fe;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Fe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Fe;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>Fe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Fe)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Kr(e);if(this.pos>=Fe){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<Fe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Fe;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class oi{constructor(e){this.rows=[],this.currRow=xe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<xe;t++)this.rows.push(new gl(e));this.logger=e}reset(){for(let e=0;e<xe;e++)this.rows[e].clear();this.currRow=xe-1}equals(e){let t=!0;for(let i=0;i<xe;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<xe;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<xe;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<xe;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let h=0;h<this.nrRollUpRows;h++)this.rows[t-this.nrRollUpRows+h+1].copy(a.rows[n+h])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+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 i="",s=-1;for(let n=0;n<xe;n++){const a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(` 15`)),i}getTextAndFormat(){return this.rows}}class Us{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new oi(i),this.nonDisplayedMemory=new oi(i),this.lastOutputScreen=new oi(i),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}
15ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+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 Bs{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Gs(),this.logger=void 0;const s=this.logger=new ul;this.channels=[null,new Us(e,t,s),new Us(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,s,n,a=!1;this.logger.time=e;for(let o=0;o<t.length;o+=2)if(s=t[o]&127,n=t[o+1]&127,!(s===0&&n===0)){if(this.logger.log(3,"["+Be([t[o],t[o+1]])+"] -> ("+Be([s,n])+")"),i=this.parseCmd(s,n),i||(i=this.parseMidrow(s,n)),i||(i=this.parsePAC(s,n)),i||(i=this.parseBackgroundAttributes(s,n)),!i&&(a=this.parseChars(s,n),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,"Couldn't parse cleaned data "+Be([s,n])+" orig: "+Be([t[o],t[o+1]]))}}parseCmd(e,t){const{cmdHistory:i}=this,s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;if($s(e,t,i))return qe(null,null,i),this.logger.log(3,"Repeated command ("+Be([e,t])+") is dropped"),!0;const a=e===20||e===21||e===23?1:2,o=this.channels[a];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),qe(e,t,i),this.currentChannel=a,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,"MIDROW ("+Be([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const s=this.cmdHistory,n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(e===16||e===24)&&t>=64&&t<=95;if(!(n||a))return!1;if($s(e,t,s))return qe(null,null,s),!0;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?ol[e]:hl[e]:i=o===1?ll[e]:cl[e];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(i,t)),qe(e,t,s),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,"Special char '"+Kr(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);if(s){const a=Be(s);this.logger.log(3,"Char codes = "+a.join(",")),qe(e,t,this.cmdHistory)}return s}
vendor: 52,500 bytes, lines 15-26
15parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n;const a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=dl[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),qe(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=Gs()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function qe(r,e,t){t.a=r,t.b=e}function $s(r,e,t){return t.a===r&&t.b===e}function Gs(){return{a:null,b:null}}class St{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Vi=function(){if(Ze!=null&&Ze.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function i(o){return t(r,o)}function s(o){return t(e,o)}function n(o,...l){let h=1;for(;h<arguments.length;h++){const c=arguments[h];for(const d in c)o[d]=c[d]}return o}function a(o,l,h){const c=this,d={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,g=o,m=l,y=h,T=null,E="",S=!0,b="auto",x="start",D=50,R="middle",w=50,P="middle";Object.defineProperty(c,"id",n({},d,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(c,"pauseOnExit",n({},d,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(c,"startTime",n({},d,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},d,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},d,{get:function(){return y},set:function(I){y=""+I,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},d,{get:function(){return T},set:function(I){T=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},d,{get:function(){return E},set:function(I){const k=i(I);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},d,{get:function(){return S},set:function(I){S=!!I,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},d,{get:function(){return b},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},d,{get:function(){return x},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");x=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},d,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},d,{get:function(){return R},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");R=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},d,{get:function(){return w},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");w=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},d,{get:function(){return P},set:function(I){const k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");P=k,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class ml{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Wr(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const t=r.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 pl{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function Yr(r,e,t,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const Ri=new Vi(0,0,""),xt=Ri.align==="middle"?"middle":"center";function yl(r,e,t){const i=r;function s(){const o=Wr(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const h=new pl;Yr(o,function(u,f){let g;switch(u){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){h.set(u,t[m].region);break}break;case"vertical":h.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),h.integer(u,g[0]),h.percent(u,g[0])&&h.set("snapToLines",!1),h.alt(u,g[0],["auto"]),g.length===2&&h.alt("lineAlign",g[1],["start",xt,"end"]);break;case"position":g=f.split(","),h.percent(u,g[0]),g.length===2&&h.alt("positionAlign",g[1],["start",xt,"end","line-left","line-right","auto"]);break;case"size":h.percent(u,f);break;case"align":h.alt(u,f,["start",xt,"end","left","right"]);break}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let c=h.get("line","auto");c==="auto"&&Ri.line===-1&&(c=-1),l.line=c,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",xt);let d=h.get("position","auto");d==="auto"&&Ri.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function jr(r){return r.replace(/<br(?: \/)?>/gi,` 16`)}class Tl{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ml,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=jr(n);a<n.length&&n[a]!=="\r"&&n[a]!==` 17`;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===` 18`&&++a,t.buffer=n.slice(a),o}function s(n){Yr(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new Vi(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{yl(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` 19`),t.cue.text+=n}continue;case"BADCUE":n||(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+=` 20 21`,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 El=/\r\n|\n\r|\n|\r/g,li=function(e,t,i=0){return e.slice(i,i+t.length)===t},Sl=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!O(t)||!O(i)||!O(s)||!O(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t},hi=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function Wi(r,e,t){return hi(r.toString())+hi(e.toString())+hi(t)}const xl=function(e,t,i){let s=e[t],n=e[s.prevCC];if(!n||!n.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=s.start-n.start,s.new=!1,s=n,n=e[s.prevCC]}e.presentationOffset=i};function vl(r,e,t,i,s,n,a){const o=new Tl,l=we(new Uint8Array(r)).trim().replace(El,` 22`).split(` 23`),h=[],c=e?Ho(e.baseTime,e.timescale):0;let d="00:00.000",u=0,f=0,g,m=!0;o.oncue=function(y){const T=t[i];let E=t.ccOffset;const S=(u-c)/9e4;if(T!=null&&T.new&&(f!==void 0?E=t.ccOffset=T.start:xl(t,i,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}E=S-t.presentationOffset}const b=y.endTime-y.startTime,x=Te((y.startTime+E-f)*9e4,s*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+b,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=Wi(y.startTime,y.endTime,D)),y.endTime>0&&h.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}n(h)},l.forEach(y=>{if(m)if(li(y,"X-TIMESTAMP-MAP=")){m=!1,y.slice(16).split(",").forEach(T=>{li(T,"LOCAL:")?d=T.slice(6):li(T,"MPEGTS:")&&(u=parseInt(T.slice(7)))});try{f=Sl(d)/1e3}catch(T){g=T}return}else y===""&&(m=!1);o.parse(y+` 24`)}),o.flush()}const ci="stpp.ttml.im1t",qr=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Al={left:"start",center:"center",right:"end",start:"start",end:"end"};function Hs(r,e,t,i){const s=V(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>we(o)),a=Go(e.baseTime,1,e.timescale);try{n.forEach(o=>t(Ll(o,a)))}catch(o){i(o)}}function Ll(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((d,u)=>(d[u]=s.getAttribute(`ttp:${u}`)||n[u],d),{}),o=s.getAttribute("xml:space")!=="preserve",l=Ks(di(s,"styling","style")),h=Ks(di(s,"layout","region")),c=di(s,"body","[begin]");return[].map.call(c,d=>{const u=Xr(d,o);if(!u||!d.hasAttribute("begin"))return null;const f=fi(d.getAttribute("begin"),a),g=fi(d.getAttribute("dur"),a);let m=fi(d.getAttribute("end"),a);if(f===null)throw Vs(d);if(m===null){if(g===null)throw Vs(d);m=f+g}const y=new Vi(f-e,m-e,u);y.id=Wi(y.startTime,y.endTime,y.text);const T=h[d.getAttribute("region")],E=l[d.getAttribute("style")],S=Rl(T,E,l),{textAlign:b}=S;if(b){const x=Al[b];x&&(y.lineAlign=x),y.align=b}return re(y,S),y}).filter(d=>d!==null)}function di(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Ks(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Xr(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+` 25`:(n=i.childNodes)!=null&&n.length?Xr(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Rl(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{const h=ui(e,i,l)||ui(r,i,l)||ui(s,i,l);return h&&(o[l]=h),o},{})}function ui(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Vs(r){return new Error(`Could not parse ttml timestamp ${r}`)}function fi(r,e){if(!r)return null;let t=Wr(r);return t===null&&(qr.test(r)?t=bl(r,e):zr.test(r)&&(t=Il(r,e))),t}function bl(r,e){const t=qr.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Il(r,e){const t=zr.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class Dl{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ys(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new St(this,"textTrack1"),t=new St(this,"textTrack2"),i=new St(this,"textTrack3"),s=new St(this,"textTrack4");this.cea608Parser1=new Bs(1,e,t),this.cea608Parser2=new Bs(3,i,s)}}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){const l=n[o],h=Cl(l[0],l[1],t,i);if(h>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,h/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const n=i.textTracks[s];if(Ws(n,{name:e,lang:t,attrs:{}}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,Xe(i[e]),pr(i[e],s);else{const l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Xe(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ys(),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 i=0;i<t.length;i++)Xe(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===ci);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Hr(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Rt(a.textTracks):null;if(this.tracks.forEach((l,h)=>{let c;if(o){let d=null;for(let u=0;u<o.length;u++)if(o[u]&&Ws(o[u],l)){d=o[u],o[u]=null;break}d&&(c=d)}if(c)Xe(c);else{const d=Qr(l);c=this.createTextTrack(d,l.name,l.lang),c&&(c.mode="disabled")}c&&this.textTracks.push(c)}),o!=null&&o.length){const l=o.filter(h=>h!==null).map(h=>h.label);l.length&&v.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s,lastCc:n,lastSn:a,lastPartIndex:o}=this;if(!(!this.enabled||!i||!s)&&t.frag.type===U.MAIN){var l,h;const{cc:c,sn:d}=t.frag,u=(l=t==null||(h=t.part)==null?void 0:h.index)!=null?l:-1;d===a+1||d===a&&u===o+1||c===n||(i.reset(),s.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===U.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===ci?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Hs(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{v.log(`Failed to parse IMSC1: ${s}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const l=this.hls,h=(t=i.initSegment)!=null&&t.data?Ee(i.initSegment.data,new Uint8Array(s)):s;vl(h,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{const d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,s),v.log(`Failed to parse VTT cue: ${c}`),!(d&&o>i.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Hs(t,this.initPTS[e.cc],()=>{i.textCodec=ci,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>yr(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===U.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!i||!s)return;const{frag:n,samples:a}=t;if(!(n.type===U.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const h=this.extractCea608Data(l);i.addData(a[o].pts,h[0]),s.addData(a[o].pts,h[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Ti(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Ti(o[l],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){const c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l))}}return t}}function Qr(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function Ws(r,e){return!!r&&r.kind===Qr(e)&&Li(e,r)}function Cl(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Ys(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Yi{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&O(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&v.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.clientRect=null,Yi.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}}class wl{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,h=this.hls;if(h.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>h.config.fpsDroppedMonitoringThreshold*o){let c=h.currentLevel;v.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=c)&&(c=c-1,h.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:h.currentLevel}),h.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const vt="[eme]";class Je{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=Je.CDMCleanupPromise?[Je.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=v.debug.bind(v,vt),this.log=v.log.bind(v,vt),this.warn=v.warn.bind(v,vt),this.error=v.error.bind(v,vt),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(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=t[e];if(s)return s.licenseUrl;if(e===te.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=h=>{const c=h.shift();this.getMediaKeysPromise(c,s,n).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{h.length?l(h):d instanceof ye?o(d):o(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return sr===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){const s=$n(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(e,s);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),h.then(d=>d?this.setMediaKeysServerCertificate(c,e,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${be.hexDump(e.keyId||[])}`);const s=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,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 be.hexDump(e.keyId)}updateKeySession(e,t){var i;const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${be.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])} 26 } (data length: ${t&&t.byteLength})`),s.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const s=zt(this.config),n=e.map(Qi).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=Ji(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof ye?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const s=Qi(e.keyFormat),n=s?[s]:zt(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=zt(this.config)),e.length===0)throw new ye({type:$.KEY_SYSTEM_ERROR,details:L.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:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let s,n;if(t==="sinf"&&this.config.drmSystems[te.FAIRPLAY]){const c=ne(new Uint8Array(i));try{const d=ki(JSON.parse(c).sinf),u=dr(new Uint8Array(d));if(!u)return;s=u.subarray(8,24),n=te.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const c=da(i);if(c===null)return;c.version===0&&c.systemId===ir.WIDEVINE&&c.data&&(s=c.data.subarray(8,24)),n=Bn(c.systemId)}if(!n||!s)return;const a=be.hexDump(s),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let h=o[a];for(let c=0;c<l.length;c++){const d=l[c],u=d.decryptdata;if(u.pssh||!u.keyId)continue;const f=be.hexDump(u.keyId);if(a===f||u.uri.replace(/-/g,"").indexOf(a)!==-1){h=o[f],delete o[f],u.pssh=new Uint8Array(i),u.keyId=s,h=o[a]=h.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:c,mediaKeys:d})=>{var u;this.throwIfDestroyed();const f=new ct("ISO-23001-7",a,(u=Ji(c))!=null?u:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(c,d).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:c,mediaKeys:d});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),h.catch(c=>this.handleError(c))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,s){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=e.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null}catch(g){var l;if(this.warn(g.message),(l=this.hls)!=null&&l.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const h=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${s}": ${h} (init data type: ${t} length: ${i?i.byteLength:null})`);const c=new Ki,d=e._onmessage=g=>{const m=e.mediaKeysSession;if(!m){c.emit("error",new Error("invalid state"));return}const{messageType:y,message:T}=g;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${T.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,T).catch(E=>{this.handleError(E),c.emit("error",E)}):y==="license-release"?e.keySystem===te.FAIRPLAY&&(this.updateKeySession(e,pi("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},u=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;c.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${h}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",u);const f=new Promise((g,m)=>{c.on("error",m),c.on("keyStatus",y=>{y.startsWith("usable")?g():y==="output-restricted"?m(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${h}`)}).catch(g=>{throw new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw c.removeAllListeners(),this.removeSession(e),g}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${be.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${be.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,s=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},h=t.certLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,m)=>{a(u.data)},onError:(u,f,g,m)=>{o(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:he({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};s.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(s=>{throw new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let d=0,u=n.length;d<u;d++){var a,o;c=n[d];const f=(a=c.querySelector("name"))==null?void 0:a.textContent,g=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=s.querySelector("Challenge"),h=l==null?void 0:l.textContent;if(!h)throw new Error("Cannot find <Challenge> in key message");return pi(atob(h))}setupLicenseXHR(e,t,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,s)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(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 h=this.config.licenseResponseCallback;if(h)try{l=h.call(this.hls,o,a,e)}catch(c){this.error(c)}s(l)}else{const l=i.errorRetry,h=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||o.status>=400&&o.status<500)n(new ye({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:h})=>{e.keySystem==te.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(l,h)),l.send(h)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.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={},ct.clearKeyUriToKeyIdMap();const i=t.length;Je.CDMCleanupPromise=Promise.all(t.map(s=>this.removeSession(s)).concat(e==null?void 0:e.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);return s>-1&&this.mediaKeySessions.splice(s,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}Je.CDMCleanupPromise=void 0;class ye 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}}var ue;(function(r){r.MANIFEST="m",r.AUDIO="a",r.VIDEO="v",r.MUXED="av",r.INIT="i",r.CAPTION="c",r.TIMED_TEXT="tt",r.KEY="k",r.OTHER="o"})(ue||(ue={}));var bi;(function(r){r.DASH="d",r.HLS="h",r.SMOOTH="s",r.OTHER="o"})(bi||(bi={}));var Ge;(function(r){r.OBJECT="CMCD-Object",r.REQUEST="CMCD-Request",r.SESSION="CMCD-Session",r.STATUS="CMCD-Status"})(Ge||(Ge={}));const kl={[Ge.OBJECT]:["br","d","ot","tb"],[Ge.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ge.SESSION]:["cid","pr","sf","sid","st","v"],[Ge.STATUS]:["bs","rtp"]};class it{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof it?i:new it(i))),this.value=e,this.params=t}}class Jr{constructor(e){this.description=void 0,this.description=e}}const Pl="Dict";function _l(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Fl(r,e,t,i){return new Error(`failed to ${r} "${_l(e)}" as ${t}`,{cause:i})}const js="Bare Item",Ol="Boolean",Ml="Byte Sequence",Nl="Decimal",Ul="Integer";function Bl(r){return r<-999999999999999||999999999999999<r}const $l=/[\x00-\x1f\x7f]+/,Gl="Token",Hl="Key";function ke(r,e,t){return Fl("serialize",r,e,t)}function Kl(r){if(typeof r!="boolean")throw ke(r,Ol);return r?"?1":"?0"}function Vl(r){return btoa(String.fromCharCode(...r))}function Wl(r){if(ArrayBuffer.isView(r)===!1)throw ke(r,Ml);return`:${Vl(r)}:`}function Zr(r){if(Bl(r))throw ke(r,Ul);return r.toString()}function Yl(r){return`@${Zr(r.getTime()/1e3)}`}function en(r,e){if(r<0)return-en(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const s=Math.floor(r*t);return(s%2===0?s:s+1)/t}else return Math.round(r*t)/t}function jl(r){const e=en(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ke(r,Nl);const t=e.toString();return t.includes(".")?t:`${t}.0`}const ql="String";function zl(r){if($l.test(r))throw ke(r,ql);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Xl(r){return r.description||r.toString().slice(7,-1)}function qs(r){const e=Xl(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ke(e,Gl);return e}function Ii(r){switch(typeof r){case"number":if(!O(r))throw ke(r,js);return Number.isInteger(r)?Zr(r):jl(r);case"string":return zl(r);case"symbol":return qs(r);case"boolean":return Kl(r);case"object":if(r instanceof Date)return Yl(r);if(r instanceof Uint8Array)return Wl(r);if(r instanceof Jr)return qs(r);default:throw ke(r,js)}}function Di(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw ke(r,Hl);return r}function ji(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Di(e)}`:`;${Di(e)}=${Ii(t)}`).join("")}function tn(r){return r instanceof it?`${Ii(r.value)}${ji(r.params)}`:Ii(r)}function Ql(r){return`(${r.value.map(tn).join(" ")})${ji(r.params)}`}function Jl(r,e={whitespace:!0}){if(typeof r!="object")throw ke(r,Pl);const t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof it||(n=new it(n));let a=Di(s);return n.value===!0?a+=ji(n.params):(a+="=",Array.isArray(n.value)?a+=Ql(n):a+=tn(n)),a}).join(`,${i}`)}function Zl(r,e){return Jl(r,e)}const eh=r=>r==="ot"||r==="sf"||r==="st",th=r=>typeof r=="number"?O(r):r!=null&&r!==""&&r!==!1;function ih(r,e){const t=new URL(r),i=new URL(e);if(t.origin!==i.origin)return r;const s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function sh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?n:n&3|8).toString(16)})}}}const wt=r=>Math.round(r),rh=(r,e)=>(e!=null&&e.baseUrl&&(r=ih(r,e.baseUrl)),encodeURIComponent(r)),At=r=>wt(r/100)*100,nh={br:wt,d:wt,bl:At,dl:At,mtp:At,nor:rh,rtp:At,tb:wt};function ah(r,e){const t={};if(r==null||typeof r!="object")return t;const i=Object.keys(r).sort(),s=re({},nh,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=r[a];const l=s[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||th(o)&&(eh(a)&&typeof o=="string"&&(o=new Jr(o)),t[a]=o))}),t}function sn(r,e={}){return r?Zl(ah(r,e),re({whitespace:!1},e)):""}function oh(r,e={}){if(!r)return{};const t=Object.entries(r),i=Object.entries(kl).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),s=t.reduce((n,a)=>{var o,l;const[h,c]=a,d=((o=i.find(u=>u[1].includes(h)))==null?void 0:o[0])||Ge.REQUEST;return(l=n[d])!=null||(n[d]={}),n[d][h]=c,n},{});return Object.entries(s).reduce((n,[a,o])=>(n[a]=sn(o,e),n),{})}function lh(r,e,t){return re(r,oh(e,t))}const hh="CMCD";function ch(r,e={}){if(!r)return"";const t=sn(r,e);return`${hh}=${encodeURIComponent(t)}`}const zs=/CMCD=[^&#]+/;function dh(r,e,t){const i=ch(e,t);if(!i)return r;if(zs.test(r))return r.replace(zs,i);const s=r.includes("?")?"&":"?";return`${r}${s}${i}`}class uh{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:ue.MANIFEST,su:!this.initialized})}catch(n){v.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const n=s.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===ue.VIDEO||o===ue.AUDIO||o==ue.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(n){v.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||sh(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;
26e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:bi.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){re(t,this.createData());const i=t.ot===ue.INIT||t.ot===ue.VIDEO||t.ot===ue.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((n,a)=>(s.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),lh(e.headers,t)):e.url=dh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ue.TIMED_TEXT;if(e.sn==="initSegment")return ue.INIT;if(t==="audio")return ue.AUDIO;if(t==="main")return this.hls.audioTracks.length?ue.VIDEO:ue.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===ue.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ue.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:J.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const fh=3e5;class gh{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(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===de.SendAlternateToPenaltyBox&&i.flags===Se.MoveAllAlternatesMatchingHost){const s=this.levels;let n=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:h}=t.context;o&&s?a=this.getPathwayForGroupId(o,h,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||v.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();
vendor: 1,160 bytes, line 26
26Object.keys(i).forEach(n=>{s-i[n]>fh&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,xr(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===Y.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===Y.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;const h=this.getLevelsForPathway(o).map(c=>{const d=new ie(c.attrs);d["PATHWAY-ID"]=a;const u=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;
26u&&(i[d.AUDIO]=u,d.AUDIO=u),f&&(s[d.SUBTITLES]=f,d.SUBTITLES=f);const g=rn(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new et({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:g,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let y=1;y<c.audioGroups.length;y++)m.addGroupId("audio",`${c.audioGroups[y]}_clone_${a}`);if(c.subtitleGroups)for(let y=1;y<c.subtitleGroups.length;y++)m.addGroupId("text",`${c.subtitleGroups[y]}_clone_${a}`);return m});t.push(...h),Xs(this.audioTracks,i,l,a),Xs(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}const n={responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(c,d,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=c.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":T}=g;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||u.url),y&&this.clonePathways(y);const E={steeringManifest:g,url:s.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,E),T&&this.updatePathwayPriority(T)},onError:(c,d,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let g=this.timeToLoad*1e3;if(c.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,g)},onTimeout:(c,d,u)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,h)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Xs(r,e,t,i){r&&Object.keys(e).forEach(s=>{const n=r.filter(a=>a.groupId===s).map(a=>{const o=re({},a);return o.details=void 0,o.attrs=new ie(o.attrs),o.url=o.attrs.URI=rn(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function rn(r,e,t,i){const{HOST:s,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(r=o));const l=new self.URL(r);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(h=>{h&&l.searchParams.set(h,n[h])}),l.href}const mh=/^age:\s*[\d.]+\s*$/im;class nn{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ht,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=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,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>
26{if(!this.stats.aborted)return n(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&O(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,h=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=h,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const c=this.callbacks.onProgress;if(c&&c(i,e,l,t),!this.callbacks)return;const d={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(d,i,e,t)}else{const l=n.loadPolicy.errorRetry,h=i.retry,c={url:e.url,data:void 0,code:a};Ut(l,h,!1,c)?this.retry(l):(v.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Ut(t,i,!0))this.retry(t);else{var s;v.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Fi(e,i.retry),i.retry++,v.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&mh.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 ph(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const yh=/(\d+)-(\d+)\/(\d+)/;class Qs{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||xh,this.controller=new self.AbortController,this.stats=new Ht}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=Th(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=h&&O(h)?h:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},c-(u-s.loading.start)),!d.ok){const{status:f,statusText:g}=d;throw new vh(g||"fetch, bad network response",f,d)}return s.loading.first=u,s.total=Sh(d.headers)||s.total,a&&O(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=d[l];f&&(s.loaded=s.total=f);const g={url:u.url,data:d,code:u.status};a&&!O(t.highWaterMark)&&a(s,e,d,u),i.onSuccess(g,s,e,u)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=d&&d.code||0,f=d?d.message:null;i.onError({code:u,text:f}
vendor: 5,071 bytes, line 26
26,e,d?d.details:null,s)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){const a=new Rr,o=e.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const c=h.value,d=c.length;return t.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush(),e)):n(t,i,c,e),l()}).catch(()=>Promise.reject());return l()}}function Th(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(re({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Eh(r){const e=yh.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Sh(r){const e=r.get("Content-Range");if(e){const i=Eh(e);if(O(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function xh(r,e){return new self.Request(r.url,e)}class vh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const Ah=/\s/,Lh={newCue(r,e,t,i){const s=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var d;for(let m=0;m<n.chars.length;m++)Ah.test(n.chars[m].uchar)&&o?l++:(h+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=jr(h.trim()),g=Wi(e,t,f);r!=null&&(d=r.cues)!=null&&d.getCueById(g)||(a=new c(e,t,f),a.id=g,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>yr(r,u))),s}},Rh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},an=he(he({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold: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:nn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:eo,bufferController:nl,capLevelController:Yi,errorController:Ha,fpsController:wl,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:sr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Rh},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},bh()),{},{subtitleStreamController:tl,subtitleTrackController:sl,timelineController:Dl,audioStreamController:Zo,audioTrackController:el,emeController:Je,cmcdController:uh,
26contentSteeringController:gh});function bh(){return{cueHandler:Lh,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 Ih(r,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=Ci(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];s.forEach(h=>{const c=`${n}Loading${h}`,d=e[c];if(d!==void 0&&o){l.push(c);const u=t[a].default;switch(e[a]={default:u},h){case"TimeOut":u.maxLoadTimeMs=d,u.maxTimeToFirstByteMs=d;break;case"MaxRetry":u.errorRetry.maxNumRetry=d,u.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":u.errorRetry.retryDelayMs=d,u.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=d,u.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&v.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),he(he({},t),e)}function Ci(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Ci):Object.keys(r).reduce((e,t)=>(e[t]=Ci(r[t]),e),{}):r}function Dh(r){const e=r.loader;e!==Qs&&e!==nn?(v.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):ph()&&(r.loader=Qs,r.progressive=!0,r.enableSoftwareAES=!0,v.log("[config]: Progressive streaming enabled, using FetchLoader"))}let gi;class Ch extends Oi{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],n={},a={};let o=!1,l=!1,h=!1;t.levels.forEach(c=>{var d,u;const f=c.attrs;let{audioCodec:g,videoCodec:m}=c;((d=g)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(gi||(gi=/chrome|firefox/i.test(navigator.userAgent)),gi&&(c.audioCodec=g=void 0)),g&&(c.audioCodec=g=Ot(g,i)),((u=m)==null?void 0:u.indexOf("avc1"))===0&&(m=c.videoCodec=ya(m));const{width:y,height:T,unknownCodecs:E}=c;if(o||(o=!!(y&&T)),l||(l=!!m),h||(h=!!g),E!=null&&E.length||g&&!Zt(g,"audio",i)||m&&!Zt(m,"video",i))return;const{CODECS:S,"FRAME-RATE":b,"HDCP-LEVEL":x,"PATHWAY-ID":D,RESOLUTION:R,"VIDEO-RANGE":w}=f,I=`${`${D||"."}-`}${c.bitrate}-${R}-${b}-${S}-${w}-${x}`;if(n[I])if(n[I].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const k=a[I]+=1;c.attrs["PATHWAY-ID"]=new Array(k+1).join(".");const K=new et(c);n[I]=K,s.push(K)}else n[I].addGroupId("audio",f.AUDIO),n[I].addGroupId("text",f.SUBTITLES);
26else{const k=new et(c);n[I]=k,a[I]=1,s.push(k)}}),this.filterAndSortMediaOptions(s,t,o,l,h)}filterAndSortMediaOptions(e,t,i,s,n){let a=[],o=[],l=e;if((i||s)&&n&&(l=l.filter(({videoCodec:g,videoRange:m,width:y,height:T})=>(!!g||!!(y&&T))&&wa(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const g=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:g,reason:g.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:g}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||Zt(m.audioCodec,"audio",g)),Js(a)}t.subtitles&&(o=t.subtitles,Js(o));const h=l.slice(0);l.sort((g,m)=>{if(g.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&g.height!==m.height)return g.height-m.height;if(g.frameRate!==m.frameRate)return g.frameRate-m.frameRate;if(g.videoRange!==m.videoRange)return Mt.indexOf(g.videoRange)-Mt.indexOf(m.videoRange);if(g.videoCodec!==m.videoCodec){const y=ss(g.videoCodec),T=ss(m.videoCodec);if(y!==T)return T-y}if(g.uri===m.uri&&g.codecSet!==m.codecSet){const y=Ft(g.codecSet),T=Ft(m.codecSet);if(y!==T)return T-y}return g.averageBitrate!==m.averageBitrate?g.averageBitrate-m.averageBitrate:0});let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let g=0;g<h.length;g++)if(h[g].pathwayId===l[0].pathwayId){c=h[g];break}}this._levels=l;for(let g=0;g<l.length;g++)if(l[g]===c){var d;this._firstLevel=g;const m=c.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${m}`),((d=this.hls.userConfig)==null?void 0:d.abrEwmaDefaultEstimate)===void 0){const T=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);T>y&&y===an.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const u=n&&!s,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:!u&&a.some(g=>!!g.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(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 c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const h=a.details;if(!h||h.live){const c=this.switchParams(a.uri,s==null?void 0:s.details);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===Y.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===U.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:n}=t,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}
26`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const n=i.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:""} ${s}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:s,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,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){var t;const i=this._levels.filter((s,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));xr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Js(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class wh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=L.KEY_LOAD_ERROR,i,s,n){return new Oe({type:$.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let n=0;n<t.length;n++){const a=t[n];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.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 i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const h=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,L.KEY_LOAD_ERROR,h))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.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(h=>(n.key=h.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.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,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);
26if(s)return(e.keyLoadPromise=s.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},h=i.keyLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,m)=>{const{frag:y,keyInfo:T,url:E}=g;if(!y.decryptdata||T!==this.keyUriToKeyInfo[E])return o(this.createKeyLoadError(y,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));T.decryptdata.key=y.decryptdata.key=new Uint8Array(u.data),y.keyLoader=null,T.loader=null,a({frag:y,keyInfo:T})},onError:(u,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,he({url:l.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,L.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(l,c,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}function on(){return self.SourceBuffer||self.WebKitSourceBuffer}function ln(){if(!st())return!1;const e=on();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function kh(){if(!ln())return!1;const r=st();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(dt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(dt(e,"audio"))))}function Ph(){var r;const e=on();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const _h=250,kt=2,Fh=.1,Oh=.05;class Mh{constructor(e,t,i,s){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=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:s,stalled:n}=this;if(s===null)return;const{currentTime:a,seeking:o}=s,l=this.seeking&&!o,h=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){const y=self.performance.now()-n;v.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(h||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!J.getBuffered(s).length){this.nudgeRetry=0;return}const c=J.bufferInfo(s,a,0),d=c.nextStart||0;if(o){const y=c.len>kt,T=!d||t&&t.start<=a||d-a>kt&&!this.fragmentTracker.getPartialFragment(a);if(y||T)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var u;if(!(c.len>0)&&!d)return;const T=Math.max(d,c.start||0)-a,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,b=(E==null||(u=E.details)==null?void 0:u.live)?E.details.targetduration*2:kt,x=this.fragmentTracker.getPartialFragment(a);if(T>0&&(T<=b||x)){s.paused||this._trySkipBufferHole(x);return}}const f=self.performance.now();if(n===null){this.stalled=f;return}const g=f-n;if(!o&&g>=_h&&(this._reportStall(c),!this.media))return;const m=J.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;const a=n.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(v.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);v.warn(n.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:s}=this;if(s===null)return 0;const n=s.currentTime,a=J.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,h=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(l||h)){if(c>t.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(n===0){const g=u.getAppendedFrag(0,U.MAIN);g&&o<g.end&&(f=!0)}if(!f){const g=e||u.getAppendedFrag(n,U.MAIN);if(g){let m=!1,y=g.end;for(;y<o;){const T=u.getPartialFragment(y);if(T)y+=T.duration;else{m=!0;break}}if(m)return 0}}}const d=Math.max(o+Oh,n+Fh);if(v.warn(`skipping hole, adjusting currentTime from ${n} to ${d}`),this.moved=!0,this.stalled=null,s.currentTime=d,e&&!e.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${d}`);i.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:e})}return d}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;
26const n=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){const a=n+(s+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);v.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);v.error(a.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Nh=100;class Uh extends Ui{constructor(e,t,i){super(e,t,i,"[stream-controller]",U.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(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Nh),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,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:{const{levels:t,level:i}=this,s=t==null?void 0:t[i],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(n))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 e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:s,level:n}=this,a=s==null?void 0:s[n];this.resetStartWhenNotLoaded(a||null),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:i,media:s}=this;if(t===null||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),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 h=a.details;if(!h||this.state===C.WAITING_LEVEL||h.live&&this.levelLastLoaded!==a){this.level=n,this.state=C.WAITING_LEVEL;return}const c=o.len,d=this.getMaxBufferLength(a.maxBitrate);
26if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(u,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==le.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-h.startSN,T=h.fragments[y-1];T&&f.cc===T.cc&&(f=T,this.fragmentTracker.removeFragment(T))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?X.AUDIO:X.VIDEO,T=(y===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;T&&this.afterBufferFlushed(T,y,U.MAIN)}f=this.getNextFragmentLoopLoading(f,h,o,U.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,u))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===le.NOT_LOADED||s===le.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,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,U.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 i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],h=this.fragLastKbps;h&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*h)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,h=o.duration,c=Math.max(a.end,l+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,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 i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Mh(this.config,i,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;O(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,s=!1;
26t.levels.forEach(n=>{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!Ph(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==C.IDLE)return;const s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s}=this,n=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=s[n],h=this.fragCurrent;h&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=C.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const h=o.videoCodec,c=l.PTSKnown||!l.live,d=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Gr(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=g!==-1,y=new Mi(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,m),T=this.initPTS[i.cc];f.push(n,d,u,h,i,s,l.totalduration,c,y,T)}onAudioTrackSwitching(e,t){const i=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 a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,s=!!this.hls.audioTracks[i].url;if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){const h=i[o];h&&(this.videoBuffer=h.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i&&i.type!==U.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}const n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Y.LEVEL&&(this.state=C.IDLE);break;case L.BUFFER_APPEND_ERROR:case L.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===L.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}
26checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!J.getBuffered(e).length){const i=this.state!==C.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}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!==X.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,U.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=J.getBuffered(e),a=(s.length?s.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(p.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:c}=o,{video:d,text:u,id3:f,initSegment:g}=n,{details:m}=c,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,g){if(g!=null&&g.tracks){const S=l.initSegment||l;this._bufferInitSegment(c,g.tracks,S,a),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:i,tracks:g.tracks})}const T=g.initPTS,E=g.timescale;O(T)&&(this.initPTS[l.cc]={baseTime:T,timescale:E},s.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:T,timescale:E}))}if(d&&m&&l.sn!=="initSegment"){const T=m.fragments[l.sn-1-m.startSN],E=l.sn===m.startSN,S=!T||l.cc>T.cc;if(n.independent!==!1){const{startPTS:b,endPTS:x,startDTS:D,endDTS:R}=d;if(h)h.elementaryStreams[d.type]={startPTS:b,endPTS:x,startDTS:D,endDTS:R};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!S&&(this.couldBacktrack=!0),d.dropped&&d.independent){const w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,I=d.firstKeyFramePTS?d.firstKeyFramePTS:b;if(!E&&P<I-this.config.maxBufferHole&&!S){this.backtrack(l);return}else S&&(l.gap=!0);l.setElementaryStreamInfo(d.type,l.start,x,l.start,R,!0)}else E&&b>kt&&(l.gap=!0);l.setElementaryStreamInfo(d.type,b,x,D,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,h,a,E||S)}else if(E||S)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:T,endPTS:E,startDTS:S,endDTS:b}=y;h&&(h.elementaryStreams[X.AUDIO]={startPTS:T,endPTS:E,startDTS:S,endDTS:b}),l.setElementaryStreamInfo(X.AUDIO,T,E,S,b),this.bufferFragmentData(y,l,h,a)}if(m&&f!=null&&(t=f.samples)!=null&&t.length){const T={id:i,frag:l,details:m,samples:f.samples};s.trigger(p.FRAG_PARSING_METADATA,T)}if(m&&u){const T={id:i,frag:l,details:m,samples:u.samples};s.trigger(p.FRAG_PARSING_USERDATA,T)}}_bufferInitSegment(e,t,i,s){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec;const h=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&h.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&n.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}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const c=t[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:c,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,U.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 i=e.currentTime;if(J.isBuffered(e,i)?t=this.getAppendedFrag(i):J.isBuffered(e,i+.
261)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}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,i=this.currentFrag;if(i&&O(t)&&O(i.programDateTime)){const s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ae{static get version(){return"1.5.6"}static isMSESupported(){return ln()}static isSupported(){return kh()}static getMediaSource(){return st()}static get Events(){return p}static get ErrorTypes(){return $}static get ErrorDetails(){return L}static get DefaultConfig(){return Ae.defaultConfig?Ae.defaultConfig:an}static set DefaultConfig(e){Ae.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Ki,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,Cn(e.debug||!1,"Hls instance");const t=this.config=Ih(Ae.DefaultConfig,e);this.userConfig=e,t.progressive&&Dh(t);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),h=this.abrController=new i(this),c=this.bufferController=new s(this),d=this.capLevelController=new n(this),u=new o(this),f=new va(this),g=new Ia(this),m=t.contentSteeringController,y=m?new m(this):null,T=this.levelController=new Ch(this,y),E=new io(this),S=new wh(this.config),b=this.streamController=new Uh(this,E,S);d.setStreamController(b),u.setStreamController(b);const x=[f,T,b];y&&x.splice(1,0,y),this.networkControllers=x;const D=[h,c,d,u,g,E];this.audioTrackController=this.createController(t.audioTrackController,x);const R=t.audioStreamController;R&&x.push(new R(this,E,S)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);const w=t.subtitleStreamController;w&&x.push(new w(this,E,S)),this.createController(t.timelineController,D),S.emeController=this.emeController=this.createController(t.emeController,D),this.cmcdController=this.createController(t.cmcdController,D),this.latencyController=this.createController(Da,D),this.coreComponents=D,x.push(l);const P=l.onErrorOut;typeof P=="function"&&this.on(p.ERROR,P,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(v.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===p.ERROR;this.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){v.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEac
26h(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(p.MEDIA_ATTACHING,{media:e})}detachMedia(){v.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,s=this.url=wi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,v.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){v.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){v.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in 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){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){v.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,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(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}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}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}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,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ca(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!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}}Ae.defaultConfig=void 0;const Bh=Object.prototype.hasOwnProperty;
26class at extends Event{constructor(e,t){super(e),this.detail=t}}class $h extends EventTarget{constructor(e={}){super();const{concurrency:t=1/0,timeout:i=0,autostart:s=!1,results:n=null}=e;this.concurrency=t,this.timeout=i,this.autostart=s,this.results=n,this.pending=0,this.session=0,this.running=!1,this.jobs=[],this.timers=[],this.addEventListener("error",this._errorHandler)}_errorHandler(e){this.end(e.detail.error)}pop(){return this.jobs.pop()}shift(){return this.jobs.shift()}indexOf(e,t){return this.jobs.indexOf(e,t)}lastIndexOf(e,t){return t!==void 0?this.jobs.lastIndexOf(e,t):this.jobs.lastIndexOf(e)}slice(e,t){return this.jobs=this.jobs.slice(e,t),this}reverse(){return this.jobs.reverse(),this}push(...e){const t=this.jobs.push(...e);return this.autostart&&this._start(),t}unshift(...e){const t=this.jobs.unshift(...e);return this.autostart&&this._start(),t}splice(e,t,...i){return this.jobs.splice(e,t,...i),this.autostart&&this._start(),this}get length(){return this.pending+this.jobs.length}start(e){if(this.running)throw new Error("already started");let t;return e?this._addCallbackToEndEvent(e):t=this._createPromiseToEndEvent(),this._start(),t}_start(){if(this.running=!0,this.pending>=this.concurrency)return;if(this.jobs.length===0){this.pending===0&&this.done();return}const e=this.jobs.shift(),t=this.session,i=e!==void 0&&Bh.call(e,"timeout")?e.timeout:this.timeout;let s=!0,n=null,a=!1,o=null;const l=(h,...c)=>{s&&this.session===t&&(s=!1,this.pending--,n!==null&&(this.timers=this.timers.filter(d=>d!==n),clearTimeout(n)),h?this.dispatchEvent(new at("error",{error:h,job:e})):a||(o!==null&&this.results!==null&&(this.results[o]=[...c]),this.dispatchEvent(new at("success",{result:[...c],job:e}))),this.session===t&&(this.pending===0&&this.jobs.length===0?this.done():this.running&&this._start()))};i&&(n=setTimeout(()=>{a=!0,this.dispatchEvent(new at("timeout",{next:l,job:e})),l()},i),this.timers.push(n)),this.results!=null&&(o=this.results.length,this.results[o]=null),this.pending++,this.dispatchEvent(new at("start",{job:e})),e.promise=e(l),e.promise!==void 0&&typeof e.promise.then=="function"&&e.promise.then(function(h){return l(void 0,h)}).catch(function(h){return l(h||!0)}),this.running&&this.jobs.length>0&&this._start()}stop(){this.running=!1}end(e){this.clearTimers(),this.jobs.length=0,this.pending=0,this.done(e)}clearTimers(){this.timers.forEach(e=>{clearTimeout(e)}),this.timers=[]}_addCallbackToEndEvent(e){const t=i=>{this.removeEventListener("end",t),e(i.detail.error,this.results)};this.addEventListener("end",t)}_createPromiseToEndEvent(){return new Promise((e,t)=>{this._addCallbackToEndEvent((i,s)=>{i?t(i):e(s)})})}done(e){this.session++,this.running=!1,this.dispatchEvent(new at("end",{error:e}))}}const Gh=new $h({concurrency:1,autostart:!0,timeout:1e3}),Hh=mn({name:"EntireMedia",props:{media:{type:Object,default:null},subtitles:{type:Object,default:null},objectFit:{type:String,default:null},paused:{type:Boolean,default:!1},pauseOffscreen:{type:Boolean,default:!1},preload:{type:Boolean,default:!1},ratio:{type:Number,default:null},zoom:{type:Number,default:1},alt:{type:String,default:null},multiplier:{type:Number,default:1},minWidth:{type:Number,default:null},minHeight:{type:Number,default:null},maxWidth:{type:Number,default:null},maxHeight:{type:Number,default:null},xOffset:{type:Number,default:null},yOffset:{type:Number,default:null},transition:{type:Boolean,default:!1},transitionDuration:{type:Number,default:500},background:{type:Boolean,default:!1},muted:{type:Boolean,default:!0},controls:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},loop:{type:Boolean,default:!0},playsinline:{type:Boolean,default:!0},loading:{type:String,default:null},thumbnail:{type:Boolean,default:!0},hlsEnabled:{type:Boolean,default:!0},formatsEnabled:{type:Boolean,default:!0},posterWebpEnabled:{type:Boolean,default:!0},format:{type:String,default:null},currentTime:{type:Number,default:0},startTime:{type:Number,default:null},endTime:{type:Number,default:null}},emits:["loaded","play","timeupdate","thumbnailloaded","error","subtitlesloaded"],data(){return{offscreen:!0,thumbnailLoaded:!1,loaded:!1,mediaLoaded:!1,videoWidth:null,videoHeight:null,forceLocal:!1,hlsSupportedNatively:!1,hlsSupportedNativelyLevels:[],hlsSupportedNativelySrc:void 0,hlsSupported:!0,formats:["thumbnail","tiny","small","medium","big","large","huge","original"],availableWidth:null,availableHeight:null,mediaRefs:[],loadRef:null,thumbnailLoadRef:null,posterLoadRef:null}},computed:{mediaFragment(){return this.startTime||this.endTime?`#t=${this.startTime||0}${this.endTime?","+this.endTime:""}`:""},mediaFormats(){return Sn(this.media,this.formatsEnabled)},mediaWidth(){return this.media.width||this.videoWidth},mediaHeight(){return this.media.height||this.videoHeight},mediaRatio(){return this.media?this.mediaWidth&&this.mediaHeight?this.mediaWidth/this.mediaHeight:null:1},containerMinWidth(){const r=this.minWidth?Math.max(this.minWidth,0):null;return this.mediaRatio&&!this.objectFit&&(this.containerMinHeight||r)?Math.min((this.containerMaxHeight||1/0)*this.mediaRatio,Math.min(this.containerMaxWidth||1/0,Math.max((this.containerMinHeight||0)*this.mediaRatio,r||0)||1/0)):r},containerMinHeight(){return this.minHeight?Math.max(this.minHeight,0):null},containerMinRatio(){return this.containerMinWidth&&this.containerMinHeight?this.containerMinWidth/this.containerMinHeight:null},containerMaxWidth(){const r=this.maxWidth?Math.max(this.maxWidth,0):null;return this.mediaRatio&&!this.objectFit&&(this.containerMaxHeight||r)&&Math.min((this.containerMaxHeight||1/0)*this.mediaRatio,r||1/0)||r},containerMaxHeight(){return this.maxHeight?Math.max(this.maxHeight,0):null},containerMaxRatio(){return this.containerMaxWidth&&this.containerMaxHeight?this.containerMaxWidth/this.containerMaxHeight:null},contentRatio(){return this.ratio?this.ratio:this.mediaRatio&&!this.objectFit?this.mediaRatio:null},outerPaddingTop(){return!(this.loaded||!this.transition)&&this.contentRatio?1/this.contentRatio*100+"%":"0"},innerPaddingTop(){return this.contentRatio&&this.objectFit?1/this.contentRatio*100+"%":this.mediaRatio&&!this.objectFit?1/this.mediaRatio*100+"%":"0"},innerHeight(){return this.contentRatio&&this.objectFit||this.mediaRatio&&!this.objectFit?0:"100%"},isAudio(){return this.media&&this.media.mime?this.media.mime.includes("audio"):!1},isVideo(){return this.media&&this.media.mime?this.media.mime.includes("video"):!1},isGif(){return this.media&&this.media.mime?this.media.mime.includes("image/gif"):!1}
26,src(){return this.getSrc(this.forceLocal?"local":"")},thumbnailSrc(){return this.getSrc(this.forceLocal?"local":"","","thumbnail")},srcWebm(){return this.getSrc(this.forceLocal?"local":"","webm")},srcWebp(){return this.getSrc(this.forceLocal?"local":"","webp")},thumbnailSrcWebp(){return this.isGif?this.getSrc(this.forceLocal?"local":"","webp","thumbnail"):null},srcPoster(){return this.isVideo?this.getSrc(this.forceLocal?"local":"","poster"):null},srcPosterWebp(){return this.isVideo?this.getSrc(this.forceLocal?"local":"","poster-webp"):null},thumbnailSrcPoster(){return this.isVideo?this.getSrc(this.forceLocal?"local":"","poster","thumbnail"):null},thumbnailSrcPosterWebp(){return this.isVideo?this.getSrc(this.forceLocal?"local":"","poster-webp","thumbnail"):null},srcHls(){return this.isVideo&&this.hlsEnabled&&this.hlsSupported&&!this.src.endsWith(".webm")?this.getMediaUrl(this.media,"","hls"):null},size(){const r=this.zoom*ut("devicePixelRatio",()=>1).value;return{width:(this.availableWidth||this.containerMinWidth||this.containerMaxWidth||ut("clientWidth").value)*r,height:(this.availableHeight||this.containerMinHeight||this.containerMaxHeight||ut("clientHeight").value)*r}},mediaPaused(){return this.paused||this.pauseOffscreen&&this.offscreen},webpSupported(){return ut("webpSupported",()=>!0).value},skipLoading(){return!this.preload&&this.mediaPaused&&(!this.controls||this.pauseOffscreen&&!this.paused)}},watch:{size(){this.updateHlsLevel()},preload(){this.loadHls()},loaded(){this.loadHls()},mediaPaused(){this.$nextTick(()=>{this.loadHls(),this.hls&&(this.mediaPaused&&!this.preload?this.hls.stopLoad():this.hls.startLoad()),this.restartVideo()})},currentTime(){this.$refs.video?this.$refs.video.currentTime=this.currentTime:this.$refs.audio&&(this.$refs.audio.currentTime=this.currentTime)}},mounted(){var r,e,t,i,s;this.$nextTick(()=>{this.loadHls()}),gn().isHydrating&&((r=this.thumbnailLoadRef)!=null&&r.complete&&(this.thumbnailLoadRef.getAttribute("data-error")?this.loadError(new Event("error"),"thumbnail"):this.thumbnailLoad(new Event("load"))),(e=this.loadRef)!=null&&e.complete&&(this.loadRef.getAttribute("data-error")?this.loadError(new Event("error")):this.load(new Event("load"))),(t=this.posterLoadRef)!=null&&t.complete&&(this.posterLoadRef.getAttribute("data-error")?this.loadError(new Event("error"),"poster"):this.load(new Event("load"))),(i=this.$refs.video)!=null&&i.complete&&(this.$refs.video.getAttribute("data-error")?this.loadError(new Event("error"),"video"):this.loadeddata(new Event("loadeddata"))),(s=this.$refs.audio)!=null&&s.complete&&(this.$refs.audio.getAttribute("data-error")?this.loadError(new Event("error"),"audio"):this.loadeddata(new Event("loadeddata"))))},unmounted(){const r=this.hls;setTimeout(()=>{this.destroyHls(r),this.mediaRefs&&this.mediaRefs.forEach(e=>{try{e.src&&(e.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),e.srcset&&(e.srcset=""),e.loading&&delete e.loading}catch{}})},500)},methods:{updateHlsLevel(){var e;const r=((e=this.hls)==null?void 0:e.levels)||this.hlsSupportedNativelyLevels;if(r!=null&&r.length){const t=r.find(i=>i.height*1.1>=this.size.height&&i.width*1.1>=this.size.width)||r[r.length-1];this.hlsSupportedNatively?t!=null&&t.url&&(this.hlsSupportedNativelySrc=this.srcHls.replace(/\/[^/]*$/,"/"+t.url)):this.hls&&r.indexOf(t)!==this.hls.currentLevel&&(this.hls.currentLevel=r.indexOf(t))}},destroyHls(r){r&&Gh.push(e=>{try{r.destroy(),delete this.hls,e&&e()}catch{e&&e()}})},setMediaRef(r,e=""){r&&(this.mediaRefs.push(r),e==="load"?this.loadRef=r:e==="thumbnail"?this.thumbnailLoadRef=r:e==="poster"&&(this.posterLoadRef=r))},onResize(r){this.availableWidth=r.width,this.availableHeight=r.height},getMediaUrl(r,e="",t=""){return r?(t==="webm"&&e!=="local"&&this.$config.public.cloudinaryEnabled&&this.$config.public.cloudinaryWebmEnabled&&r.provider_metadata&&r.provider_metadata.cloudinary&&r.provider_metadata.cloudinary.webm_url?r.provider_metadata.cloudinary.webm_url:(t==="webp"||t==="poster")&&e!=="local"&&this.$config.public.cloudinaryEnabled&&this.$config.public.cloudinaryWebpEnabled&&r.provider_metadata&&r.provider_metadata.cloudinary&&r.provider_metadata.cloudinary.webp_url?r.provider_metadata.cloudinary.webp_url:(t===""||t==="poster")&&e!=="local"&&this.$config.public.cloudinaryEnabled&&r.provider_metadata&&r.provider_metadata.cloudinary&&r.provider_metadata.cloudinary.url?r.provider_metadata.cloudinary.url:(t===""||t==="poster")&&e!=="local"&&this.$config.public.bunnycdnEnabled&&r.provider_metadata&&r.provider_metadata.bunnycdn&&r.provider_metadata.bunnycdn.url?r.provider_metadata.bunnycdn.url:(t===""||t==="poster")&&e!=="local"&&this.$config.public.keycdnEnabled&&r.provider_metadata&&r.provider_metadata.keycdn&&r.provider_metadata.keycdn.url?r.provider_metadata.keycdn.url:(t===""||t==="poster")&&e!=="local"&&this.$config.public.cloudflareEnabled&&r.provider_metadata&&r.provider_metadata.cloudflare&&r.provider_metadata.cloudflare.url?r.provider_metadata.cloudflare.url:t!=="hls"&&(t===""||t==="poster")?r.url.indexOf("/files/")!==0&&r.url.indexOf("/uploads/")!==0?r.url:this.$config.public.strapiURL+r.url:t==="hls"&&e!=="local"&&this.$config.public.bunnycdnEnabled&&r.provider_metadata&&r.provider_metadata.bunnycdn&&r.provider_metadata.bunnycdn.hls?r.provider_metadata.bunnycdn.hls.replace(this.$config.public.bunnycdnStreamUrl,this.$config.public.bunnycdnStreamProxyUrl||this.$config.public.bunnycdnStreamUrl):t==="hls"&&e!=="local"&&this.$config.public.cloudflareEnabled&&r.provider_metadata&&r.provider_metadata.cloudflare&&r.provider_metadata.cloudflare.hls?r.provider_metadata.cloudflare.hls.replace(this.$config.public.bunnycdnStreamUrl,this.$config.public.bunnycdnStreamProxyUrl||this.$config.public.bunnycdnStreamUrl):"").replace(/ /g,"%20"):null},getSrc(r="",e="",t=null){return this.size.width||this.size.height||t?this.srcSized(this.size.width,this.size.height,r,e,t):null},srcSized(r,e,t="",i="",s=null){if(!this.media||!this.media.url)return"";if(this.media.url.indexOf("/files/")!==0&&this.media.url.indexOf("/uploads/")!==0)return this.getMediaUrl(this.media,t,i);if(this.media.url.indexOf("/files/")!==0&&this.media.url.indexOf("/uploads/")!==0||!this.mediaFormats||this.media.url.includes(".svg")||!r&&!s)return this.getMediaUrl(this.media,t,i);{const n=i==="poster"||i==="poster-webp",a=i==="webp"||i==="poster-webp",o=(this.format?this.format+(n?"-"+i:a?"-webp":""):void 0)||(s?s+(n?"-"+i:a?"-webp":""):void 0)||this.formats.find((l,h)=>{const c=l?this.mediaFormats[l+(n?"-"+i:"")]:this.media;return c&&(r<=c.width*1.1&&(this.objectFit!=="cover"||!e&&!this.ratio||(e||r*this.ratio)<=c.height*1.1)||!this.formats[h+1]||!this.formats.slice(h+1).find(d=>this.mediaFormats[d+(n?"-"+i:a?"-webp":"")]&&this.mediaFormats[d+(n?"-"+i:a?"-webp":"")].width<=2560))})+(n?"-"+i:a?"-webp":"");return this.getMediaUrl(this.mediaFormats[o]||(n||a?null:this.media),t,a?""
26:i)}},load(r){this.loaded=!0,this.$emit("loaded",r)},thumbnailLoad(r){this.thumbnailLoaded=!0,this.$emit("thumbnailloaded",r)},subtitlesLoad(){this.$emit("subtitlesloaded",this.$refs.subtitles)},playing(){this.restartVideo()},seeked(){var r;(r=this.$refs.video)!=null&&r.removeEventListener&&this.$refs.video.removeEventListener("seeked",this.seeked),this.$nextTick(()=>{this.mediaLoaded=!0})},async loadeddata(r){var e;this.load(r),this.$refs.video&&(!this.media.width||!this.media.height)&&(this.videoWidth=this.$refs.video.videoWidth,this.videoHeight=this.$refs.video.videoHeight),await this.restartVideo(),(e=this.$refs.video)!=null&&e.addEventListener&&this.$refs.video.seeking?(this.$refs.video.addEventListener("seeked",this.seeked),setTimeout(()=>{this.mediaLoaded=!0},1e3)):this.mediaLoaded=!0},mousedown(){this.restartVideo()},async restartVideo(){if(!this.controls){if(this.$refs.video)try{this.mediaPaused?await this.$refs.video.pause():await this.$refs.video.play()}catch{}else if(this.$refs.audio)try{this.mediaPaused?await this.$refs.audio.pause():await this.$refs.audio.play()}catch{}}},loadError(r,e=""){var t,i,s,n,a,o,l,h,c,d;typeof process<"u"&&process.server&&(e===""?(t=this.loadRef)!=null&&t.setAttribute&&((i=this.loadRef)==null||i.setAttribute("data-error","true")):e==="poster"?(s=this.posterLoadRef)!=null&&s.setAttribute&&((n=this.posterLoadRef)==null||n.setAttribute("data-error","true")):e==="video"?(a=this.$refs.video)!=null&&a.setAttribute&&((o=this.$refs.video)==null||o.setAttribute("data-error","true")):e==="audio"?(l=this.$refs.audio)!=null&&l.setAttribute&&((h=this.$refs.audio)==null||h.setAttribute("data-error","true")):e==="thumbnail"&&(c=this.thumbnailLoadRef)!=null&&c.setAttribute&&((d=this.thumbnailLoadRef)==null||d.setAttribute("data-error","true"))),this.forceLocal&&e!=="thumbnail"&&e!=="poster"?this.$emit("error",r):this.forceLocal=!0},loadHls(){this.skipLoading||this.$refs.video&&this.srcHls&&!this.hls&&this.hlsEnabled&&(this.$refs.video.canPlayType("application/vnd.apple.mpegurl")?fetch(this.srcHls).then(r=>r.text()).then(r=>{const e=r.split(` 27`);this.hlsSupportedNativelyLevels=[];for(let t=0;t<e.length;t++){const i=e[t];if(i.startsWith("#EXT-X-STREAM-INF:")){const s={},n=i.match(/BANDWIDTH=(\d+)/),a=i.match(/RESOLUTION=(\d+x\d+)/);if(n&&(s.bandwidth=parseInt(n[1])),a){const[o,l]=a[1].split("x").map(Number);s.width=o,s.height=l}t+1<e.length&&(s.url=e[++t]),this.hlsSupportedNativelyLevels.push(s)}}this.hlsSupportedNatively=!0,this.updateHlsLevel()}):Ae.isSupported()?(this.hls=new Ae({startFragPrefetch:!this.mediaPaused,startPosition:this.startTime}),this.hls.attachMedia(this.$refs.video),this.hls.loadSource(this.srcHls),this.hls.on(Ae.Events.MANIFEST_PARSED,()=>{this.hls&&this.updateHlsLevel()}),this.hls.on(Ae.Events.MEDIA_DETACHED,()=>{this.destroyHls(this.hls)}),this.hls.on(Ae.Events.ERROR,(r,e)=>{e.fatal&&(this.hlsSupported=!1,this.destroyHls(this.hls))})):this.hlsSupported=!1)}}}),Kh={key:0,class:"thumbnail"},Vh={key:1},Wh=["srcset"],Yh=["src","alt","loading"],jh={key:2},qh=["srcset"],zh=["src","alt","loading"],Xh=["alt"],Qh=["srcset"],Jh=["src","alt","loading"],Zh=["autoplay","loop","playsinline","muted","controls","alt","loading"],ec=["src","type"],tc=["width","height","autoplay","loop","playsinline","muted","controls","alt","poster","loading"],ic=["src","type"],sc=["src","type"],rc=["src"],nc={key:2},ac=["srcset"],oc=["src","alt","loading"],lc=["alt"],hc={key:3,class:"image-placeholder"};function cc(r,e,t,i,s,n){const a=hn,o=cn,l=dn;return Z(),pn(l,{onResize:r.onResize},{default:ft(()=>[Wt(o,{enabled:r.pauseOffscreen,onEnter:e[21]||(e[21]=h=>r.offscreen=!1),onLeave:e[22]||(e[22]=h=>r.offscreen=!0)},{default:ft(()=>[qi("div",{class:"media-container",style:Le({height:r.objectFit?void 0:"auto",minWidth:r.containerMinWidth?r.containerMinWidth+"px":void 0,minHeight:r.objectFit&&r.containerMinHeight?r.containerMinHeight+"px":void 0,maxWidth:r.containerMaxWidth?r.containerMaxWidth+"px":void 0,maxHeight:r.objectFit&&r.containerMaxHeight?r.containerMaxHeight+"px":void 0,paddingTop:r.outerPaddingTop})},[Wt(yn,{name:r.transition?"media":void 0,duration:r.transition?{enter:r.transitionDuration,leave:r.transitionDuration}:0},{default:ft(()=>[Yt(qi("div",{class:Tn(["media",{cover:r.objectFit&&r.objectFit==="cover",contain:r.objectFit&&r.objectFit==="contain"}
27]),style:Le({height:r.innerHeight,"padding-top":r.innerPaddingTop,transitionDuration:r.transition?r.transitionDuration+"ms":void 0})},[r.thumbnail&&!r.transition&&!r.loaded?(Z(),ee("div",Kh,[r.background?(Z(),ee("div",{key:0,style:Le({background:`url(${r.thumbnailSrc})`,backgroundSize:r.objectFit||"contain",width:"100%"}),class:"picture"},null,4)):fe("",!0),!r.background&&r.thumbnailSrcPoster?(Z(),ee("picture",Vh,[r.posterWebpEnabled&&r.thumbnailSrcPosterWebp?(Z(),ee("source",{key:r.thumbnailSrcPosterWebp,ref:h=>r.setMediaRef(h),srcset:r.thumbnailSrcPosterWebp,type:"image/webp"},null,8,Wh)):fe("",!0),(Z(),ee("img",{key:r.thumbnailSrcPoster,ref:h=>r.setMediaRef(h,"thumbnail"),src:r.thumbnailSrcPoster,alt:r.alt,loading:r.loading||"eager",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),onError:e[0]||(e[0]=h=>r.loadError(h,"thumbnail")),onLoad:e[1]||(e[1]=(...h)=>r.thumbnailLoad&&r.thumbnailLoad(...h))},null,44,Yh))])):!r.background&&r.media&&!r.isVideo&&!r.isAudio?(Z(),ee("picture",jh,[r.thumbnailSrcWebp?(Z(),ee("source",{key:r.thumbnailSrcWebp,ref:h=>r.setMediaRef(h),srcset:r.thumbnailSrcWebp,type:"image/webp"},null,8,qh)):fe("",!0),r.thumbnailSrc?(Z(),ee("img",{key:r.thumbnailSrc,ref:h=>r.setMediaRef(h,"thumbnail"),src:r.thumbnailSrc,alt:r.alt,loading:r.loading||"eager",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),onError:e[2]||(e[2]=h=>r.loadError(h,"thumbnail")),onLoad:e[3]||(e[3]=(...h)=>r.thumbnailLoad&&r.thumbnailLoad(...h))},null,44,zh)):(Z(),ee("img",{key:"empty",src:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",alt:r.alt},null,8,Xh))])):fe("",!0)])):fe("",!0),r.background?(Z(),ee("div",{key:(r.src||"")+"background",style:Le({background:`url(${r.src})`,backgroundSize:r.objectFit||"contain",width:"100%"}),class:"picture"},null,4)):fe("",!0),!r.background&&r.srcPoster?Yt((Z(),ee("picture",{key:r.srcPoster+"poster"},[r.posterWebpEnabled&&r.srcPosterWebp?(Z(),ee("source",{key:r.srcPosterWebp,ref:h=>r.setMediaRef(h),srcset:r.srcPosterWebp,type:"image/webp"},null,8,Qh)):fe("",!0),(Z(),ee("img",{key:r.srcPoster,ref:h=>r.setMediaRef(h,"poster"),src:r.srcPoster,alt:r.alt,loading:r.loading||"auto",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),onError:e[4]||(e[4]=h=>r.loadError(h,"poster")),onLoad:e[5]||(e[5]=(...h)=>r.load&&r.load(...h))},null,44,Jh))])),[[jt,!r.mediaLoaded]]):fe("",!0),Wt(a,null,{default:ft(()=>[r.media&&r.isAudio?(Z(),ee("audio",{ref:"audio",key:(r.src||"")+"audio",autoplay:r.autoplay,loop:r.loop,playsinline:r.playsinline,muted:r.muted,controls:r.controls,alt:r.alt,loading:r.loading||"auto",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),crossorigin:"anonymous",onError:e[6]||(e[6]=h=>r.loadError(h,"audio")),onLoadeddata:e[7]||(e[7]=(...h)=>r.loadeddata&&r.loadeddata(...h)),onPlaying:e[8]||(e[8]=(...h)=>r.playing&&r.playing(...h)),onMousedown:e[9]||(e[9]=(...h)=>r.mousedown&&r.mousedown(...h)),onPlay:e[10]||(e[10]=h=>r.$emit("play",h)),onTimeupdate:e[11]||(e[11]=h=>r.$emit("timeupdate",h))},[r.src?(Z(),ee("source",{key:r.src,ref:h=>r.setMediaRef(h,"audio"),src:r.src+r.mediaFragment,type:r.src.endsWith(".mp3")?"audio/mp3":r.media.mime},null,8,ec)):fe("",!0)],44,Zh)):!r.background&&r.media&&r.isVideo?Yt((Z(),ee("video",{key:(r.hlsSupportedNativelySrc||r.src||"")+"video",ref:"video",width:r.media.width,height:r.media.height,autoplay:r.autoplay,loop:r.loop,playsinline:r.playsinline,muted:r.muted,controls:r.controls,alt:r.alt,poster:r.webpSupported&&r.posterWebpEnabled&&r.srcPosterWebp?r.srcPosterWebp:r.srcPoster,loading:r.loading||"auto",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),crossorigin:"anonymous",onError:e[13]||(e[13]=h=>r.loadError(h,"video")),onLoadeddata:e[14]||(e[14]=(...h)=>r.loadeddata&&r.loadeddata(...h)),onPlaying:e[15]||(e[15]=(...h)=>r.playing&&r.playing(...h)),onMousedown:e[16]||(e[16]=(...h)=>r.mousedown&&r.mousedown(...h)),onPlay:e[17]||(e[17]=h=>r.$emit("play",h)),onTimeupdate:e[18]||(e[18]=h=>r.$emit("timeupdate",h))},[!r.srcHls&&r.srcWebm?(Z(),ee("source",{key:r.srcWebm,ref:h=>r.setMediaRef(h,"video"),src:r.srcWebm+r.mediaFragment,type:r.srcWebm.endsWith(".mp4")?"video/mp4":r.srcWebm.endsWith(".webm")?"video/webm":r.media.mime},null,8,ic)):fe("",!0),(!r.srcHls||r.hlsSupportedNativelySrc)&&(r.hlsSupportedNativelySrc||r.src)?(Z(),ee("source",{key:r.hlsSupportedNativelySrc||r.src,ref:h=>r.setMediaRef(h),src:(r.hlsSupportedNativelySrc||r.src)+r.mediaFragment,type:r.hlsSupportedNativelySrc?void 0:r.src.endsWith(".mp4")?"video/mp4":r.media.mime},null,8,sc)):fe("",!0),r.subtitles?(Z(),ee("track",{key:2,ref:"subtitles",src:r.subtitles.url,kind:"chapters",default:"",onLoad:e[12]||(e[12]=(...h)=>
27r.subtitlesLoad&&r.subtitlesLoad(...h))},null,40,rc)):fe("",!0)],44,tc)),[[jt,r.mediaLoaded]]):!r.background&&r.media&&!r.isVideo?(Z(),ee("picture",nc,[r.srcWebp?(Z(),ee("source",{key:r.srcWebp,ref:h=>r.setMediaRef(h),srcset:r.srcWebp,type:"image/webp"},null,8,ac)):fe("",!0),r.src?(Z(),ee("img",{key:r.src,ref:h=>r.setMediaRef(h,"load"),src:r.src,alt:r.alt,loading:r.loading||"auto",style:Le(r.xOffset||r.yOffset?`object-position: ${50+(r.xOffset||0)}% ${50+(r.yOffset||0)}%;`:void 0),onError:e[19]||(e[19]=(...h)=>r.loadError&&r.loadError(...h)),onLoad:e[20]||(e[20]=(...h)=>r.load&&r.load(...h))},null,44,oc)):(Z(),ee("img",{key:"empty",src:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",alt:r.alt},null,8,lc))])):r.media?fe("",!0):(Z(),ee("div",hc))]),_:1})],6),[[jt,r.loaded||!r.transition]])]),_:1},8,["name","duration"])],4)]),_:1},8,["enabled"])]),_:1},8,["onResize"])}const yc=fn(Hh,[["render",cc]]);export{$h as Q,yc as _};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.