@meshstream/p2p-web 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters.js +1 -1
- package/dist/advanced.js +1 -1
- package/dist/config.d.ts +2 -0
- package/dist/hls.d.ts +7 -0
- package/dist/index.js +1 -1
- package/dist/player.d.ts +13 -0
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/advanced.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,s)=>function(){if(s)throw s[0];try{return e&&(t=(0,e[r(e)[0]])(e=0)),t}catch(e){throw s=[e],e}},l=(e,t)=>function(){try{return t||(0,e[r(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},h=(e,t)=>{for(var i in t)s(e,i,{get:t[i],enumerable:!0})},d=(e,o,l)=>(l=null!=e?t(n(e)):{},((e,t,n,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of r(t))a.call(e,n)||void 0===n||s(e,n,{get:()=>t[n],enumerable:!(o=i(t,n))||o.enumerable});return e})(!o&&e&&e.__esModule?l:s(l,"default",{value:e,enumerable:!0}),e));function c(e,t){return v(e).length>0||"function"==typeof t}function u(e,t,s){if(c(e,t))return async(i,r,n,a)=>{if(!function(e,t){if(!e||!t)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}(i,s))return;const o=new Headers,l=a??r;l&&o.set("Range",`bytes=${l.start}-${l.end??""}`);for(const[s,r]of p(e,t,i))try{o.set(s,r)}catch{}return new Request(i,{method:"GET",headers:o,signal:n})}}function f(e,t,s){if(!c(t,s))return;const i=e.xhrSetup;e.xhrSetup=(e,r)=>{i?.(e,r);for(const[i,n]of p(t,s,r))try{e.setRequestHeader(i,n)}catch{}}}function g(e,t,s,i=m(s)){const r={};for(const[t,s]of v(e))r[t]=s;try{for(const[e,n]of v(t?.({url:s,kind:i})))r[e]=n}catch{}return r}function m(e){const t=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.split("?",1)[0]?.toLowerCase()??""}})();return/\.(m3u8|mpd)$/.test(t)?"manifest":/\.(key|lic)$/.test(t)?"key":/\.(mp4|mp3)$/.test(t)?"direct-file":/\.(ts|m4s|m4a|aac|mp4a|cmfv|cmfa|webm)$/.test(t)?"segment":"unknown"}function p(e,t,s,i=m(s)){return v(g(e,t,s,i))}function v(t){return Object.entries(t??{}).filter(([t,s])=>{const i=t.trim().toLowerCase();return i&&s.trim()&&!e.has(i)&&!i.startsWith("proxy-")})}var y,S,E=o({"src/origin-headers.ts"(){e=new Set(["connection","content-length","host","proxy-connection","range","transfer-encoding","upgrade"])}});function b(e,t,s={}){const i=t??{mode:"none"},r=i.mode?.trim()||"none";if("signed-url"!==r)return{mode:r,status:"none"};let n;try{n=new URL(e)}catch{return{mode:r,status:"invalid-url"}}const a=T(n,i.signatureQueryKeys??y);if(!a)return{mode:r,status:"missing-signature"};const o=T(n,i.expiresQueryKeys??S),l=o?Number(n.searchParams.get(o)):void 0,h=Number.isFinite(l)?l:void 0;if(o&&void 0!==h){const e=Math.floor((s.nowSeconds??(()=>Date.now()/1e3))());if(h+("number"==typeof(d=i.clockSkewSeconds)&&Number.isFinite(d)?Math.max(0,Math.min(3600,Math.floor(d))):0)<e)return{mode:r,status:"expired-url",signatureKey:a,expiresKey:o,expiresAtSeconds:h}}var d;return{mode:r,status:"valid",signatureKey:a,expiresKey:o,expiresAtSeconds:h}}function T(e,t){return t.map(e=>e.trim()).find(t=>t&&e.searchParams.has(t))}var w=o({"src/playback-auth.ts"(){y=["token","signature","sign","auth_key"],S=["expires","expire","exp","e"]}});function I(e,t,s,i,r,n,a){const o=[...new Set((t?.length?t:e?[e]:[]).map(e=>e?.trim()).filter(e=>Boolean(e)))];if(!o.length)return[];const l=n?.trim(),h=l&&o.includes(l)?l:o.reduce((e,t)=>U(s??"",i,t)>U(s??"",i,e)?t:e);return[h,...o.filter(e=>e!==h)].map(e=>L(C(e,{appId:s,keyId:r,...a}),"tracker")).filter(e=>Boolean(e?.trim()))}function L(e,t){if(!e)return;if("undefined"==typeof window)return e;const{protocol:s,hostname:i}=window.location;if(!["localhost","127.0.0.1","::1"].includes(i))return e;try{const r=new URL(e);if(!A(r.hostname))return e;if("https:"===s){const e=new URL(window.location.origin);return e.pathname="tracker"===t?r.pathname&&"/"!==r.pathname?r.pathname:"/tracker":"/events/v1/events/reports",e.search=r.search,e.hash="",e.toString()}return r.hostname=i,r.toString()}catch{return e}}function A(e){const t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(!t||"localhost"===t||"::1"===t||t.endsWith(".local"))return!0;if(/^\d{1,3}(?:\.\d{1,3}){3}$/.test(t)){const e=t.split(".").map(Number);return 10===e[0]||127===e[0]||172===e[0]&&e[1]>=16&&e[1]<=31||192===e[0]&&168===e[1]||169===e[0]&&254===e[1]}return!t.includes(".")}function k(e){return L(e,"report")}function R(e){if(e)try{const t=new URL(e);return t.protocol="wss:"===t.protocol?"https:":"http:",t.pathname="/reports",t.search="",t.hash="",t.toString()}catch{return}}function C(e,t){if(!e)return;const s=[["app_id",t.appId],["key_id",t.keyId],["platform","web"],["live_window_bucket",t.liveWindowBucket]].filter(([,e])=>e?.trim());if(!s.length)return e;try{const t=new URL(e);for(const[e,i]of s)t.searchParams.set(e,i.trim());return t.toString()}catch{return e}}function P(e){return`url-v1-${N(function(e){const t=e.trim();try{const e=new URL(t);e.hash="";const s=e.protocol.toLowerCase(),i=e.hostname.toLowerCase(),r="http:"===s&&"80"===e.port||"https:"===s&&"443"===e.port?"":e.port?`:${e.port}`:"",n=[...e.searchParams.entries()].filter(([e])=>!function(e){const t=e.toLowerCase();return["token","sign","signature","expires","expire","exp","e","auth","auth_key","authkey","key","policy","x-amz-signature","x-amz-expires","x-amz-date","x-amz-credential","x-amz-algorithm","x-amz-security-token","x-oss-signature","x-oss-expires","x-oss-date","x-oss-credential","x-oss-security-token","x-goog-signature","x-goog-expires","x-goog-date","x-goog-credential","x-goog-algorithm"].includes(t)||t.startsWith("x-amz-")||t.startsWith("x-oss-")||t.startsWith("x-goog-")}(e)).sort(([e,t],[s,i])=>e===s?t.localeCompare(i):e.localeCompare(s)),a=n.length?`?${new URLSearchParams(n).toString()}`:"";return`${s}//${i}${r}${e.pathname}${a}`}catch{return t.split("#",1)[0]?.trim()??t}}(e))}`}function D(e){return`content-v1-${N(e.trim())}`}function M(e,t){return e?.trim()?D(e):P(t)}function _(e){const t=e.trim();try{const e=new URL(t);return e.search="",e.hash="",e.toString()}catch{return t.split(/[?#]/,1)[0]?.trim()??t}}function O(e,t){const s=B(t);return Number($(e)%BigInt(s))}function x(e,t,s){const i=B(t);return`${e}-b${(Math.floor(Number.isFinite(s)?s:0)%i+i)%i}`}function F(e,t,s=1,i){const r=B(s);return x(P(e),r,i??O(t,r))}function B(e){return Number.isFinite(e)?Math.max(1,Math.min(4096,Math.floor(e))):1}function U(e,t,s){let i=0xcbf29ce484222325n;for(const r of(new TextEncoder).encode(`${e}\0${t}\0${s}`))i^=BigInt(r),i=BigInt.asUintN(64,0x100000001b3n*i);return i}function N(e){return $(e).toString(36)}function $(e){let t=0xcbf29ce484222325n;for(const s of(new TextEncoder).encode(e))t^=BigInt(s),t=1099511628211n*t&18446744073709551615n;return t}var G,H,W=o({"src/url.ts"(){}});function q(e){return{httpDownloaded:e?.httpDownloaded??0,p2pDownloaded:e?.p2pDownloaded??0,p2pUploaded:e?.p2pUploaded??0,httpSegmentDownloadSuccesses:e?.httpSegmentDownloadSuccesses??0,httpSegmentDownloadFailures:e?.httpSegmentDownloadFailures??0,p2pSegmentDownloadSuccesses:e?.p2pSegmentDownloadSuccesses??0,p2pSegmentDownloadFailures:e?.p2pSegmentDownloadFailures??0,p2pSegmentUploadSuccesses:e?.p2pSegmentUploadSuccesses??0,p2pSegmentUploadFailures:e?.p2pSegmentUploadFailures??0,connectedPeers:e?.connectedPeers??0,peerConnectErrors:e?.peerConnectErrors??0,trackerErrors:e?.trackerErrors??0,p2pAttempts:e?.p2pAttempts??0,httpAttempts:e?.httpAttempts??0,p2pErrors:e?.p2pErrors??0,httpErrors:e?.httpErrors??0,lastLoadedBytes:e?.lastLoadedBytes??0}}function j(e){return Number.isFinite(e)?Math.max(H,Math.min(3e5,Math.floor(e))):G}function K(e){return j(e)+Math.floor(10001*Math.random())}function V(e,t=!0){const s={firstPeerConnectMs:e.diagnostics.firstPeerConnectMs,...e.diagnostics.coldStart?{coldStart:{...e.diagnostics.coldStart}}:{},...e.diagnostics.liveLatency?{liveLatency:{...e.diagnostics.liveLatency}}:{},...e.diagnostics.liveSeed?{liveSeed:{...e.diagnostics.liveSeed}}:{},fallbackCount:e.diagnostics.fallbackCount,lastTrackerError:e.diagnostics.lastTrackerError,lastPeerError:e.diagnostics.lastPeerError,lastErrorAtMs:e.diagnostics.lastErrorAtMs,...t&&e.diagnostics.playbackAuth?{playbackAuth:e.diagnostics.playbackAuth}:{},...e.diagnostics.ice?{ice:{...e.diagnostics.ice}}:{},...e.diagnostics.auth?{auth:{...e.diagnostics.auth}}:{},...e.diagnostics.websocket?{websocket:{...e.diagnostics.websocket}}:{}},i=JSON.stringify({playbackMode:e.playbackMode,stats:e.stats,load:t?e.load:{activeUploadPeers:e.load.activeUploadPeers,activeDownloadPeers:e.load.activeDownloadPeers},diagnostics:s});return{reportType:"stats",reportId:`${e.sessionId}-${Y(i)}`,reportSeq:e.stats.httpDownloaded+e.stats.p2pDownloaded+e.stats.p2pUploaded,reportedAtMs:Date.now(),platform:e.platform,playbackMode:e.playbackMode,appId:e.appId?.trim()||void 0,keyId:e.keyId?.trim()||void 0,sessionId:e.sessionId,stats:e.stats,load:t?e.load:{activeUploadPeers:e.load.activeUploadPeers,activeDownloadPeers:e.load.activeDownloadPeers},diagnostics:s,...t?{protocol:e.protocol,playerType:e.playerType,runtimeMode:e.runtimeMode,sdkVersion:e.sdkVersion,contentId:e.contentId?.trim()||void 0,swarmId:e.swarmId,playbackUrl:_(e.playbackUrl),capability:e.capability}:{}}}function Y(e){let t=14695981039346656037n;for(let s=0;s<e.length;s+=1)t^=BigInt(e.charCodeAt(s)),t=BigInt.asUintN(64,1099511628211n*t);return t.toString(36)}async function z(e,t,s={}){const i=e?.trim();if(!i)return;const r={"Content-Type":"application/json"};return s.authorizationHeader?.trim()&&(r.Authorization=s.authorizationHeader.trim()),(s.fetcher??fetch)(i,{method:"POST",headers:r,keepalive:!0,body:JSON.stringify(t)})}var Q,X,J=o({"src/report.ts"(){W(),G=3e4,H=2e4}}),Z=o({"src/version.ts"(){Q="1.0.4"}});function ee(){return[{urls:[...X]}]}var te,se,ie,re=o({"src/ice.ts"(){X=Object.freeze(["stun:stun.cloudflare.com:3478","stun:stun.l.google.com:19302"])}});function ne(e){return new ie}function ae(e,t){return`${e}:${t}`}function oe(e){return Number.isFinite(e)?Math.max(0,Math.min(120,e)):se}var le,he,de,ce,ue,fe,ge,me,pe,ve,ye,Se,Ee,be,Te,we,Ie,Le,Ae,ke,Re,Ce,Pe,De,Me,_e,Oe,xe,Fe,Be,Ue,Ne,$e,Ge,He,We,qe,je,Ke,Ve,Ye,ze,Qe,Xe,Je,Ze,et,tt,st,it,rt,nt,at,ot,lt,ht,dt,ct,ut,ft,gt,mt,pt,vt,yt,St,Et,bt,Tt,wt,It,Lt,At,kt,Rt,Ct,Pt,Dt,Mt=o({"src/segment-storage.ts"(){te=1048576,se=15,ie=class{limitBytes=100663296;usedBytes=0;mainLiveRetentionSeconds=se;secondaryLiveRetentionSeconds=se;playbackPosition;cache=new Map;segmentChangeCallback;async initialize(e,t,s){const i=e.segmentMemoryStorageLimit,r="number"==typeof i&&Number.isFinite(i)&&i>0?i:96;this.limitBytes=Math.floor(r*te),this.mainLiveRetentionSeconds=oe(t.highDemandTimeWindow),this.secondaryLiveRetentionSeconds=oe(s.highDemandTimeWindow)}onPlaybackUpdated(e,t){Number.isFinite(e)&&(this.playbackPosition=e,this.notifyChanged(this.trimExpiredLiveSegments()))}onSegmentRequested(e,t,s,i,r,n,a){}async storeSegment(e,t,s,i,r,n,a,o){const l=ae(t,s),h=this.cache.get(l);var d;h&&(this.usedBytes-=h.data.byteLength,this.cache.delete(l)),this.cache.set(l,{streamId:t,segmentId:s,data:i,endTime:(d=n,Number.isFinite(d)?d:0),streamType:a,isLive:o}),this.usedBytes+=i.byteLength;const c=this.trimExpiredLiveSegments();for(const e of this.trimToLimit())c.add(e);c.add(t),this.notifyChanged(c),this.publishDebugSnapshot()}async getSegmentData(e,t,s){const i=ae(t,s),r=this.cache.get(i);if(r)return this.cache.delete(i),this.cache.set(i,r),r.data}getUsage(){return{totalCapacity:this.limitBytes/te,usedCapacity:this.usedBytes/te}}hasSegment(e,t,s){return this.cache.has(ae(t,s))}getStoredSegmentIds(e,t){return[...this.cache.values()].filter(e=>e.streamId===t).map(e=>e.segmentId).sort((e,t)=>e-t)}setSegmentChangeCallback(e){this.segmentChangeCallback=e}destroy(){this.cache.clear(),this.usedBytes=0,this.playbackPosition=void 0,this.segmentChangeCallback=void 0,this.publishDebugSnapshot()}trimToLimit(){const e=new Set;for(;this.usedBytes>this.limitBytes&&this.cache.size>1;){const t=this.cache.entries().next();if(t.done)break;const[s,i]=t.value;this.cache.delete(s),this.usedBytes-=i.data.byteLength,e.add(i.streamId)}return e}trimExpiredLiveSegments(){const e=new Set,t=this.playbackPosition;if(void 0===t)return e;for(const[s,i]of this.cache)!i.isLive||t<=i.endTime+this.liveRetentionSeconds(i.streamType)||(this.cache.delete(s),this.usedBytes-=i.data.byteLength,e.add(i.streamId));return e}liveRetentionSeconds(e){return"secondary"===e?this.secondaryLiveRetentionSeconds:this.mainLiveRetentionSeconds}notifyChanged(e){for(const t of e)this.segmentChangeCallback?.(t)}publishDebugSnapshot(){const e=globalThis;if(!e.__MESHSTREAM_DEBUG_SEGMENT_STORAGE__)return;const t={};for(const e of this.cache.values())t[e.streamId]??=[],t[e.streamId].push(e.segmentId);for(const e of Object.values(t))e.sort((e,t)=>e-t);e.__meshStreamSegmentStorageSnapshot={totalCapacityMiB:this.limitBytes/te,usedCapacityMiB:this.usedBytes/te,streams:t}}}}}),_t={};function Ot(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}function xt(e){Promise.resolve().then(e)}function Ft(e,t){t??=e.reduce((e,t)=>e+t.byteLength,0);const s=new Uint8Array(t);let i=0;for(const t of e)s.set(t,i),i+=t.byteLength;return s}function*Bt(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function Ut(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Nt(e){if(function(e){return Array.isArray(e)}(e))return e.map(e=>Nt(e));if(Ut(e)){const t={};for(const s of Object.keys(e))t[s]=Nt(e[s]);return t}return e}function $t(e,t,s={}){return"object"!=typeof e||null===e||"object"!=typeof t||null===t||Object.keys(t).forEach(i=>{const r="symbol"==typeof i?i.toString():String(i);if("__proto__"===i||"constructor"===i||"prototype"===i)throw new Error(`Attempt to modify restricted property '${r}'`);const n=t[i],a=s[i];i in e&&(e[i]=void 0===n?void 0===a?void 0:a:n)}),e}function Gt(e){const{defaultConfig:t,baseConfig:s={},specificStreamConfig:i={}}=e,r=Nt({...t,...s,...i}),n=Object.keys(t),a={};return n.forEach(e=>{e in r&&(a[e]=r[e])}),a}function Ht(e){const t=e.length,s=(e,s)=>{const i=8*(t-1-s);return e*Math.pow(2,i)};let i=s(127&e[0],0);for(let r=1;r<t;r++)i+=s(e[r],r);return(128&e[0])>>7&&(i=-i),i}function Wt(e){const t=function(e){const t=e<0,s=function(e){if(0===e)return 1;const t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}(e),i=new Uint8Array(s);e=Math.abs(e);for(let t=0;t<s;t++){const r=8*(s-1-t);i[t]=255&Math.floor(e/Math.pow(2,r))}return t&&(i[0]=128|i[0]),i}(e),s=0|t.length;return new Uint8Array([s,...t])}function qt(e){if(0===e.length)throw new Error("Buffer is too short");const t=e[0];if(t>>4)throw new Error("Trying to deserialize integer with invalid serialized item code");const s=15&t;if(0===s)throw new Error("Invalid integer: zero byte length");if(s>7)throw new Error("Invalid integer: byte length exceeds safe integer limit");const i=1+s;if(e.length<i)throw new Error("Buffer is too short");return{number:Ht(e.subarray(1,i)),byteLength:s+1}}function jt(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!=1)throw new Error("Trying to deserialize similar int array with invalid serialized item code");let i=2;const r=[];for(let t=0;t<s;t++){const{number:t,byteLength:s}=qt(e.subarray(i));i+=s;const n=255&t,a=0===n?256:n,o=t-n;if(i+a>e.length)throw new Error("Malformed similar int array: buffer too short");for(let t=0;t<a;t++){const t=e[i];r.push(o+t),i++}}return{numbers:r,byteLength:i}}function Kt(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!=2)throw new Error("Trying to deserialize bytes (sting) with invalid serialized item code.");const i=(15&t)<<8|s;if(e.length<i+2)throw new Error("Malformed string: buffer too short");const r=e.subarray(2,i+2);return{string:Be.decode(r),byteLength:i+2}}function Vt(e){if(e.length<Ve)return!1;const{length:t}=Ge,s=e.subarray(-t);return je.some(t=>Jt(e,t,$e))&&Ke.some(e=>Jt(s,e,$e))}function Yt(e){const[t]=e,s={c:t};let i=1;for(;i<e.length;){if(i+1>=e.length)throw new Error("Malformed command buffer: truncated name/type header");const t=String.fromCharCode(e[i]);switch(i++,zt(e[i])){case Ue.Int:{const{number:r,byteLength:n}=qt(e.subarray(i));s[t]=r,i+=n}break;case Ue.SimilarIntArray:{const{numbers:r,byteLength:n}=jt(e.subarray(i));s[t]=r,i+=n}break;case Ue.String:{const{string:r,byteLength:n}=Kt(e.subarray(i));s[t]=r,i+=n}}}return function(e){switch(e.c){case xe.SegmentsAnnouncement:return e;case xe.SegmentRequest:return Zt(e,"i","r"),e;case xe.SegmentData:return Zt(e,"i","r","s"),e;case xe.SegmentAbsent:case xe.CancelSegmentRequest:case xe.SegmentDataSendingCompleted:return Zt(e,"i","r"),e;default:throw new Error(`Unknown peer command type: ${String(e.c)}`)}}(s)}function zt(e){const t=e>>4;if(t<=Ue.Min||t>=Ue.Max)throw new Error("Not existing type");return t}function Qt(e,t){if(t&&e.length!==t)throw new Error("Wrong string length");const s=new Uint8Array(t??e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Xt(e,t,s){const i=new Uint8Array(e.length+t.length+s.length);return i.set(t),i.set(e,t.length),i.set(s,t.length+e.length),i}function Jt(e,t,s){for(let i=0;i<s;i++)if(e[i]!==t[i])return!1;return!0}function Zt(e,...t){for(const s of t)if("number"!=typeof e[s])throw new Error(`Expected number field "${s}", got ${typeof e[s]}`)}function es(e,t){switch(e.c){case xe.CancelSegmentRequest:case xe.SegmentAbsent:case xe.SegmentDataSendingCompleted:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t);case xe.SegmentRequest:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),e.b&&s.addInteger("b",e.b),s.complete(),s.getResultBuffers()}(e,t);case xe.SegmentsAnnouncement:return function(e,t){const{c:s,p:i,l:r}=e,n=new Qe(s,t);return r?.length&&n.addUniqueSimilarIntArr("l",r),i?.length&&n.addUniqueSimilarIntArr("p",i),n.complete(),n.getResultBuffers()}(e,t);case xe.SegmentData:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("s",e.s),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t)}}function ts(e,t="RTC error"){return function(e,t="RTC error"){const s=e;if(s.error instanceof Error)return s.error;const i=s.error?.message??t;return new Error(i)}(e,t).message}function ss(e){return"failed"===e||"closed"===e||"disconnected"===e}function is(e,t){return lt?e.setLocalDescription(t):new Promise((s,i)=>{try{e.setLocalDescription(t,s,i)}catch(e){i(e)}})}function rs(e,t){return lt?e.setRemoteDescription(t):new Promise((s,i)=>{try{e.setRemoteDescription(t,s,i)}catch(e){i(e)}})}function ns(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&ht.has(t.type)&&"string"==typeof t.sdp}function as(e){const t=(s=e,(new TextEncoder).encode(s));var s;const i=[],r=8*t.length;for(let e=0;e<t.length;e++)i[e>>2]|=(255&t[e])<<24-e%4*8;i[r>>5]|=128<<24-r%32,i[15+(r+64>>9<<4)]=r;let n=1732584193,a=4023233417,o=2562383102,l=271733878,h=3285377520;const d=[];for(let e=0;e<i.length;e+=16){const t=n,s=a,r=o,c=l,u=h;for(let t=0;t<80;t++){if(t<16)d[t]=0|i[e+t];else{const e=d[t-3]^d[t-8]^d[t-14]^d[t-16];d[t]=e<<1|e>>>31}let s;s=t<20?1518500249+(a&o|~a&l):t<40?1859775393+(a^o^l):t<60?(a&o|a&l|o&l)-1894007588:(a^o^l)-899497514;const r=(n<<5|n>>>27)+h+(d[t]>>>0)+s|0;h=l,l=o,o=a<<30|a>>>2,a=n,n=r}n=n+t|0,a=a+s|0,o=o+r|0,l=l+c|0,h=h+u|0}let c="";const u=[n,a,o,l,h];for(let e=0;e<20;e++){const t=24-e%4*8,s=u[e>>2];c+=String.fromCharCode(s>>>t&255)}return c}function os({bitrate:e,codecs:t,width:s,height:i,language:r,channels:n,name:a,frameRate:o,videoRange:l}){const h=t?t.split(",").map(e=>{const t=(e=e.trim().toLowerCase()).split(".");if(3===t.length&&("avc1"===t[0]||"avc"===t[0])){const s=parseInt(t[1],10),i=parseInt(t[2],10);if(!isNaN(s)&&!isNaN(i)&&t[1]===s.toString()&&t[2]===i.toString()){const r=`00${s.toString(16)}`.slice(-2),n=`00${i.toString(16)}`.slice(-2);e=`${t[0]}.${r}00${n}`}}return e}).sort().join(","):"",d=r&&"und"!==r?r.slice(0,2).toLowerCase():"",c=n?n.toString().split("/")[0]:"",u=a?a.toLowerCase().trim():"",f=o&&!isNaN(Number(o))?Number(o).toString():"",g=l?l.toUpperCase().trim():"";return btoa(as(`${e??0}-${h}-${s??""}-${i??""}-${d}-${c}-${u}-${f}-${g}`))}function ls(e,t){return`${ut}-${e}-${function(e){return`${e.type}-${e.index}`}(t)}`}function hs(e,t){for(const s of e.values()){const e=s.segments.get(t);if(e)return e}}function ds(e,t,s,i,r){const{highDemandTimeWindow:n,httpDownloadTimeWindow:a,p2pDownloadTimeWindow:o}=function(e,t){const{highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r}=e,n={highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r};return t<=5?(n.httpDownloadTimeWindow=0,n.p2pDownloadTimeWindow=0):t<=10&&(n.p2pDownloadTimeWindow=n.httpDownloadTimeWindow),n}(s,r);return{isHighDemand:cs(e,t,n),isHttpDownloadable:cs(e,t,a),isP2PDownloadable:cs(e,t,o)&&i.isSegmentLoadingOrLoadedBySomeone(e)}}function cs(e,t,s){const{startTime:i,endTime:r}=e,{position:n,rate:a}=t;return!(n+s*a<i||n>r)}function us(e){return btoa(as(e).slice(0,15))}function fs(e){if(1===e.length)return e[0];let t=0;for(const s of e){const e=s.getDownloadBandwidth();e>t&&(t=e)}if(t>0){const s=Math.max(1,.1*t);let i=0,r=0;for(const t of e)t.getDownloadBandwidth()<=s?i++:r+=t.getDownloadBandwidth();let n=s;return i>0&&r>0&&i*s>r&&(n=r/i),function(e){if(0===e.length)throw new Error("Cannot get item from empty array");if(1===e.length)return e[0];let t=0;const s=e.map(e=>{const s=(i=e,Math.max(i.getDownloadBandwidth(),n));var i;return t+=s,s});let i=Math.random()*t;for(let t=0;t<e.length;t++)if(i-=s[t],i<=0)return e[t];return e[e.length-1]}(e)}return(s=e)[Math.floor(Math.random()*s.length)];var s}function gs(e){return`${e.type}-${e.index}`}function ms(e){const{externalId:t}=e;return`(${gs(e.stream)} | ${t})`}function ps(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}function*vs(e,t,s,i,r){const{runtimeId:n,stream:a}=e,o=a.segments.get(n);if(!o)return;const l=a.segments.values();let h;do{const e=l.next();if(e.done)return;h=e.value}while(h!==o);const d=ds(h,t,s,i,r);if(ys(d)){const e=l.next();if(e.done)return;const n=e.value,a=ds(n,t,s,i,r);if(ys(a))return;d.isHighDemand=!0,yield{segment:h,statuses:d},yield{segment:n,statuses:a}}else yield{segment:h,statuses:d};for(const e of l){const n=ds(e,t,s,i,r);if(ys(n))break;yield{segment:e,statuses:n}}}function ys(e){const{isHighDemand:t,isHttpDownloadable:s,isP2PDownloadable:i}=e;return!t&&!s&&!i}h(_t,{Core:()=>Pt,CoreRequestError:()=>Le,PeerConnectError:()=>we,PeerError:()=>Se,PeerWarning:()=>Ee,RequestError:()=>Ie,TrackerError:()=>be,TrackerWarning:()=>Te,TypedError:()=>ye,debug:()=>Dt,generateStreamShortId:()=>os});var Ss,Es,bs,Ts,ws,Is,Ls,As,ks,Rs,Cs,Ps,Ds,Ms,_s,Os,xs,Fs,Bs,Us,Ns,$s,Gs,Hs,Ws,qs,js,Ks,Vs,Ys,zs,Qs,Xs,Js,Zs,ei,ti,si,ii,ri,ni,ai,oi,li,hi,di,ci,ui,fi,gi,mi,pi,vi,yi,Si,Ei,bi,Ti,wi,Ii,Li,Ai,ki,Ri,Ci,Pi,Di,Mi,_i,Oi,xi,Fi,Bi,Ui,Ni,$i,Gi,Hi,Wi,qi,ji,Ki,Vi,Yi,zi,Qi,Xi,Ji,Zi,er,tr,sr,ir,rr,nr,ar,or,lr,hr,dr,cr,ur,fr,gr,mr,pr,vr,yr,Sr,Er,br,Tr,wr,Ir,Lr,Ar,kr,Rr,Cr,Pr,Dr,Mr,_r,Or,xr,Fr,Br,Ur,Nr,$r,Gr,Hr,Wr,qr,jr,Kr,Vr,Yr,zr,Qr,Xr,Jr,Zr,en,tn,sn,rn,nn,an,on,ln,hn,dn,cn,un,fn,gn,mn,pn,vn,yn,Sn,En,bn,Tn,wn,In,Ln,An,kn,Rn,Cn,Pn,Dn,Mn,_n,On,xn,Fn,Bn,Un,Nn,$n,Gn,Hn,Wn,qn,jn,Kn,Vn,Yn,zn,Qn,Xn,Jn,Zn,ea,ta,sa,ia,ra,na,aa,oa,la,ha,da,ca,ua,fa,ga,ma,pa,va,ya,Sa,Ea,ba,Ta,wa,Ia,La,Aa,ka,Ra,Ca,Pa,Da,Ma,_a,Oa,xa,Fa,Ba,Ua,Na,$a,Ga,Ha,Wa,qa,ja,Ka,Va,Ya,za,Qa,Xa,Ja,Za,eo,to,so,io,ro,no,ao,oo,lo,ho,co,uo,fo,go,mo,po,vo,yo,So,Eo,bo,To,wo,Io,Lo,Ao,ko,Ro,Co,Po,Do,Mo,_o,Oo,xo,Fo,Bo,Uo,No,$o=o({"src/vendor/meshstream-p2p-core.js"(){le=Object.create,he=Object.defineProperty,de=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyNames,ue=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty,ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),me=(e,t)=>{let s={};for(var i in e)he(s,i,{get:e[i],enumerable:!0});return t||he(s,Symbol.toStringTag,{value:"Module"}),s},pe=(e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var r,n=ce(t),a=0,o=n.length;a<o;a++)r=n[a],fe.call(e,r)||r===s||he(e,r,{get:(e=>t[e]).bind(null,r),enumerable:!(i=de(t,r))||i.enumerable});return e},ve=(e,t,s)=>(s=null!=e?le(ue(e)):{},pe(!t&&e&&e.__esModule?s:he(s,"default",{value:e,enumerable:!0}),e)),ye=class extends Error{type;cause;constructor(e,t,s){super(t),this.type=e,this.cause=s}},Se=class extends ye{name="PeerError"},Ee=class extends ye{name="PeerWarning"},be=class extends ye{name="TrackerError"},Te=class extends ye{name="TrackerWarning"},we=class extends ye{name="PeerConnectError"},Ie=class extends ye{name="RequestError";timestamp;constructor(e,t,s){super(e,t,s),this.timestamp=performance.now()}},Le=class extends ye{name="CoreRequestError"},Ae=class{aborted=!1;#e=new Set;addEventListener(e,t){this.#e.add(t)}removeEventListener(e,t){this.#e.delete(t)}dispatchEvent(e){this.aborted=!0;for(const e of this.#e)try{e()}catch{}this.#e.clear()}},ke=class{signal=new Ae;abort(){this.signal.dispatchEvent("abort")}},Re="undefined"!=typeof AbortController,Ce=Re?AbortController:ke,Pe=class{request;httpConfig;abortController=new Ce;expectedBytesLength;requestByteRange;onChunkDownloaded;isAborted(){return this.abortController.signal.aborted}constructor(e,t,s){this.request=e,this.httpConfig=t,this.onChunkDownloaded=s.getEventDispatcher("onChunkDownloaded");const{byteRange:i}=this.request.segment;i&&(this.requestByteRange={...i})}execute(){const e={onAbort:()=>this.abortController.abort(),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs};if(this.request.tryCompleteByLoadedBytes({downloadSource:"http"},e,this.httpConfig.validateHTTPSegment,"http-segment-validation-failed"))return;0!==this.request.loadedBytes&&(this.requestByteRange=this.requestByteRange??{start:0},this.requestByteRange.start=this.requestByteRange.start+this.request.loadedBytes),this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes);const t=this.request.start({downloadSource:"http"},e);this.fetch(t)}async fetch(e){const{segment:t}=this.request;let s;if(this.isAborted())return;const i=()=>{try{s?.cancel().catch(()=>{})}catch{}};this.abortController.signal.addEventListener("abort",i);const r=Re?this.abortController.signal:void 0;try{let i=await(this.httpConfig.httpRequestSetup?.(t.url,t.byteRange,r,this.requestByteRange));if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!i){const e=new Headers;this.requestByteRange&&e.set("Range",`bytes=${this.requestByteRange.start}-${this.requestByteRange.end??""}`);const s={headers:e};r&&(s.signal=r),i=new Request(t.url,s)}if(this.isAborted())throw new DOMException("Request aborted before request fetch","AbortError");const n=await window.fetch(i);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(this.handleResponseHeaders(n),e.firstBytesReceived(),n.body&&"function"==typeof n.body.getReader){const i=n.body.getReader();for(s=i;;){if(this.isAborted())throw new DOMException("Request aborted","AbortError");const{done:s,value:r}=await i.read();if(s)break;if(this.isAborted())throw new DOMException("Request aborted","AbortError");e.addLoadedChunk(r),this.onChunkDownloaded(r.byteLength,"http",void 0,t.stream.type,this.request.infoHash)}}else{const s=await n.arrayBuffer();if(this.isAborted())throw new DOMException("Request aborted","AbortError");const i=new Uint8Array(s);e.addLoadedChunk(i),this.onChunkDownloaded(i.byteLength,"http",void 0,t.stream.type,this.request.infoHash)}if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(void 0!==this.request.totalBytes&&this.request.loadedBytes!==this.request.totalBytes)throw new Ie("http-bytes-mismatch",`HTTP response truncated: received ${this.request.loadedBytes} of ${this.request.totalBytes} bytes`);const a=await this.request.validateData(this.httpConfig.validateHTTPSegment);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!a)throw this.request.clearLoadedBytes(),new Ie("http-segment-validation-failed");e.completeOnSuccess()}catch(t){this.handleError(t,e)}finally{this.abortController.signal.removeEventListener("abort",i)}}handleResponseHeaders(e){if(!e.ok)throw 406===e.status||416===e.status?(this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText)):new Ie("http-error",e.statusText);const{requestByteRange:t}=this;if(t)if(200===e.status){if(this.request.segment.byteRange)throw new Ie("http-unexpected-status-code");this.request.clearLoadedBytes()}else{if(206!==e.status)throw new Ie("http-unexpected-status-code",e.statusText);const s=e.headers.get("Content-Length");if(s&&void 0!==this.expectedBytesLength&&this.expectedBytesLength!==+s)throw this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText);const i=e.headers.get("Content-Range"),r=i?function(e){const t=De.exec(e.trim());if(!t)return;const[,s,i,r]=t;return{from:s?parseInt(s):void 0,to:i?parseInt(i):void 0,total:r?parseInt(r):void 0}}(i):void 0;if(r){const{from:s,to:i}=r,n=void 0!==i&&void 0!==s?i-s+1:void 0;if(void 0!==n&&this.expectedBytesLength!==n||void 0!==s&&t.start!==s||void 0!==i&&void 0!==t.end&&t.end!==i)throw this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText)}}if(200===e.status&&void 0===this.request.totalBytes){const t=e.headers.get("Content-Length");t&&this.request.setTotalBytes(+t)}}handleError(e,t){if(!this.isAborted()&&e instanceof Error){const s=e instanceof Ie?e:new Ie("http-error",e.message);t.failWithError(s)}}},De=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/,Me=ge((e,t)=>{var s=1e3,i=60*s,r=60*i,n=24*r,a=7*n;function o(e,t,s,i){var r=t>=1.5*s;return Math.round(e/s)+" "+i+(r?"s":"")}t.exports=function(e,t){t=t||{};var l,h,d=typeof e;if("string"===d&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return o*a;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*i;case"seconds":case"second":case"secs":case"sec":case"s":return o*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===d&&isFinite(e))return t.long?(l=e,(h=Math.abs(l))>=n?o(l,h,n,"day"):h>=r?o(l,h,r,"hour"):h>=i?o(l,h,i,"minute"):h>=s?o(l,h,s,"second"):l+" ms"):function(e){var t=Math.abs(e);return t>=n?Math.round(e/n)+"d":t>=r?Math.round(e/r)+"h":t>=i?Math.round(e/i)+"m":t>=s?Math.round(e/s)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),_e=ge((e,t)=>{t.exports=function(e){function t(e){let i,r,n,a=null;function o(...e){if(!o.enabled)return;const s=o,r=Number(new Date);s.diff=r-(i||r),s.prev=i,s.curr=r,i=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let n=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,r)=>{if("%%"===i)return"%";n++;const a=t.formatters[r];if("function"==typeof a){const t=e[n];i=a.call(s,t),e.splice(n,1),n--}return i}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=s,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==t.namespaces&&(r=t.namespaces,n=t.enabled(e)),n),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function s(e,s){const i=t(this.namespace+(void 0===s?":":s)+e);return i.log=this.log,i}function i(e,t){let s=0,i=0,r=-1,n=0;for(;s<e.length;)if(i<t.length&&(t[i]===e[s]||"*"===t[i]))"*"===t[i]?(r=i,n=s,i++):(s++,i++);else{if(-1===r)return!1;i=r+1,n++,s=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(i(e,s))return!1;for(const s of t.names)if(i(e,s))return!0;return!1},t.humanize=Me(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(s=>{t[s]=e[s]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}}),Oe=ve(ge((e,t)=>{e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;e.splice(1,0,s,"color: inherit");let i=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(r=i))}),e.splice(r,0,s)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=_e()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}})(),1),xe=function(e){return e[e.SegmentsAnnouncement=0]="SegmentsAnnouncement",e[e.SegmentRequest=1]="SegmentRequest",e[e.SegmentData=2]="SegmentData",e[e.SegmentDataSendingCompleted=3]="SegmentDataSendingCompleted",e[e.SegmentAbsent=4]="SegmentAbsent",e[e.CancelSegmentRequest=5]="CancelSegmentRequest",e}({}),Fe=new TextEncoder,Be=new TextDecoder("utf8"),Ue=function(e){return e[e.Min=-1]="Min",e[e.Int=0]="Int",e[e.SimilarIntArray=1]="SimilarIntArray",e[e.String=2]="String",e[e.Max=3]="Max",e}({}),Ne=class{#t=[];#s=0;push(e){this.#i(e,"end")}unshift(e){this.#i(e,"start")}#i(e,t){let s;s=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),this.#s+=s.length,this.#t["start"===t?"unshift":"push"](s)}getBytesChunks(){return this.#t}getBuffer(){return Ft(this.#t,this.#s)}get length(){return this.#s}},Ge=Qt("cstr",$e=4),He=Qt("cend",$e),We=Qt("dstr",$e),qe=Qt("dend",$e),je=[Ge,We],Ke=[He,qe],Ve=Ge.length+He.length,Ye=class extends Error{type;constructor(e){super(),this.type=e}},ze=class{#r=new Ne;#n="joining";#a;constructor(e){this.#a=e}addCommandChunk(e){if("completed"===this.#n)return;const t=!((s=e).length<Ve)&&Jt(s,Ge,$e);var s;if(!this.#r.length&&!t)throw new Ye("no-first-chunk");if(this.#r.length&&t)throw new Ye("incomplete-joining");this.#r.push(this.#o(e)),function(e){return!(e.length<Ve)&&Jt(e.subarray(-4),He,$e)}(e)&&(this.#n="completed",this.#a(this.#r.getBuffer()))}#o(e){if(e.length<Ve)throw new Error("Command chunk is too short to unframe");return e.subarray($e,e.length-$e)}},Qe=class{#t=new Ne;#l=[];#n="creating";#h;constructor(e,t){this.#h=t,this.#t.push(e)}addInteger(e,t){this.#t.push(e.charCodeAt(0));const s=Wt(t);this.#t.push(s)}addUniqueSimilarIntArr(e,t){this.#t.push(e.charCodeAt(0));const s=function(e){const t=new Map;for(const s of e){const e=255&s,i=s-e,r=t.get(i)??new Ne;r.length||t.set(i,r),r.push(e)}const s=new Ne;s.push([16,t.size]);for(const[e,i]of t){const{length:t}=i,r=e+(255&t);i.unshift(Wt(r)),s.push(i.getBuffer())}return s.getBuffer()}(t);this.#t.push(s)}addString(e,t){this.#t.push(e.charCodeAt(0));const s=function(e){const t=Fe.encode(e),{length:s}=t;if(s>4095)throw new Error("String exceeds maximum length of 4095 bytes");const i=new Ne;return i.push([32|s>>8&15,255&s]),i.push(t),i.getBuffer()}(t);this.#t.push(s)}complete(){if(!this.#t.length)throw new Error("Buffer is empty");if("completed"===this.#n)return;this.#n="completed";const e=this.#t.getBuffer();if(e.length+Ve<=this.#h)return void this.#l.push(Xt(e,Ge,He));let t=Math.ceil(e.length/this.#h);Math.ceil(e.length/t)+Ve>this.#h&&t++;for(const[s,i]of function*(e,t){const s=Math.ceil(e.length/t);for(let i=0;i<t;i++)yield[i,e.subarray(i*s,(i+1)*s)]}(e,t))0===s?this.#l.push(Xt(i,Ge,qe)):s===t-1?this.#l.push(Xt(i,We,He)):this.#l.push(Xt(i,We,qe))}getResultBuffers(){if("creating"===this.#n||!this.#l.length)throw new Error("Command is not complete.");return this.#l}},Xe=me({BinaryCommandChunksJoiner:()=>ze,BinaryCommandJoiningError:()=>Ye,PeerCommandType:()=>xe,deserializeCommand:()=>Yt,isCommandChunk:()=>Vt,serializePeerCommand:()=>es}),Je=class{channel;maxMessageSize;#d;constructor(e,t){this.channel=e,this.maxMessageSize=t}async sendData(e,t){if(this.#d)throw new Error("Already sending data");if("open"!==this.channel.readyState)throw new Error("Data channel is not open");this.channel.bufferedAmountLowThreshold=8192;const{promise:s,resolve:i,reject:r}=Ot();let n,a=0,o=!1;const l=()=>!o&&(o=!0,void 0!==n&&clearTimeout(n),this.#d=void 0,this.channel.removeEventListener("bufferedamountlow",g),this.channel.removeEventListener("closing",h),this.channel.removeEventListener("close",h),this.channel.removeEventListener("error",d),!0);this.#d={cancel:()=>{l()&&r(new Error("Send cancelled"))}};const h=()=>{l()&&r(new Error("Data channel closed"))},d=e=>{if(!l())return;const t=ts(e,"Unknown error");r(new Error(`Data channel error: ${t}`))},c=ArrayBuffer.isView(e)?e.buffer:e,u=ArrayBuffer.isView(e)?e.byteOffset:0,f=()=>{void 0===n&&(n=setTimeout(()=>{n=void 0,g()},25))},g=()=>{if(!o)if("open"===this.channel.readyState){try{for(;a<e.byteLength;){if(this.channel.bufferedAmount>=16384)return void f();const s=Math.min(this.maxMessageSize,e.byteLength-a),i=new Uint8Array(c,u+a,s);if(this.channel.send(i),a+=s,t?.(s),!this.#d)return}}catch(e){return void(l()&&r(e instanceof Error?e:new Error(String(e))))}l()&&i()}else l()&&r(new Error(`Data channel not open (state: ${this.channel.readyState})`))};return this.channel.addEventListener("bufferedamountlow",g),this.channel.addEventListener("closing",h),this.channel.addEventListener("close",h),this.channel.addEventListener("error",d),g(),s}cancel(){this.#d?.cancel()}},Ze=(0,Oe.default)("p2pml-core:peer-protocol"),et=class{#c;#u;#f;#g;#m;#p;#v;#y;#S;constructor(e,t,s,i,r){if(this.#p=e,this.#v=t,this.#y=s,this.#S=r,this.#u=new Je(e,t.webRtcMaxMessageSize),this.#g=i.getEventDispatcher("onChunkDownloaded"),this.#m=i.getEventDispatcher("onChunkUploaded"),"arraybuffer"!==e.binaryType)throw new Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener("message",this.#E)}#E=e=>{try{const t=new Uint8Array(e.data);Vt(t)?this.#b(t):(this.#y.onSegmentChunkReceived(t),this.#g(t.byteLength,"p2p",this.#S,this.#v.streamType,this.#v.infoHash))}catch(e){Ze("error handling data channel message: %O",e),this.#y.onProtocolError(e)}};sendCommand(e){if("open"!==this.#p.readyState)throw new Error(`cannot send command ${e.c} (channel state: ${this.#p.readyState})`);const t=es(e,this.#v.webRtcMaxMessageSize);for(const e of t)this.#p.send(e)}stopUploadingSegmentData(){this.#u.cancel(),this.#f=void 0}getUploadingRequestId(){return this.#f}async splitSegmentDataToChunksAndUploadAsync(e,t){if(void 0!==this.#f)throw new Error("Some segment data is already uploading.");this.#f=t;try{await this.#u.sendData(e,e=>{this.#m(e,this.#S,this.#v.streamType,this.#v.infoHash)})}finally{this.#f===t&&(this.#f=void 0)}}#b(e){this.#c??=new ze(e=>{let t;this.#c=void 0;try{t=Yt(e)}catch(e){return Ze("error deserializing command: %O",e),void this.#y.onProtocolError(e)}this.#y.onCommandReceived(t)});try{this.#c.addCommandChunk(e)}catch(e){Ze("error receiving command chunks: %O",e),this.#c=void 0,this.#y.onProtocolError(e)}}destroy(){this.#p.removeEventListener("message",this.#E),this.#u.cancel(),this.#c=void 0,this.#f=void 0}},tt=class{clearThresholdMs;loadingsCount=0;bytes=[];loadingOnlyTimestamps=[];timestamps=[];noLoadingsTime=0;loadingsStoppedAt=0;constructor(e=2e4){this.clearThresholdMs=e}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),0===this.loadingsCount&&0!==this.loadingsStoppedAt&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,0===this.loadingsCount&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=Number.NEGATIVE_INFINITY){if(!this.loadingOnlyTimestamps.length)return 0;const s=1e3*e,i=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1];let r=i;const n=i-s;let a=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.loadingOnlyTimestamps[e];if(s<n||this.timestamps[e]<t)break;r=s,a+=this.bytes[e]}return 8e3*a/Math.max(i-r,1)}getBandwidth(e,t=Number.NEGATIVE_INFINITY,s=performance.now()){if(!this.timestamps.length)return 0;const i=s-1e3*e;let r=s,n=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.timestamps[e];if(s<i||s<t)break;r=s,n+=this.bytes[e]}return 8e3*n/Math.max(s-r,1)}clearStale(){if(!this.loadingOnlyTimestamps.length)return;const e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs;let t=0;for(const s of this.loadingOnlyTimestamps){if(s>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}clear(){this.bytes.length=0,this.loadingOnlyTimestamps.length=0,this.timestamps.length=0,this.loadingsCount=0,this.noLoadingsTime=0,this.loadingsStoppedAt=0}},({PeerCommandType:st}=Xe),it=class{id;channel;eventTarget;#T;#w;#I=new Set;#L=new Set;#A=0;#k=new tt;#R={value:0,timestamp:0};#C=(0,Oe.default)("p2pml-core:peer");#P=0;#D;#M=!1;connectedAt=performance.now();#_;#y;#v;get isDestroyed(){return this.#M}constructor(e,t,s,i,r,n){this.id=e,this.channel=t,this.eventTarget=n,this.#_=s,this.#y=i,this.#v=r,this.#T=new et(t,r,{onSegmentChunkReceived:this.#O,onCommandReceived:e=>{this.#x(e).catch(t=>{this.#C("error processing command %O: %O",e,t),this.destroy(!1,new Se("protocol-violation",t instanceof Error?t.message:"Error processing command",t))})},onProtocolError:e=>{this.destroy(!1,new Se("protocol-violation",e instanceof Error?e.message:"Protocol error",e))}},n,e)}get downloadingSegment(){return this.#w?.request.segment}get isUploadingSegment(){return void 0!==this.#T.getUploadingRequestId()}getDownloadBandwidth(){const e=performance.now();return e-this.#R.timestamp>1e3&&(this.#R.value=this.#k.getBandwidthLoadingOnly(15),this.#R.timestamp=e),this.#R.value}getSegmentStatus(e){const{externalId:t}=e;return this.#I.has(t)?"loaded":this.#L.has(t)?"http-loading":void 0}#x=async e=>{switch(e.c){case st.SegmentsAnnouncement:this.#I=new Set(e.l),this.#L=new Set(e.p),this.#y.onSegmentsAnnouncement(this.#I.size,this.#L.size);break;case st.SegmentRequest:this.#D=e.r,this.#T.stopUploadingSegmentData(),this.#y.onSegmentRequested(this,e.i,e.r,e.b);break;case st.SegmentData:{if(!this.#w)break;if(this.#w.isSegmentDataCommandReceived)break;const{request:t,controls:s,requestId:i}=this.#w;if(t.segment.externalId!==e.i||i!==e.r)break;this.#w.isSegmentDataCommandReceived=!0,s.firstBytesReceived(),void 0===t.totalBytes?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&this.#F("bytes-length-mismatch","Peer response bytes length mismatch")}break;case st.SegmentDataSendingCompleted:{const t=this.#w;if(!t?.isSegmentDataCommandReceived)return;const{request:s,controls:i,requestId:r}=t;if(s.segment.externalId!==e.i||r!==e.r)return void this.#F("protocol-violation","Peer protocol violation");if(s.loadedBytes!==s.totalBytes)return void this.#F("bytes-length-mismatch","Peer response bytes length mismatch");const n=await s.validateData(this.#v.validateP2PSegment);if(this.#M)return;if(this.#w!==t)return;if(!n)return void this.#F("validation-failed","P2P segment validation failed");this.#A=0,i.completeOnSuccess(),this.#k.stopLoading(),this.#w=void 0;break}case st.SegmentAbsent:this.#I.delete(e.i),this.#w?.request.segment.externalId===e.i&&this.#w.requestId===e.r&&this.#B("peer-segment-absent");break;case st.CancelSegmentRequest:if(this.#D===e.r&&(this.#D=void 0),this.#T.getUploadingRequestId()!==e.r)break;this.#T.stopUploadingSegmentData()}};#O=e=>{if(!this.#w?.isSegmentDataCommandReceived)return;const{request:t,controls:s}=this.#w;void 0!==t.totalBytes&&t.loadedBytes+e.byteLength>t.totalBytes?this.#F("bytes-length-mismatch","Peer response bytes length mismatch"):(this.#k.addBytes(e.byteLength),this.#R.timestamp=0,s.addLoadedChunk(e))};downloadSegment(e){if(this.#M)return;if(this.#w)throw new Error("Some segment already is downloading");if(e.tryCompleteByLoadedBytes({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:this.#v.p2pNotReceivingBytesTimeoutMs,onAbort:()=>{}},this.#v.validateP2PSegment,"p2p-segment-validation-failed"))return;this.#k.startLoading(),this.#P=(this.#P+1)%1e9,this.#w={request:e,requestId:this.#P,isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:this.#v.p2pNotReceivingBytesTimeoutMs,onAbort:t=>{if(!this.#w||this.#w.request!==e)return;const{request:s,requestId:i}=this.#w;this.#U(s.segment,i),this.#k.stopLoading(),"abort"!==t.type&&(this.#k.clear(),this.#R.timestamp=0,this.#C(`cleared bandwidth history due to ${t.type}`)),this.#w=void 0,"bytes-receiving-timeout"===t.type&&this.#A++,this.#A>=this.#v.p2pErrorRetries?this.destroy(!1,new Se("timeout","Too many timeout errors")):"bytes-receiving-timeout"===t.type&&this.#y.onWarning(new Ee("timeout-strike",`Timeout strike ${this.#A}/${this.#v.p2pErrorRetries}`))}})};const t={c:st.SegmentRequest,r:this.#w.requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),this.#N(t)||this.#B("peer-closed")}async uploadSegmentData(e,t,s){if(this.#M)return;if(t!==this.#D)return void this.#C(`discarding obsolete upload request ${t} for segment ${e.externalId}`);const{externalId:i}=e;this.#C(`send segment ${e.externalId} to ${this.id} (byteLength: ${s.byteLength})`);const r={c:st.SegmentData,i:i,r:t,s:s.byteLength};if(this.#N(r))try{if(await this.#T.splitSegmentDataToChunksAndUploadAsync(s,t),this.isDestroyed||t!==this.#D)return;this.#$(e,t),this.#C(`segment ${i} has been sent to ${this.id}`)}catch(e){this.#C(`cancel segment uploading ${i}: %O`,e)}}#F(e,t){this.#w?.request.clearLoadedBytes();const s=new Se(e,t);this.#B("peer-closed",s),this.destroy(!1,s)}#B(e,t){if(!this.#w)return;const{request:s,controls:i}=this.#w,{segment:r}=s;this.#C(`cancel segment request ${r.externalId} (${e})`);const n=new Ie(e,void 0,t);i.failWithError(n),this.#k.stopLoading(),"peer-segment-absent"!==e&&(this.#k.clear(),this.#R.timestamp=0,this.#C(`cleared bandwidth history due to ${n.type}`)),this.#w=void 0}sendSegmentsAnnouncementCommand(e,t){const s={c:st.SegmentsAnnouncement,p:t,l:e};this.#N(s)}sendSegmentAbsentCommand(e,t){this.#N({c:st.SegmentAbsent,i:e,r:t})}#U(e,t){this.#N({c:st.CancelSegmentRequest,i:e.externalId,r:t})}#$(e,t){this.#N({c:st.SegmentDataSendingCompleted,r:t,i:e.externalId})}destroy(e=!1,t){this.#M||(this.#M=!0,this.#B("peer-closed",t),this.#T.destroy(),e||this.#_(t),this.#C(`peer closed ${this.id}`))}#N(e){if(this.#M)return!1;try{return this.#T.sendCommand(e),!0}catch(t){return this.#C("error sending command %d: %O",e.c,t),!1}}},rt=class{events=new Map;dispatchEvent(e,t,s,i,r,n){const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch{}}getEventDispatcher(e){return(t,s,i,r,n)=>{const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch{}}}addEventListener(e,t){const s=this.events.get(e);s?this.events.set(e,[...s,t]):this.events.set(e,[t])}removeEventListener(e,t){const s=this.events.get(e);if(!s)return;const i=s.indexOf(t);if(-1===i)return;if(1===s.length)return void this.events.delete(e);const r=s.slice();r.splice(i,1),this.events.set(e,r)}clear(){this.events.clear()}},nt="undefined"!=typeof window?window:{},at=nt.RTCPeerConnection??nt.webkitRTCPeerConnection??nt.mozRTCPeerConnection,ot=nt.RTCSessionDescription??nt.webkitRTCSessionDescription??nt.mozRTCSessionDescription,lt=(()=>{if(!nt.RTCPeerConnection&&!nt.webkitRTCPeerConnection&&!nt.mozRTCPeerConnection)return!1;let e;try{e=new at;const t=e.createOffer();if("function"==typeof t?.then)return t.catch(()=>{}),!0}catch{}finally{try{e?.close()}catch{}}return!1})(),ht=new Set(["offer","answer","pranswer","rollback"]),dt=class e{static#G=120;static#H=20;#W;#q;#j=new rt;#K=new Map;#V=new Set;#Y=new Ce;#z=null;#Q=null;#X=0;#J=null;#Z=!1;#ee=void 0;#te=null;#se=!1;#M(){return this.#Y.signal.aborted}#ie(){if(this.#Y.signal.aborted)throw new Error("Client destroyed")}constructor(e){this.#W={infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:e.offerTimeout??(()=>5e4),offersCount:e.offersCount??(()=>5),iceGatheringTimeout:e.iceGatheringTimeout??(()=>5e3),connectionTimeout:e.connectionTimeout??(()=>15e3),claimPeer:e.claimPeer??(()=>!0),shouldGenerateOffers:e.shouldGenerateOffers??(()=>!0)},this.#q=e.wsClient}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}start(){this.#M()||this.#se||(this.#se=!0,this.#q.addEventListener("connected",this.#re),this.#q.addEventListener("disconnected",this.#ne),this.#q.addEventListener("message",this.#ae),"connected"===this.#q.state&&this.#re())}destroy(){this.#M()||(this.#Y.abort(),this.#oe(),this.#le(),this.#he(),this.#de(),this.#se&&(this.#q.removeEventListener("connected",this.#re),this.#q.removeEventListener("disconnected",this.#ne),this.#q.removeEventListener("message",this.#ae)),this.#j.clear())}#re=()=>{this.#ce(e.#G),this.#ue("started").catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("announce-failed",`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})};#ne=()=>{this.#oe(),this.#Q=null};#ae=t=>{if(this.#M())return;let s;try{const e="string"==typeof t?t:(new TextDecoder).decode(t);s=JSON.parse(e)}catch(e){return void this.#j.dispatchEvent("error",new be("parse-error",`Failed to parse tracker message: ${e instanceof Error?e.message:String(e)}`,e))}if("object"!=typeof s||null===s||Array.isArray(s))return;const i=s,r=i.info_hash;if("string"==typeof r&&r!==this.#W.infoHash)return;const n=i["warning message"];"string"==typeof n&&this.#j.dispatchEvent("warning",new Te("tracker-response",n));const a=i["failure reason"];if("string"==typeof a)return void this.#j.dispatchEvent("error",new be("tracker-response",a));const{interval:o}=i;if("number"==typeof o&&o>0){const t=Math.max(e.#H,o);this.#Q!==t&&this.#ce(t)}const l=i["tracker id"];"string"==typeof l&&(this.#te=l),!0===i.request_offers&&this.#fe();const h=i.peer_id;if("string"==typeof h&&h===this.#W.peerId)return;const d=i.offer_id;"string"==typeof h&&"string"==typeof d&&(ns(i.offer)?this.#ge({sdp:i.offer,peerId:h,offerId:d}).catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("signaling-failed",`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):ns(i.answer)&&this.#me({sdp:i.answer,peerId:h,offerId:d}).catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("signaling-failed",`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))};#ce(e){this.#oe(),this.#Q=e;const t=++this.#X,s=async()=>{try{await this.#ue()}catch(e){if(this.#M())return;this.#j.dispatchEvent("error",new be("announce-failed",`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}this.#M()||null===this.#Q||this.#X!==t||(this.#z=setTimeout(s,1e3*this.#Q))};this.#z=setTimeout(s,1e3*e)}#oe(){null!==this.#z&&(clearTimeout(this.#z),this.#z=null)}#fe(){this.#M()||"connected"!==this.#q.state||(this.#J?this.#Z=!0:this.#ue().catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("announce-failed",`Requested announce failed: ${e instanceof Error?e.message:String(e)}`,e))}))}async#ue(e){if(this.#M()||"connected"!==this.#q.state)return;if(e&&(this.#ee=e),this.#J)return this.#J;const t=(async()=>{const e=this.#W.shouldGenerateOffers()?this.#W.offersCount():0,t=await Promise.all(Array.from({length:e},()=>this.#pe()));if(this.#M()){for(const e of t)e&&this.#ve(e.offer_id);return}const s=[];for(const e of t)e&&s.push(e);const i=this.#ee;this.#ee=void 0;const r=this.#ye({numwant:s.length,offers:s,event:i});if("connected"===this.#q.state)try{this.#q.send(JSON.stringify(r))}catch(e){for(const e of s)this.#ve(e.offer_id);throw e}else for(const e of s)this.#ve(e.offer_id)})();this.#J=t;try{await t}finally{this.#J===t&&(this.#J=null,this.#Z&&(this.#Z=!1,xt(()=>this.#fe())))}}async#pe(){if(this.#M())return;let e;try{e=new at(this.#W.rtcConfig?.()),this.#V.add(e);const t=e.createDataChannel("webtorrent",this.#W.channelConfig),s=await function(e,t){return lt?e.createOffer(t):new Promise((s,i)=>{try{e.createOffer(s,i,t)}catch(e){i(e)}})}(e);this.#ie(),await is(e,s),this.#ie(),await this.#Se(e),this.#ie();const i=e.localDescription;if(!i?.sdp)return void e.close();const r=function(){let e="";for(let t=0;t<20;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e}();return this.#K.set(r,{connection:e,channel:t,timeoutId:setTimeout(()=>{this.#ve(r)},this.#W.offerTimeout())}),{offer:{type:i.type,sdp:i.sdp},offer_id:r}}catch(t){e?.close(),this.#M()||this.#j.dispatchEvent("warning",new Te("offer-failed",`Failed to create offer: ${t instanceof Error?t.message:String(t)}`,t))}finally{e&&this.#V.delete(e)}}#le(){if("connected"!==this.#q.state)return;const e=this.#ye({numwant:0,offers:[],event:"stopped"});try{this.#q.send(JSON.stringify(e))}catch{}}#ye({numwant:e,offers:t,event:s}){const i={action:"announce",info_hash:this.#W.infoHash,peer_id:this.#W.peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return s&&(i.event=s),this.#te&&(i.trackerid=this.#te),i}async#ge({sdp:e,peerId:t,offerId:s}){if(this.#M())return;if(!this.#W.claimPeer(t))return;let i;try{i=new at(this.#W.rtcConfig?.()),this.#V.add(i),await rs(i,new ot(e)),this.#ie();const r=await function(e,t){return lt?e.createAnswer(t):new Promise((s,i)=>{try{e.createAnswer(s,i,t)}catch(e){i(e)}})}(i);this.#ie(),await is(i,r),this.#ie(),await this.#Se(i),this.#ie();const n=i.localDescription;if(!n)throw new Error("Failed to get local description after ICE gathering");const a={action:"announce",info_hash:this.#W.infoHash,peer_id:this.#W.peerId,to_peer_id:t,offer_id:s,answer:{type:n.type,sdp:n.sdp}};this.#q.send(JSON.stringify(a));const o=await this.#Ee(i);this.#ie(),this.#j.dispatchEvent("peerConnected",{peerId:t,connection:i,channel:o})}catch(e){i?.close(),this.#j.dispatchEvent("peerConnectFailed",{peerId:t,error:new we("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{i&&this.#V.delete(i)}}async#me({sdp:e,peerId:t,offerId:s}){if(this.#M())return;const i=this.#K.get(s);if(i)if(this.#K.delete(s),clearTimeout(i.timeoutId),this.#W.claimPeer(t)){this.#V.add(i.connection);try{await rs(i.connection,new ot(e)),this.#ie();const s=await this.#Ee(i.connection,i.channel);this.#ie(),this.#j.dispatchEvent("peerConnected",{peerId:t,connection:i.connection,channel:s})}catch(e){i.connection.close(),this.#j.dispatchEvent("peerConnectFailed",{peerId:t,error:new we("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{this.#V.delete(i.connection)}}else i.connection.close()}#Se(e){return new Promise((t,s)=>{if("complete"===e.iceGatheringState)return void t();if("closed"===e.signalingState)return void s(new Error("RTCPeerConnection closed"));let i;const r=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",n),e.removeEventListener("icecandidate",a),e.removeEventListener("signalingstatechange",o),this.#Y.signal.removeEventListener("abort",l)},n=()=>{"complete"===e.iceGatheringState&&(r(),t())},a=e=>{null===e.candidate&&(r(),t())},o=()=>{"closed"===e.signalingState&&(r(),s(new Error("RTCPeerConnection closed")))},l=()=>{r(),s(new Error("ICE gathering aborted due to teardown"))};this.#Y.signal.aborted?l():(i=setTimeout(()=>{r(),t()},this.#W.iceGatheringTimeout()),e.addEventListener("icegatheringstatechange",n),e.addEventListener("icecandidate",a),e.addEventListener("signalingstatechange",o),this.#Y.signal.addEventListener("abort",l))})}#Ee(e,t){const{promise:s,resolve:i,reject:r}=Ot();let n,a=t;const o=()=>!!ss(e.iceConnectionState)&&(g(),r(new Error(`ICE connection ${e.iceConnectionState}`)),!0),l=()=>{g(),a?i(a):r(new Error("Data channel missing on open"))},h=()=>{g(),r(new Error("Data channel error"))},d=()=>{g(),r(new Error("Data channel closed prematurely"))},c=e=>{a=e,"open"===e.readyState?l():"closed"===e.readyState||"closing"===e.readyState?d():(e.addEventListener("open",l),e.addEventListener("error",h),e.addEventListener("close",d),e.addEventListener("closing",d))},u=e=>{a||c(e.channel)},f=()=>{g(),r(new Error("Connection aborted due to teardown"))},g=()=>{clearTimeout(n),e.removeEventListener("iceconnectionstatechange",o),e.removeEventListener("datachannel",u),a&&(a.removeEventListener("open",l),a.removeEventListener("error",h),a.removeEventListener("close",d),a.removeEventListener("closing",d)),this.#Y.signal.removeEventListener("abort",f)};return this.#Y.signal.aborted?(f(),s):(o()||(n=setTimeout(()=>{g(),r(new Error("Data channel open timeout"))},this.#W.connectionTimeout()),e.addEventListener("iceconnectionstatechange",o),this.#Y.signal.addEventListener("abort",f),a?c(a):e.addEventListener("datachannel",u)),s)}#ve(e,t){const s=t??this.#K.get(e);s&&(clearTimeout(s.timeoutId),s.connection.close(),this.#K.delete(e))}#he(){for(const[e,t]of this.#K)this.#ve(e,t)}#de(){for(const e of this.#V)e.close();this.#V.clear()}},ct=class{#W;#j=new rt;#be=new Set;#Te=new Map;#we=new Set;#Ie=!1;#se=!1;#Le=e=>{if(this.#Ie)return!1;if(this.#be.has(e)||this.#Te.has(e))return!1;const t=Math.floor(this.#W.maxPeers()*Math.max(1,this.#W.maxPeersMultiplier()));return!(this.#be.size+this.#Te.size>=t||(this.#be.add(e),0))};constructor(e){this.#W={...e,maxPeers:e.maxPeers??(()=>50),maxPeersMultiplier:e.maxPeersMultiplier??(()=>1.5)}}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}start(){if(!this.#Ie&&!this.#se){this.#se=!0;try{for(const e of this.#W.trackerUrls){const{client:t,release:s}=this.#W.socketPool.acquire(e);let i=!1;try{const r=new dt({infoHash:this.#W.infoHash,peerId:this.#W.peerId,wsClient:t,rtcConfig:this.#W.rtcConfig,channelConfig:this.#W.channelConfig,claimPeer:this.#Le,offersCount:this.#W.offersCount,offerTimeout:this.#W.offerTimeout,iceGatheringTimeout:this.#W.iceGatheringTimeout,connectionTimeout:this.#W.connectionTimeout,shouldGenerateOffers:()=>this.#be.size+this.#Te.size<this.#W.maxPeers()}),n=t=>{this.#be.delete(t.peerId),this.#Ae(t.peerId,t.connection,t.channel,e)},a=t=>{this.#be.has(t.peerId)&&(this.#be.delete(t.peerId),this.#j.dispatchEvent("peerConnectFailed",{peerId:t.peerId,trackerUrl:e,error:t.error}))},o=t=>{this.#j.dispatchEvent("warning",{trackerUrl:e,warning:t})},l=t=>{this.#j.dispatchEvent("error",{trackerUrl:e,error:t})};r.addEventListener("peerConnected",n),r.addEventListener("peerConnectFailed",a),r.addEventListener("warning",o),r.addEventListener("error",l);const h=()=>{r.removeEventListener("peerConnected",n),r.removeEventListener("peerConnectFailed",a),r.removeEventListener("warning",o),r.removeEventListener("error",l)};this.#we.add({client:r,releaseSocket:s,cleanupListeners:h}),i=!0,r.start()}catch(e){throw i||s(),e}}}catch(e){throw this.destroy(),e}}}destroy(){if(this.#Ie)return;this.#Ie=!0;for(const{client:e,releaseSocket:t,cleanupListeners:s}of this.#we)s(),e.destroy(),t();this.#we.clear(),this.#be.clear();const e=[...this.#Te.entries()];this.#Te.clear();for(const[t,s]of e){s.cleanup();try{s.channel.close()}catch{}try{s.connection.close()}catch{}this.#j.dispatchEvent("peerDisconnected",{peerId:t,trackerUrl:s.trackerUrl,disconnectReason:"Manager destroyed"})}this.#j.clear()}#ke(e,t){if(this.#Ie)return;const s=this.#Te.get(e);if(s){this.#Te.delete(e),s.cleanup();try{s.channel.close()}catch{}try{s.connection.close()}catch{}this.#j.dispatchEvent("peerDisconnected",{peerId:e,trackerUrl:s.trackerUrl,...t})}}#Ae(e,t,s,i){if(ss(t.iceConnectionState)){try{t.close()}catch{}return void this.#j.dispatchEvent("peerConnectFailed",{peerId:e,trackerUrl:i,error:new we("connection-failed","Connection failed during promotion")})}const r=t=>this.#ke(e,t),n=()=>{ss(t.iceConnectionState)&&r({error:new Se("connection-lost",`ICE connection state became ${t.iceConnectionState}`)})},a=()=>r({disconnectReason:"Data channel closed"}),o=()=>r({disconnectReason:"Data channel closing"}),l=e=>{r({error:new Se("transport-error",`Data channel error: ${ts(e,"Data channel error")}`)})};let h=t=>this.#ke(e,t?{error:t}:{disconnectReason:"Closed by consumer"});this.#Te.set(e,{connection:t,channel:s,trackerUrl:i,cleanup:()=>{h=null,t.removeEventListener("iceconnectionstatechange",n),s.removeEventListener("close",a),s.removeEventListener("closing",o),s.removeEventListener("error",l)}}),t.addEventListener("iceconnectionstatechange",n),s.addEventListener("close",a),s.addEventListener("closing",o),s.addEventListener("error",l),this.#j.dispatchEvent("peerConnected",{peerId:e,connection:t,channel:s,trackerUrl:i,close:e=>h?.(e)})}},ut="v2",ft=`-PM${function(){const e="3.0.1".split(".");return`${`00${e[0]}`.slice(-2)}${`00${e[1]}`.slice(-2)}`}()}-`,gt=class{#Re;#Ce=new Map;#Pe;#De;#Me=!1;#_e=(0,Oe.default)("p2pml-core:webtorrent-manager");#Oe=(0,Oe.default)("p2pml-core:churn-cleanup");#xe;#Fe;#Be;#Ue;#Ne;#W;#$e;#j;#Ge;#He;#We;#qe;#je;#Ke;#Ve;#Ye;#ze;#Qe;constructor(e,t,s,i,r,n,a,o,l){this.#Fe=e,this.#Be=t,this.#Ue=s,this.#Ne=i,this.#W=r,this.#$e=n,this.#j=a,this.#Ge=l,this.#We=a.getEventDispatcher("onPeerConnect"),this.#qe=a.getEventDispatcher("onPeerConnectError"),this.#je=a.getEventDispatcher("onPeerClose"),this.#Ke=a.getEventDispatcher("onPeerError"),this.#Ve=a.getEventDispatcher("onPeerWarning"),this.#Ye=a.getEventDispatcher("onTrackerWarning"),this.#ze=a.getEventDispatcher("onTrackerError"),this.#Qe=a.getEventDispatcher("onPeerSegmentsAnnouncement"),this.#Pe=this.#W.swarmId??this.#Fe,this.#De=ls(this.#Pe,this.#Be);const h=us(this.#De);this.#xe=h,this.#Re=new ct({infoHash:h,peerId:o,trackerUrls:this.#W.announceTrackers,rtcConfig:()=>this.#W.rtcConfig,socketPool:this.#$e,maxPeers:()=>this.#W.p2pMaxPeers,maxPeersMultiplier:()=>this.#W.p2pChurnMaxPeersMultiplier,offersCount:()=>this.#W.webRtcOffersCount,offerTimeout:()=>this.#W.webRtcOfferTimeoutMs,iceGatheringTimeout:()=>this.#W.webRtcIceGatheringTimeoutMs,connectionTimeout:()=>this.#W.webRtcConnectionTimeoutMs}),this.#Re.addEventListener("peerConnected",this.#Xe),this.#Re.addEventListener("peerDisconnected",this.#Je),this.#Re.addEventListener("peerConnectFailed",e=>{this.#_e(`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),this.#qe({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type,trackerUrl:e.trackerUrl,error:e.error})}),this.#Re.addEventListener("warning",e=>{this.#_e(`Tracker warning (${e.trackerUrl}):`,e.warning),this.#Ye({trackerUrl:e.trackerUrl,infoHash:this.#xe,streamType:this.#Be.type,warning:e.warning})}),this.#Re.addEventListener("error",e=>{this.#_e(`Tracker error (${e.trackerUrl}):`,e.error),this.#ze({trackerUrl:e.trackerUrl,infoHash:this.#xe,streamType:this.#Be.type,error:e.error})}),this.#j.addEventListener(`onStorageUpdated-${this.#De}`,this.broadcastAnnouncement),this.#Re.start(),this.#He=setTimeout(this.#Ze,Math.max(1e3,this.#W.p2pChurnCleanupIntervalMs))}#Ze=()=>{this.#He=setTimeout(this.#Ze,Math.max(1e3,this.#W.p2pChurnCleanupIntervalMs));const e=this.#Ce.size-this.#W.p2pMaxPeers;if(e<=0)return;const t=[],s=performance.now();for(const e of this.#Ce.values())e.downloadingSegment||e.isUploadingSegment||s-e.connectedAt<this.#W.p2pChurnGracePeriodMs||t.push(e);if(0===t.length)return;t.sort((e,t)=>e.getDownloadBandwidth()-t.getDownloadBandwidth()||e.connectedAt-t.connectedAt);const i=t.slice(0,e);this.#Oe(`Background churn cleanup: dropping ${i.length} excess peers (total: ${this.#Ce.size}, target: ${this.#W.p2pMaxPeers}, eligible: ${t.length})`);for(const e of i)this.#Oe(`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()};downloadSegment(e){const t=[];for(const s of this.#Ce.values())s.downloadingSegment||"loaded"!==s.getSegmentStatus(e)||t.push(s);if(0===t.length)return;const s=fs(t),i=this.#Ue.getOrCreateRequest(e);s.downloadSegment(i)}isSegmentLoadingOrLoadedBySomeone(e){for(const t of this.#Ce.values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(const t of this.#Ce.values())if("loaded"===t.getSegmentStatus(e))return!0;return!1}get connectedPeerCount(){return this.#Ce.size}*peers(){for(const e of this.#Ce.values())yield e}#et(){const e=this.#Ne.getStoredSegmentIds(this.#Pe,this.#De),t=[];for(const e of this.#Ue.httpRequests()){const s=this.#Be.segments.get(e.segment.runtimeId);s&&t.push(s.externalId)}return{loaded:e,httpLoading:t}}#Xe=e=>{if(this.#_e(`peerConnected: peerId=${e.peerId}`),this.#Ce.has(e.peerId))return void e.close();const t=new it(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,s,i)=>{this.#tt(e,t,s,i).catch(s=>{this.#_e(`Error in onSegmentRequested ${t} for peer ${e.id}:`,s)})},onSegmentsAnnouncement:(t,s)=>{this.#Qe(e.peerId,this.#xe,this.#Be.type,t,s),this.#Ge()},onWarning:e=>{this.#Ve({peerId:t.id,infoHash:this.#xe,streamType:this.#Be.type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:this.#W.p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:this.#W.webRtcMaxMessageSize,p2pErrorRetries:this.#W.p2pErrorRetries,validateP2PSegment:this.#W.validateP2PSegment,streamType:this.#Be.type,infoHash:this.#xe},this.#j);if(this.#Ce.set(e.peerId,t),this.#We({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type}),this.#W.isP2PUploadDisabled)return;const{httpLoading:s,loaded:i}=this.#et();t.sendSegmentsAnnouncementCommand(i,s)};#Je=e=>{this.#_e("peerDisconnected: peerId=%s error=%s reason=%s",e.peerId,e.error?.message,e.disconnectReason);const t=this.#Ce.get(e.peerId);t&&(this.#Ce.delete(e.peerId),t.destroy(!0),e.error&&this.#Ke({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type,error:e.error}),this.#je({peerId:t.id,infoHash:this.#xe,streamType:this.#Be.type}))};broadcastAnnouncement=(e=!1)=>{e?this.#st(e):this.#Me||this.#W.isP2PUploadDisabled||this.#st()};#st=(e=!1)=>{this.#Me=!0,xt(()=>{const{loaded:t=[],httpLoading:s=[]}=e?{}:this.#et();for(const e of this.#Ce.values())e.sendSegmentsAnnouncementCommand(t,s);this.#Me=!1})};#tt=async(e,t,s,i)=>{const r=function(e,t){for(const s of e.segments.values())if(s.externalId===t)return s}(this.#Be,t);if(!r)return;if(this.#W.isP2PUploadDisabled)return void e.sendSegmentAbsentCommand(t,s);let n;try{n=await this.#Ne.getSegmentData(this.#Pe,this.#De,r.externalId)}catch(s){this.#_e(`Storage error for segment ${t} requested by peer ${e.id}:`,s)}this.#Ce.has(e.id)&&(n?await e.uploadSegmentData(r,s,void 0!==i?new Uint8Array(n).subarray(i):n):e.sendSegmentAbsentCommand(t,s))};destroy(){clearTimeout(this.#He),this.#He=void 0,this.#j.removeEventListener(`onStorageUpdated-${this.#De}`,this.broadcastAnnouncement),this.#Re.destroy();for(const e of this.#Ce.values())e.destroy();this.#Ce.clear()}},mt=class{#it=new Map;#rt;#C=(0,Oe.default)("p2pml-core:p2p-loaders-container");#Fe;#Ue;#Ne;#W;#$e;#j;#S;#Ge;constructor(e,t,s,i,r,n,a,o,l){this.#Fe=e,this.#Ue=s,this.#Ne=i,this.#W=r,this.#$e=n,this.#j=a,this.#S=o,this.#Ge=l,this.#rt=this.#nt(t),this.#C(`set current p2p loader: ${gs(t)}`)}#at(e){if(this.#it.has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new gt(this.#Fe,e,this.#Ue,this.#Ne,this.#W,this.#$e,this.#j,this.#S,()=>{this.#rt.loader===t&&this.#Ge()}),s=gs(e);return this.#C(`created new loader: ${s}`),{loader:t,stream:e,loggerInfo:s}}#nt(e){const t=this.#it.get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{const t=this.#at(e);return this.#it.set(e.runtimeId,t),t}}changeCurrentLoader(e){const t=this.#W.swarmId??this.#Fe,s=ls(t,this.#rt.stream);this.#Ne.getStoredSegmentIds(t,s).length?this.#ot(this.#rt):this.#lt(this.#rt),this.#rt=this.#nt(e),this.#C(`change current p2p loader: ${gs(e)}`)}#ot(e){e.destroyTimeoutId=window.setTimeout(()=>this.#lt(e),this.#W.p2pInactiveLoaderDestroyTimeoutMs)}#lt(e){e.loader.destroy(),this.#it.delete(e.stream.runtimeId),this.#C("destroy p2p loader: ",e.loggerInfo)}get currentLoader(){return this.#rt.loader}destroy(){for(const{loader:e,destroyTimeoutId:t}of this.#it.values())e.destroy(),clearTimeout(t);this.#it.clear()}},pt=class{segment;requestProcessQueueCallback;bandwidthCalculators;playback;playbackConfig;infoHash;currentAttempt;_failedAttempts=new vt;finalData;bytes=[];_loadedBytes=0;_totalBytes;_status="not-started";progress;notReceivingBytesTimeout;_onAbortCallback;notReceivingBytesTimeoutMs;_logger;_isHandledByProcessQueue=!1;onSegmentError;onSegmentAbort;onSegmentStart;onSegmentLoaded;constructor(e,t,s,i,r,n,a){this.segment=e,this.requestProcessQueueCallback=t,this.bandwidthCalculators=s,this.playback=i,this.playbackConfig=r,this.infoHash=a,this.onSegmentError=n.getEventDispatcher("onSegmentError"),this.onSegmentAbort=n.getEventDispatcher("onSegmentAbort"),this.onSegmentStart=n.getEventDispatcher("onSegmentStart"),this.onSegmentLoaded=n.getEventDispatcher("onSegmentLoaded");const{byteRange:o}=this.segment;if(o){const{end:e,start:t}=o;this._totalBytes=e-t+1}this.notReceivingBytesTimeout=new yt(this.abortOnTimeout);const{type:l}=this.segment.stream;this._logger=(0,Oe.default)(`p2pml-core:request-${l}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){return this.currentAttempt?.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){return this.finalData??=Ft(this.bytes).buffer,this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(void 0!==this._totalBytes)throw new Error("Request total bytes value is already set");this._totalBytes=e}tryCompleteByLoadedBytes(e,t,s,i){if(!this._totalBytes)return!1;if(this._loadedBytes>this._totalBytes)return this.logger(`${e.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`),this.clearLoadedBytes(),!1;if(this._loadedBytes!==this._totalBytes)return!1;const r=this.start(e,t);return this.notReceivingBytesTimeout.clear(),s?this.validateAndComplete(e.downloadSource,r,s,i):r.completeOnSuccess(),!0}async validateData(e){if(!e)return!0;try{return await e(this.segment.url,this.segment.byteRange,this.data)}catch(e){return this.logger(`validation threw an error: ${String(e)}`),!1}}async validateAndComplete(e,t,s,i){const r=await this.validateData(s);if("loading"===this._status){if(!r)return this.logger(`${e} ${this.segment.externalId} validation failed for already-loaded bytes, clearing`),this.clearLoadedBytes(),void t.failWithError(new Ie(i));this.logger(`${e} ${this.segment.externalId} validation passed for already-loaded bytes`),t.completeOnSuccess()}}start(e,t){if("succeed"===this._status)throw new Error(`Request ${this.segment.externalId} has been already succeed.`);if("loading"===this._status)throw new Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus("loading"),this.currentAttempt={...e},this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState("start");const{notReceivingBytesTimeoutMs:s}=t;return this._onAbortCallback=t.onAbort,this.notReceivingBytesTimeoutMs=s,void 0!==s&&this.notReceivingBytesTimeout.start(s),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:ps(this.segment),downloadSource:e.downloadSource,peerId:"p2p"===e.downloadSource?e.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,failWithError:this.failWithError}}cancel(){this.throwErrorIfNotLoadingStatus(),this.setStatus("aborted"),this.logger(`${this.currentAttempt?.downloadSource} ${this.segment.externalId} aborted`),this._onAbortCallback?.(new Ie("abort")),this.onSegmentAbort({segment:ps(this.segment),downloadSource:this.currentAttempt?.downloadSource,peerId:"p2p"===this.currentAttempt?.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this._onAbortCallback=void 0,this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear()}abortOnTimeout=()=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress||void 0===this.notReceivingBytesTimeoutMs)return;const e=performance.now()-(this.progress.lastLoadedChunkTimestamp??this.progress.startTimestamp);if(e<this.notReceivingBytesTimeoutMs)return void this.notReceivingBytesTimeout.restart(this.notReceivingBytesTimeoutMs-e);const t=new Ie("bytes-receiving-timeout");this._onAbortCallback?.(t),this.handleFailure(t)};failWithError=e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)};handleFailure=e=>{this.currentAttempt&&(this.setStatus("failed"),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add({...this.currentAttempt,error:e}),this.onSegmentError({segment:ps(this.segment),error:e,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback())};completeOnSuccess=()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear(),this.setStatus("succeed"),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,segment:ps(this.segment),bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())};addLoadedChunk=e=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;const{byteLength:t}=e,{all:s,http:i}=this.bandwidthCalculators;s.addBytes(t),"http"===this.currentAttempt.downloadSource&&i.addBytes(t),this.bytes.push(e),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=t,this._loadedBytes+=t};firstBytesReceived=()=>{this.throwErrorIfNotLoadingStatus()};throwErrorIfNotLoadingStatus(){if("loading"!==this._status)throw new Error(`Request has been already ${this.status}.`)}logger(e){this._logger.color="http"===this.currentAttempt?.downloadSource?"green":"red",this._logger(e),this._logger.color=""}manageBandwidthCalculatorsState(e){const{all:t,http:s}=this.bandwidthCalculators,i="start"===e?"startLoading":"stopLoading";"http"===this.currentAttempt?.downloadSource&&s[i](),t[i]()}},vt=class{attempts=[];add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>"http"===t.downloadSource?e+1:e,0)}get p2pAttemptsCount(){return this.attempts.reduce((e,t)=>"p2p"===t.downloadSource?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}},yt=class{action;timeoutId;ms;constructor(e){this.action=e}start(e){if(this.timeoutId)throw new Error("Timeout is already started.");this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.clear(),void 0!==e&&(this.ms=e),void 0!==this.ms&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}},St=class{requestProcessQueueCallback;bandwidthCalculators;playback;config;eventTarget;swarmId;requests=new Map;constructor(e,t,s,i,r,n){this.requestProcessQueueCallback=e,this.bandwidthCalculators=t,this.playback=s,this.config=i,this.eventTarget=r,this.swarmId=n}get executingHttpCount(){let e=0;for(const t of this.httpRequests())"loading"===t.status&&e++;return e}get executingP2PCount(){let e=0;for(const t of this.p2pRequests())"loading"===t.status&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);if(!t){const s=us(ls(this.swarmId,e.stream));t=new pt(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,s),this.requests.set(e,t)}return t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(const e of this.requests.values())"http"===e.downloadSource&&(yield e)}*p2pRequests(){for(const e of this.requests.values())"p2p"===e.downloadSource&&(yield e)}destroy(){for(const e of this.requests.values())"loading"===e.status&&e.cancel();this.requests.clear()}},Et=class{segment;engineCallbacks;_status="pending";_shouldBeStartedImmediately=!1;constructor(e,t){this.segment=e,this.engineCallbacks=t}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){"pending"===this._status&&(this._status="succeed",this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){"pending"===this._status&&(this._status="failed",this.engineCallbacks.onError(new Le("failed")))}abort(){"pending"===this._status&&(this._status="aborted",this.engineCallbacks.onError(new Le("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}},bt=class{streamManifestUrl;lastRequestedSegment;streamDetails;config;bandwidthCalculators;segmentStorage;webTorrentSocketPool;eventTarget;peerId;requests;engineRequest;p2pLoaders;playback;segmentAvgDuration;logger;levelChangedTimestamp;lastQueueProcessingTimeStamp;randomHttpDownloadTimeout;initialHttpDelayTimeoutId;isProcessQueueMicrotaskCreated=!1;swarmId;createdAt=performance.now();constructor(e,t,s,i,r,n,a,o,l){this.streamManifestUrl=e,this.lastRequestedSegment=t,this.streamDetails=s,this.config=i,this.bandwidthCalculators=r,this.segmentStorage=n,this.webTorrentSocketPool=a,this.eventTarget=o,this.peerId=l;const h=this.lastRequestedSegment.stream;this.swarmId=this.config.swarmId??this.streamManifestUrl,this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=function(e){const{segments:t}=e;let s=0;const{size:i}=t;if(0===i)return 0;for(const e of t.values())s+=e.endTime-e.startTime;return s/i}(h),this.requests=new St(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new mt(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,Oe.default)(`p2pml-core:hybrid-loader-${h.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=1e3*Math.random()*e+1e3;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}async loadSegment(e,t){this.logger(`requests: ${ms(e)}`);const{stream:s}=e;s!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${gs(s)}`),this.p2pLoaders.changeCurrentLoader(s)),this.lastRequestedSegment=e;const i=ls(this.swarmId,s);this.segmentStorage.onSegmentRequested(this.swarmId,i,e.externalId,e.startTime,e.endTime,s.type,this.streamDetails.isLive);const r=new Et(e,t);try{if(this.segmentStorage.hasSegment(this.swarmId,i,e.externalId)){const t=await this.segmentStorage.getSegmentData(this.swarmId,i,e.externalId);if(t){const{queueDownloadRatio:e}=this.generateQueue();return void r.resolve(t,this.getBandwidth(e))}}this.engineRequest?.abort(),this.engineRequest=r;const t=this.requests.get(e);"failed"===t?.status&&t.failedAttempts.clear()}catch(t){this.logger(`request failed for ${ms(e)} in ${gs(s)}`,t),r.reject()}finally{this.requestProcessQueueMicrotask()}}requestProcessQueueMicrotask=(e=!0)=>{const t=performance.now();!e&&void 0!==this.lastQueueProcessingTimeStamp&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,xt(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))};processRequests(e,t){const{stream:s}=this.lastRequestedSegment,{httpErrorRetries:i}=this.config,r=performance.now();for(const n of this.requests.items()){const{downloadSource:a,status:o,segment:l,isHandledByProcessQueue:h}=n,d=this.engineRequest?.segment===l?this.engineRequest:void 0;switch(o){case"loading":e.has(l.runtimeId)||d||(n.cancel(),this.requests.remove(n));break;case"succeed":{if(!a)break;"http"===a&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),d&&(d.resolve(n.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(n),this.logger(`succeed: ${ms(l)} (byteLength: ${n.data.byteLength})`);const e=ls(this.swarmId,s);this.segmentStorage.storeSegment(this.swarmId,e,l.externalId,n.data,l.startTime,l.endTime,l.stream.type,this.streamDetails.isLive);break}case"failed":"http"!==a||h||this.p2pLoaders.currentLoader.broadcastAnnouncement(),d||s.segments.has(n.segment.runtimeId)||this.requests.remove(n),n.failedAttempts.httpAttemptsCount>=i&&d&&(this.engineRequest=void 0,d.reject());break;case"not-started":case"aborted":this.requests.remove(n)}n.markHandledByProcessQueue();const{lastAttempt:c}=n.failedAttempts;c&&r-c.error.timestamp>6e4&&n.failedAttempts.clear()}}processQueue(){const{queue:e,queueSegmentIds:t,queueDownloadRatio:s}=this.generateQueue();this.processRequests(t,s);const{simultaneousHttpDownloads:i,simultaneousP2PDownloads:r,httpErrorRetries:n,httpDownloadInitialTimeoutMs:a}=this.config,o=performance.now()-this.createdAt,l=a>0&&o<a;l&&(this.initialHttpDelayTimeoutId??=window.setTimeout(()=>{this.initialHttpDelayTimeoutId=void 0,this.requestProcessQueueMicrotask()},a-o));const{engineRequest:h}=this;if(h){const{segment:e}=h,t=this.requests.get(e);if(h.shouldBeStartedImmediately&&"pending"===h.status&&(!t||"not-started"===t.status||"failed"===t.status||"aborted"===t.status)){const s=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(e)&&this.requests.executingP2PCount<r;this.config.preferP2PForEngineRequest&&s?this.loadThroughP2P(e):!l&&(t?.failedAttempts.httpAttemptsCount??0)<n&&this.requests.executingHttpCount<i?this.loadThroughHttp(e):s&&this.loadThroughP2P(e)}}for(const t of e){const{statuses:s,segment:a}=t,o=this.requests.get(a);if("succeed"!==o?.status)if(s.isHighDemand){const t=!l&&(o?.failedAttempts.httpAttemptsCount??0)<n;if("loading"===o?.status){!this.config.preferP2PForEngineRequest&&t&&"p2p"===o.downloadSource&&(this.requests.executingHttpCount<i||this.abortLastHttpLoadingInQueueAfterItem(e,a))&&(o.cancel(),this.loadThroughHttp(a));continue}const s=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(a)&&(this.requests.executingP2PCount<r||this.abortLastP2PLoadingInQueueAfterItem(e,a));if(this.config.preferP2PForEngineRequest&&s){this.loadThroughP2P(a);continue}if(t&&(this.requests.executingHttpCount<i||this.abortLastHttpLoadingInQueueAfterItem(e,a))){this.loadThroughHttp(a);continue}s&&this.loadThroughP2P(a)}else s.isP2PDownloadable&&"loading"!==o?.status&&this.requests.executingP2PCount<r&&this.loadThroughP2P(a)}}abortSegmentRequest(e){this.engineRequest?.segment.runtimeId===e&&(this.engineRequest.abort(),this.logger("abort: ",ms(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){new Pe(this.requests.getOrCreateRequest(e),this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){const{httpDownloadInitialTimeoutMs:e}=this.config;if(e>0&&performance.now()-this.createdAt<e)return;const t=this.getAvailableStorageCapacityPercent();if(t<=10)return;const{simultaneousHttpDownloads:s,httpErrorRetries:i}=this.config,r=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=s||!r.connectedPeerCount)return;const n=[];for(const{segment:e,statuses:s}of vs(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){const t=ls(this.swarmId,e.stream);if(!s.isHttpDownloadable||s.isP2PDownloadable||this.segmentStorage.hasSegment(this.swarmId,t,e.externalId))continue;const r=this.requests.get(e);r&&("loading"===r.status||"succeed"===r.status||r.failedAttempts.httpAttemptsCount>=i)||n.push(e)}if(!n.length)return;if(s-this.requests.executingHttpCount===0)return;const a=r.connectedPeerCount+1,o=Math.min(n.length,s*a),l=function(e){for(let t=e.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]]}return e}(Array.from({length:o},(e,t)=>t));let h=o/a;for(const e of l){if(this.requests.executingHttpCount>=s)break;if(h>=1||Math.random()<=h){const t=n[e];this.loadThroughHttp(t)}if(h--,h<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:s}of Bt(e)){if(s===t)break;const e=this.requests.get(s);if("http"===e?.downloadSource&&"loading"===e.status)return e.cancel(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(const{segment:s}of Bt(e)){if(s===t)break;const e=this.requests.get(s);if("p2p"===e?.downloadSource&&"loading"===e.status)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){const{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){const e=[],t=new Set;let s=0,i=0;const r=this.getAvailableStorageCapacityPercent();for(const n of vs(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,r)){s++;const{segment:r}=n,a=ls(this.swarmId,r.stream);this.segmentStorage.hasSegment(this.swarmId,a,r.externalId)||"succeed"===this.requests.get(r)?.status?i++:(e.push(n),t.add(r.runtimeId))}return{queue:e,queueSegmentIds:t,maxPossibleLength:s,alreadyLoadedCount:i,queueDownloadRatio:0!==s?i/s:0}}getBandwidth(e){const{http:t,all:s}=this.bandwidthCalculators,{activeLevelBitrate:i}=this.streamDetails;if(0===i)return s.getBandwidthLoadingOnly(3);const r=Math.max(s.getBandwidth(30,this.levelChangedTimestamp),s.getBandwidth(60,this.levelChangedTimestamp),s.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||r>=.9*i)return Math.max(s.getBandwidthLoadingOnly(1),s.getBandwidthLoadingOnly(3),s.getBandwidthLoadingOnly(5));const n=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(r,n)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){const s=this.playback.rate!==t,i=this.playback.position!==e;if(!s&&!i)return;const r=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;i&&(this.playback.position=e),s&&0!==t&&(this.playback.rate=t),r&&(this.logger("position significantly changed"),this.engineRequest?.markAsShouldBeStartedImmediately()),this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(r)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${gs(e)}`),this.requestProcessQueueMicrotask())}destroy(){clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),this.engineRequest?.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}},Tt=(e,t)=>`${e}|${t}`,wt=e=>/Android/i.test(e),It=e=>/iPad|iPhone/i.test(e),Lt=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e)),At=1048576,kt=class{userAgent=navigator.userAgent;segmentMemoryStorageLimit=4096;currentStorageUsage=0;cache=new Map;logger;coreConfig;mainStreamConfig;secondaryStreamConfig;currentPlayback;lastRequestedSegment;segmentChangeCallback;constructor(){this.logger=(0,Oe.default)("p2pml-core:segment-memory-storage"),this.logger.color="RebeccaPurple"}async initialize(e,t,s){this.coreConfig=e,this.mainStreamConfig=t,this.secondaryStreamConfig=s,this.setMemoryStorageLimit(),this.logger("initialized")}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,s,i,r,n,a){this.lastRequestedSegment={streamId:t,segmentId:s,startTime:i,endTime:r,swarmId:e,streamType:n,isLiveStream:a}}async storeSegment(e,t,s,i,r,n,a,o){this.clear(o,i.byteLength);const l=Tt(t,s);if(this.cache.set(l,{data:i,segmentId:s,streamId:t,startTime:r,endTime:n,streamType:a}),this.increaseStorageUsage(i.byteLength),this.logger(`add segment: ${s} to ${t}`),!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)}async getSegmentData(e,t,s){const i=Tt(t,s),r=this.cache.get(i);if(void 0!==r)return r.data}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};const e=this.currentPlayback.position;let t=0;for(const{endTime:s,data:i}of this.cache.values())e>s||(t+=i.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/At}}hasSegment(e,t,s){const i=Tt(t,s);return void 0!==this.cache.get(i)}getStoredSegmentIds(e,t){const s=[];for(const{segmentId:e,streamId:i}of this.cache.values())i===t&&s.push(e);return s}clear(e,t){if(!(this.currentPlayback&&this.mainStreamConfig&&this.secondaryStreamConfig&&this.coreConfig))return;if(!this.isMemoryLimitReached(t)&&!e)return;const s=new Set,i=Array.from(this.cache.values()).sort((e,t)=>e.startTime-t.startTime);for(const r of i){const{streamId:i,segmentId:n,data:a}=r,o=Tt(i,n);if(this.shouldRemoveSegment(r,e,this.currentPlayback.position)&&(this.cache.delete(o),s.add(i),this.decreaseStorageUsage(a.byteLength),this.logger(`Removed segment ${n} from stream ${i}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(s)}isMemoryLimitReached(e){return this.currentStorageUsage+e/At>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){0!==e.size&&e.forEach(e=>{if(!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(e)})}shouldRemoveSegment(e,t,s){const{endTime:i,streamType:r}=e,n=this.getStreamTimeWindow(r,"highDemandTimeWindow");return!(s<=i)&&(!t||s>n+i)}increaseStorageUsage(e){this.currentStorageUsage+=e/At}decreaseStorageUsage(e){this.currentStorageUsage-=e/At}setMemoryStorageLimit(){this.coreConfig?.segmentMemoryStorageLimit?this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit:Lt(this.userAgent)||It(this.userAgent)?this.segmentMemoryStorageLimit=1024:wt(this.userAgent)&&(this.segmentMemoryStorageLimit=2048)}getStreamTimeWindow(e,t){return("main"===e?this.mainStreamConfig:this.secondaryStreamConfig)?.[t]??0}destroy(){this.cache.clear(),this.segmentChangeCallback=void 0}},Rt=class{#W;#ht="disconnected";#dt=null;#ct=0;#ut=null;#j=new rt;constructor(e){const t=Math.max(100,e.initialDelay??1e3);this.#W={url:e.url,initialDelay:t,maxDelay:Math.max(t,e.maxDelay??3e4),jitterMultiplier:Math.max(0,e.jitterMultiplier??.2)}}get state(){return this.#ht}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}connect(){if("connected"!==this.#ht&&"connecting"!==this.#ht&&"disposed"!==this.#ht){this.#ht="connecting",this.#ft();try{this.#dt=new WebSocket(this.#W.url),this.#dt.binaryType="arraybuffer",this.#dt.onopen=this.#gt,this.#dt.onclose=this.#mt,this.#dt.onerror=this.#pt,this.#dt.onmessage=this.#vt}catch(e){this.#ht="disconnected";const t=new ErrorEvent("error",{message:e instanceof Error?e.message:"Unknown WebSocket creation error",error:e});this.#j.dispatchEvent("error",t)}}}send(e){if("connected"!==this.#ht||!this.#dt)throw new Error("WebSocketClient: Cannot send data when not connected");this.#dt.send(e)}dispose(){this.#ht="disposed",this.#ft(),this.#dt&&(this.#dt.onopen=null,this.#dt.onclose=null,this.#dt.onerror=null,this.#dt.onmessage=null,this.#dt.close(),this.#dt=null),this.#j.clear()}#gt=()=>{"disposed"!==this.#ht&&(this.#ht="connected",this.#ct=0,this.#j.dispatchEvent("connected"))};#mt=()=>{"disposed"!==this.#ht&&(this.#dt&&(this.#dt.onopen=null,this.#dt.onclose=null,this.#dt.onerror=null,this.#dt.onmessage=null,this.#dt=null),this.#yt(),this.#j.dispatchEvent("disconnected"))};#pt=e=>{"disposed"!==this.#ht&&this.#j.dispatchEvent("error",e)};#vt=e=>{"disposed"!==this.#ht&&this.#j.dispatchEvent("message",e.data)};#yt(){if("disposed"===this.#ht)return;this.#ht="reconnecting";const e=Math.min(this.#W.initialDelay*Math.pow(2,this.#ct),this.#W.maxDelay),t=e*this.#W.jitterMultiplier,s=2*Math.random()*t-t,i=Math.max(0,e+s);e<this.#W.maxDelay&&this.#ct++,this.#ut=setTimeout(()=>{"disposed"!==this.#ht&&this.connect()},i),this.#j.dispatchEvent("reconnecting")}#ft(){null!==this.#ut&&(clearTimeout(this.#ut),this.#ut=null)}},Ct=class{#St=new Map;#j=new rt;addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}acquire(e){let t=this.#St.get(e);if(!t){const s=new Rt({url:e});s.addEventListener("error",t=>{this.#j.dispatchEvent("error",t,e)}),s.connect(),t={client:s,refCount:0},this.#St.set(e,t)}t.refCount++;let s=!1;return{client:t.client,release:()=>{s||(s=!0,t.refCount--,t.refCount<=0&&(t.refCount<0&&console.error(`[WebTorrentSocketPool] Negative refCount detected for ${e}`),this.#St.get(e)===t&&this.#St.delete(e),t.client.dispose()))}}}destroy(){this.#j.clear();const e=Array.from(this.#St.values());this.#St.clear();for(const t of e)try{t.client.dispose()}catch(e){console.error("[WebTorrentSocketPool] Failed to dispose WebSocketClient:",e)}}},Pt=class e{static DEFAULT_COMMON_CORE_CONFIG={segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:ft};static DEFAULT_STREAM_CONFIG={isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,preferP2PForEngineRequest:!1,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:65535,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:3e4,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:["wss://tracker.novage.com.ua","wss://tracker.openwebtorrent.com"],rtcConfig:{iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478"}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3};eventTarget=new rt;manifestResponseUrl;streams=new Map;mainStreamConfig;secondaryStreamConfig;commonCoreConfig;bandwidthCalculators={all:new tt,http:new tt};segmentStorage;webTorrentSocketPool=new Ct;socketPoolLogger=(0,Oe.default)("p2pml-core:webtorrent-socket-pool");peerId;mainStreamLoader;secondaryStreamLoader;streamDetails={isLive:!1,activeLevelBitrate:0};storageInitPromise;constructor(t){const s=function e(t){if(Ut(t)){const s={};return Object.keys(t).forEach(i=>{if(void 0!==t[i]){const r=e(t[i]);void 0!==r&&(s[i]=r)}}),s}return t}(t??{});this.commonCoreConfig=Gt({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:s}),this.mainStreamConfig=Gt({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.mainStream}),this.secondaryStreamConfig=Gt({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.secondaryStream}),this.peerId=function(e){const t=[e],s=20-e.length;for(let e=0;e<s;e++)t.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())]);return t.join("")}(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener("error",(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return{...Nt(this.commonCoreConfig),mainStream:Nt(this.mainStreamConfig),secondaryStream:Nt(this.secondaryStreamConfig)}}applyDynamicConfig(e){const{mainStream:t,secondaryStream:s}=e,i=Nt(this.mainStreamConfig),r=Nt(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,s),this.processSpecificDynamicConfigParams(i,e,"main"),this.processSpecificDynamicConfigParams(r,e,"secondary")}processSpecificDynamicConfigParams(e,t,s){const i=this.getUpdatedStreamProperty("isP2PDisabled",t,s);i&&e.isP2PDisabled!==i&&this.destroyStreamLoader(s);const r=this.getUpdatedStreamProperty("isP2PUploadDisabled",t,s);void 0!==r&&e.isP2PUploadDisabled!==r&&("main"===s?this.mainStreamLoader:this.secondaryStreamLoader)?.sendBroadcastAnnouncement(r)}getUpdatedStreamProperty(e,t,s){return("main"===s?t.mainStream:t.secondaryStream)?.[e]??t[e]}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split("?")[0]}hasSegment(e){return!!hs(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,{...e,segments:new Map})}updateStream(e,t,s){const i=this.streams.get(e);if(i){if(t)for(const e of t)i.segments.has(e.runtimeId)||i.segments.set(e.runtimeId,{...e,stream:i});if(s)for(const e of s)i.segments.delete(e);this.mainStreamLoader?.updateStream(i),this.secondaryStreamLoader?.updateStream(i)}}async loadSegment(e,t){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");await this.initializeSegmentStorage();const s=this.identifySegment(e);this.getStreamHybridLoader(s).loadSegment(s,t)}abortSegmentLoading(e){this.mainStreamLoader?.abortSegmentRequest(e),this.secondaryStreamLoader?.abortSegmentRequest(e)}updatePlayback(e,t){this.mainStreamLoader?.updatePlayback(e,t),this.secondaryStreamLoader?.updatePlayback(e,t)}setActiveLevelBitrate(e){e!==this.streamDetails.activeLevelBitrate&&(this.streamDetails.activeLevelBitrate=e,this.mainStreamLoader?.notifyLevelChanged(),this.secondaryStreamLoader?.notifyLevelChanged())}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{const t=this.identifySegment(e);return!("main"===t.stream.type&&this.mainStreamConfig.isP2PDisabled||"secondary"===t.stream.type&&this.secondaryStreamConfig.isP2PDisabled)}catch{return!1}}destroy(){this.streams.clear(),this.mainStreamLoader?.destroy(),this.secondaryStreamLoader?.destroy(),this.segmentStorage?.setSegmentChangeCallback(void 0),this.segmentStorage?.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}async initializeSegmentStorage(){if(!this.segmentStorage){if(this.storageInitPromise)return this.storageInitPromise;this.storageInitPromise=(async()=>{const{isLive:e}=this.streamDetails,t=this.commonCoreConfig.customSegmentStorageFactory;if(t&&"function"!=typeof t)throw new Error("Storage configuration is invalid");const s=t?t(e):new kt;try{await s.initialize(this.commonCoreConfig,this.mainStreamConfig,this.secondaryStreamConfig)}catch(e){throw s.destroy(),e}if(!this.storageInitPromise)return s.setSegmentChangeCallback(void 0),void s.destroy();s.setSegmentChangeCallback(e=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${e}`)}),this.segmentStorage=s})();try{await this.storageInitPromise}finally{this.storageInitPromise=void 0}}}identifySegment(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is undefined");const t=hs(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,s){$t(this.commonCoreConfig,e),$t(this.mainStreamConfig,e),$t(this.secondaryStreamConfig,e),t&&$t(this.mainStreamConfig,t),s&&$t(this.secondaryStreamConfig,s)}destroyStreamLoader(e){"main"===e?(this.mainStreamLoader?.destroy(),this.mainStreamLoader=void 0):(this.secondaryStreamLoader?.destroy(),this.secondaryStreamLoader=void 0)}getStreamHybridLoader(e){return"main"===e.stream.type?(this.mainStreamLoader??=this.createNewHybridLoader(e),this.mainStreamLoader):(this.secondaryStreamLoader??=this.createNewHybridLoader(e),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");if(!this.segmentStorage)throw new Error("Segment storage is not initialized");const t="main"===e.stream.type?this.mainStreamConfig:this.secondaryStreamConfig;return new bt(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}},Dt=Oe.debug}}),Go={};function Ho(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Wo(e){return"initSegment"!==e.sn}function qo(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function jo(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}function Ko(e,t){const s=Object.getPrototypeOf(e);if(s){return Object.getOwnPropertyDescriptor(s,t)||Ko(s,t)}}function Vo(e,t){const s=Ko(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}function Yo(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function zo(){return zo=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},zo.apply(null,arguments)}function Qo(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function Xo(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Qo(Object(s),!0).forEach(function(t){Yo(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Qo(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}function Jo(e,t){if(null==e)return{};var s,i,r=function(e,t){if(null==e)return{};var s={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;s[i]=e[i]}return s}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(i=0;i<n.length;i++)s=n[i],-1===t.indexOf(s)&&{}.propertyIsEnumerable.call(e,s)&&(r[s]=e[s])}return r}function Zo(e){switch(e.details){case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_TIMEOUT:case ws.LEVEL_LOAD_TIMEOUT:case ws.MANIFEST_LOAD_TIMEOUT:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.SUBTITLE_TRACK_LOAD_TIMEOUT:case ws.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function el(e){return e.details.startsWith("key")}function tl(e){return el(e)&&!!e.frag&&!e.frag.decryptdata}function sl(e,t){const s=Zo(t);return e.default[(s?"timeout":"error")+"Retry"]}function il(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function rl(e){return Xo(Xo({},e),{errorRetry:null,timeoutRetry:null})}function nl(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return al(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function al(e){return 0===e&&!1===navigator.onLine}function ol(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}function ll(){return zo({},Ns)}function hl(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Us}(e,s)}function dl(e=!0){if("undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function cl(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(e=>-1===i.indexOf(e))}function ul(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}function fl(e,t){if(e<0)return-fl(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}function gl(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)})}}}function ml(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function pl(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function vl(e,t){return ml(e,t)&&pl(e,t+6)+10<=e.length-t}function yl(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Sl(e,t){const s=t;let i=0;for(;ml(e,t);)i+=10,i+=pl(e,t+6),yl(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(s,s+i)}function El(e,t=0,s=1/0){return function(e,t,s,i){const r=ul(n=e)?n:n.buffer;var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(c=e)&&ul(c.buffer)&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/a,h=(o+t)/a,d=Math.floor(Math.max(0,Math.min(h,l)));var c;return new i(r,d,Math.floor(Math.min(d+Math.max(s,0),l))-d)}(e,t,s,Uint8Array)}function bl(e,t=!1){const s=t?e.indexOf(0):e.length,i=function(e,t={}){let s;s=ul(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0,{encoding:r}=t;if(!r){const e=s.getUint8(0),t=s.getUint8(1);239==e&&187==t&&191==s.getUint8(2)?(r=js,i=3):254==e&&255==t?(r=Ws,i=2):255==e&&254==t?(r=qs,i=2):r=js}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(s);const{byteLength:n}=s,a=r!==Ws;let o,l="";for(;i<n;){switch(r){case js:if(o=s.getUint8(i),o<128)i++;else if(o>=194&&o<=223)if(i+1<n){const e=s.getUint8(i+1);e>=128&&e<=191?(o=(31&o)<<6|63&e,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=n-1){const e=s.getUint8(i+1),t=s.getUint8(i+2);e>=128&&e<=191&&t>=128&&t<=191?(o=(15&o)<<12|(63&e)<<6|63&t,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=n-1){const e=s.getUint8(i+1),t=s.getUint8(i+2),r=s.getUint8(i+3);e>=128&&e<=191&&t>=128&&t<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&e)<<12|(63&t)<<6|63&r,i+=4):i++}else i++;else i++;break;case Ws:case Hs:case qs:o=s.getUint16(i,a),i+=2}l+=String.fromCodePoint(o)}return l}(new DataView(e.buffer,e.byteOffset,s),{encoding:js});return t?i:i.replace(/\0/g,"")}function Tl(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=bl(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=bl(e.data.subarray(t),!0);t+=s.length+1;const i=bl(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=bl(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?function(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=bl(El(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=bl(El(e.data,3+s,n));let o;var l;return o="--\x3e"===i?bl(El(e.data,4+s+n)):ul(l=e.data.subarray(4+s+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const{data:s}=e,i=bl(s.subarray(t),!0);t+=i.length+1;const r=bl(s.subarray(t));return{key:e.type,info:i,data:r}}const t=bl(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function wl(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=pl(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}function Il(e){let t=0;const s=[];for(;ml(e,t);){const i=pl(e,t+6);e[t+5]>>6&1&&(t+=Ks),t+=Ks;const r=t+i;for(;t+Vs<r;){const i=wl(e.subarray(t)),r=Tl(i);r&&s.push(r),t+=i.size+Ks}yl(e,t)&&(t+=Ks)}return s}function Ll(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Al(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function kl(e){const t=Il(e);for(const e of t)if(Ll(e))return Al(e)}function Rl(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Cl(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Pl(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Dl(e){return String.fromCharCode.apply(null,e)}function Ml(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function _l(e,t){const s=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return s<0?4294967296+s:s}function Ol(e,t){let s=_l(e,t);return s*=Math.pow(2,32),s+=_l(e,t+4),s}function xl(e,t){let s="";for(let i=t;i<e.length;i++)if(s+=String.fromCharCode(e[i]),0===e[i])return s;return null}function Fl(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Bl(e,t,s){e[t]=s>>24,e[t+1]=s>>16&255,e[t+2]=s>>8&255,e[t+3]=255&s}function Ul(e,t,s){const i=t.byteOffset-e.byteOffset-8,r=8+s,n=t.byteLength+8-r;n<8||(Bl(e,i,r),Bl(e,i+r,n),Bl(e,i+r+4,zs.free))}function Nl(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function $l(e,t){t.sort((e,t)=>e[0]-t[0]);const s=t.reduce((e,[t,s])=>e+s-t,0),i=new Uint8Array(e.byteLength-s);let r=0,n=0;for(let s=0;s<t.length;s++){const[a,o]=t[s];i.set(e.subarray(r,a),n),n+=a-r,r=o}return i.set(e.subarray(r),n),{result:i,dropped:s,droppedBefore:e=>t.reduce((t,[s,i])=>i<=e?t+i-s:t,0)}}function Gl(e,t){const s=[];return t.length?(Hl(e,t,0,0,e.byteLength,s),s):s}function Hl(e,t,s,i,r,n){const a=t[s];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),d=a.charCodeAt(3),c=t.length-1;for(let a=i;a<r;){const i=a+8<=r,u=a+4<=r?16777216*e[a]+(e[a+1]<<16|e[a+2]<<8|e[a+3]):_l(e,a),f=u>1?a+u:r;if(i&&e[a+4]===o&&e[a+5]===l&&e[a+6]===h&&e[a+7]===d){const i=Math.min(f,r);s===c?n.push(e.subarray(a+8,i)):Hl(e,t,s+1,a+8,i,n)}a=f}}function Wl(e){const t=[],s=e[0];let i=8;const r=_l(e,i);i+=4;let n=0,a=0;0===s?(n=_l(e,i),a=_l(e,i+4),i+=8):(n=Ol(e,i),a=Ol(e,i+8),i+=16),i+=2;let o=e.length+a;const l=Ml(e,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=_l(e,s);s+=4;const a=2147483647&n;if(1==(2147483648&n)>>>31)return Gs.warn("SIDX has hierarchical references (not supported)"),null;const l=_l(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function ql(e){const t=[],s=Gl(e,["moov","trak"]);for(let e=0;e<s.length;e++){const i=s[e],r=Gl(i,["tkhd"])[0];if(r){let e=r[0];const s=_l(r,0===e?12:20),n=Gl(i,["mdia","mdhd"])[0];if(n){e=n[0];const r=_l(n,0===e?12:20),a=Gl(i,["mdia","hdlr"])[0];if(a){const e=Dl(a.subarray(8,12)),n={soun:Ds.AUDIO,vide:Ds.VIDEO}[e],o=jl(Gl(i,["mdia","minf","stbl","stsd"])[0]);n?(t[s]={timescale:r,type:n,stsd:o},t[n]=Xo({timescale:r,id:s},o)):t[s]={timescale:r,type:e,stsd:o}}}}}return Gl(e,["moov","mvex","trex"]).forEach(e=>{const s=_l(e,4),i=t[s];i&&(i.default={duration:_l(e,12),sampleSize:_l(e,16),flags:_l(e,20)})}),t}function jl(e){const t=e.subarray(8),s=t.subarray(86),i=Dl(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=Gl(t,[i])[0];Gl(e.subarray("enca"===i?28:78),["sinf"]).forEach(e=>{const t=Gl(e,["schm"])[0];if(t){const s=Dl(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Gl(e,["frma"])[0];t&&(n=Dl(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Gl(s,["avcC"])[0];e&&e.length>3&&(n+="."+Yl(e[1])+Yl(e[2])+Yl(e[3]),r=Kl("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=Gl(t,[i])[0],s=Gl(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=Vl(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=Vl(s,e);const i=s[e++];if(64!==i)break;if(n+="."+Yl(i),e+=12,5!==s[e++])break;e=Vl(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=Gl(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=_l(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];(t||h)&&(h="."+t.toString(16).toUpperCase()+h)}n+=h}r=Kl("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Kl(n,s)||n;break;case"vp09":{const e=Gl(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+zl(t)+"."+zl(s)+"."+zl(i)}break}case"av01":{const e=Gl(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,v=0;n+="."+t+"."+zl(i)+a+"."+zl(h)+"."+d+"."+c+u+f+"."+zl(g)+"."+zl(m)+"."+zl(p)+"."+v,r=Kl("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function Kl(e,t){const s=Gl(t,["dvvC"]),i=s.length?s[0]:Gl(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+zl(t)+"."+zl(s)}}function Vl(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function Yl(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function zl(e){return(e<10?"0":"")+e}function Ql(e,t){Gl(e,["moov","trak"]).forEach(e=>{const s=Gl(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=Gl(i,["enca"]);const n=r.length>0;n||(r=Gl(i,["encv"])),r.forEach(e=>{Gl(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const s=Xl(e);s&&t(s,n)})})})}function Xl(e){const t=Gl(e,["schm"])[0];if(t){const s=Dl(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Gl(e,["schi","tenc"])[0];if(t)return t}}}function Jl(e){return"undefined"==typeof TextDecoder?bl(e):(Xs||(Xs=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function Zl(e,t,s,i,r){const n={};let a=!1;const o=function(e){const t=e.byteLength,s=[];for(let i=0;i<t;){const r=i+8<=t,n=i+4<=t?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):_l(e,i),a=n>1?i+n:t;if(r&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7]){const r=Math.min(a,t);for(let t=i+8;t<r;){const n=t+8<=r,a=t+4<=r?16777216*e[t]+(e[t+1]<<16|e[t+2]<<8|e[t+3]):_l(e,t),o=a>1?t+a:r;if(n&&116===e[t+4]&&114===e[t+5]&&97===e[t+6]&&102===e[t+7]){const n=Math.min(o,r);let a,l;const h=[];for(let s=t+8;s<n;){const t=s+8<=n,i=s+4<=n?16777216*e[s]+(e[s+1]<<16|e[s+2]<<8|e[s+3]):_l(e,s),r=i>1?s+i:n;if(t&&116===e[s+4]){const t=Math.min(r,n);102===e[s+5]&&104===e[s+6]&&100===e[s+7]?l||(l=e.subarray(s+8,t)):102===e[s+5]&&100===e[s+6]&&116===e[s+7]?a||(a=e.subarray(s+8,t)):114===e[s+5]&&117===e[s+6]&&110===e[s+7]&&h.push(e.subarray(s+8,t))}s=r}s.push({moofOffset:e.byteOffset+i,tfdt:a,tfhd:l,truns:h})}t=o}}i=a}return s}(e),l=e.byteLength;for(let c=0;c<o.length;c++){const{moofOffset:u,tfdt:f,tfhd:g,truns:m}=o[c],p=_l(g,4),v=t[p];if(!v)continue;const y=n[p]||(n[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type});let S;if(f){const e=f[0];S=_l(f,4),1===e&&(S===Ys?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Ys+1,S+=_l(f,8))),Ss(S)&&(!Ss(y.start)||S<y.start)&&(y.start=S),r&&Ss(S)&&(r.timeOffset=S/r.timescale)}const E=(null==r?void 0:r.trackId)===p&&v.type===Ds.VIDEO,b=v.default,T=16777215&_l(g,0);let w,I=(null==b?void 0:b.duration)||0,L=(null==b?void 0:b.sampleSize)||0,A=8;1&T&&(A+=8),2&T&&(A+=4),8&T&&(I=_l(g,A),w=g.byteOffset-e.byteOffset+A,A+=4),16&T&&(L=_l(g,A));let k=0;const R=!!(1&T),C=!R&&!!(131072&T);R?(k=_l(g,8),k*=Math.pow(2,32),k+=_l(g,12)):C&&(k=u);let P=S||0,D=0,M=I;for(let t=0;t<m.length;t++){const s=m[t],n=_l(s,4),a=y.sampleCount;y.sampleCount+=n;const o=1&s[3];let c=0;const u=4&s[3],f=1&s[2],g=2&s[2],p=4&s[2],v=8&s[2];let S=8;o&&(c=Fl(s,S),S+=4),u&&(1&s[S+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=a),S+=4);let b,T,A,R=k+c;if(!i&&0===s[1]&&6===s[2]&&1===s[3]){var h,d;const t=P,i=R,a=S;let o=-1,c=0,u=0,f=null!=(h=null==r?void 0:r.timeOffset)?h:0;const g=I/(null!=(d=null==r?void 0:r.timescale)?d:1),m=!0===(null==r?void 0:r.isHEVCFlavor),p=m?2:1;for(let t=0;t<n;t++){const i=0===s[S]?s[S+1]<<16|s[S+2]<<8|s[S+3]:_l(s,S),n=-1===o&&void 0===y.keyFrameIndex&&!(1&s[S+5]);S+=8;const a=R+i;if(E){if(i>0){let t=R;do{const s=0===e[t]?e[t+1]<<16|e[t+2]<<8|e[t+3]:_l(e,t);t+=4;const i=e[t],n=m?i>>1&63:31&i;(m?39===n||40===n:6===n)&&ih(e.subarray(t,t+s),p,f,r.samples),t+=s}while(t<a)}f+=g}R=a,n&&(o=t,c=R)}if(R<=l)u=n;else{let e=i,t=a;for(let i=0;i<n&&(e+=0===s[t]?s[t+1]<<16|s[t+2]<<8|s[t+3]:_l(s,t),!(e>l));i++)u=i+1,t+=8}if(E&&(r.timeOffset=f),-1!==o&&c<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=o,y.keyFrameStart=t+o*I),u){(!Ss(y.ptsMin)||t<y.ptsMin)&&(y.ptsMin=t);const e=t+u*I;(!Ss(y.ptsMax)||e>y.ptsMax)&&(y.ptsMax=e)}const v=I*n;P=t+v,D+=v;continue}i&&(b=[],T={sampleOffset:R,samples:b,defaultSampleDurationOffset:w},R<=l&&y.trun.push(T));for(let t=0;t<n;t++){let n,a,o;f?(i&&(n=s.byteOffset-e.byteOffset+S),M=_l(s,S),S+=4):M=I,g?(A=_l(s,S),S+=4):A=L,p&&(o=1&s[S+1]?1:0,i&&(a={isNonSync:o,dependsOn:1==(3&s[S])?1:2}),S+=4);let h=0;if(v&&(h=0===s[0]?_l(s,S):Fl(s,S),S+=4),E){let t=R,s=0;for(;s<A;){const i=_l(e,t);t+=4,sh(r.isHEVCFlavor,e[t])&&ih(e.subarray(t,t+i),r.isHEVCFlavor?2:1,r.timeOffset+h/r.timescale,r.samples),t+=i,s+=i+4}r.timeOffset+=M/r.timescale}if(R+=A,R<=l){T&&void 0!==n&&(T.lastSampleDurationOffset=n),0===o&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=t,y.keyFrameStart=P);const e=P+h;(!Ss(y.ptsMin)||e<y.ptsMin)&&(y.ptsMin=e),(!Ss(y.ptsMax)||e+M>y.ptsMax)&&(y.ptsMax=e+M),b&&(b[t]={cts:h,duration:M,flags:a,size:A})}P+=M,D+=M}!D&&I&&(D+=I*n)}y.duration+=D,y.duration&&(a=!0)}if(!a){let t=1/0,s=0;const i=Gl(e,["sidx"]);for(let e=0;e<i.length;e++){const r=Wl(i[e]);if(null!=r&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);const e=r.references.reduce((e,t)=>e+t.info.duration||0,0);s=Math.max(s,e+r.earliestPresentationTime/r.timescale)}}s&&Ss(s)&&Object.keys(n).forEach(e=>{n[e].duration||(n[e].duration=s*n[e].timescale-n[e].start)})}return n}function eh(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function th(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function sh(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6==(31&t)}function ih(e,t,s,i){const r=rh(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){Gs.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=Ml(r,t);if(t+=2,49===e){const e=_l(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:Jl(l),userDataBytes:l})}}}function rh(e){const t=e.byteLength;let s,i=e.indexOf(3,3);for(;-1!==i;)0===e[i-1]&&0===e[i-2]&&(s||(s=[])).push(i),i=e.indexOf(3,i+1);if(!s)return e;const r=t-s.length,n=new Uint8Array(r);let a=0,o=0;for(let t=0;t<r;o++,t++)o===s[a]&&(o++,a++),n[t]=e[o];return n}function nh(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let i=0;for(;i+32<s;){const s=ah(new DataView(e,i));t.push(s),i+=s.size}}return t}function ah(e){const t=e.getUint32(0),s=e.byteOffset,i=e.byteLength;if(i<t)return{offset:s,size:i};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:t};const n=e.buffer,a=Rl(new Uint8Array(n,s+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=e.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,s+32+16*e,16));h=32+16*r}if(!h)return{offset:s,size:t};const d=e.getUint32(h);return t-32<d?{offset:s,size:t}:(l=new Uint8Array(n,s+h+4,d),0===r&&(o=function(e){const t=[];for(let s=0;s<e.length;){const i=e[s++],r=7&i;if(0===r){for(;128&e[s++];);continue}if(2!==r){s+=1===r?8:4;continue}let n=0;for(let t=0,i=128;128&i;t+=7)n|=(127&(i=e[s++]))<<t;if(i>>3==2)if(32===n){const i=new Uint8Array(16);for(let t=0;t<16;t++)i[t]=parseInt(String.fromCharCode(e[s+2*t],e[s+2*t+1]),16);t.push(i)}else 16===n&&t.push(e.subarray(s,s+16));s+=n}return t}(l)),{version:r,systemId:a,kids:o,data:l,offset:s,size:t})}function oh(e){try{return navigator[e]||""}catch(e){}return""}function lh(){if(void 0===ei){const e=Js.match(/Chrome\/(\d+)/i);ei=e?parseInt(e[1]):0}return ei}function hh(){return/\(Windows.+Firefox\//i.test(Js)}function dh(e,t){const s=ii[t];return!!s&&!!s[e.slice(0,4)]}function ch(e,t,s=!0){return!e.split(",").some(e=>!uh(e,t,s))}function uh(e,t,s=!0){var i;const r=dl(s);return null!=(i=null==r?void 0:r.isTypeSupported(fh(e,t)))&&i}function fh(e,t){return`${t}/mp4;codecs=${e}`}function gh(e){if(e){const t=e.substring(0,4);return ii.video[t]}return 2}function mh(e){const t=hh();return e.split(",").reduce((e,s)=>{const i=t&&th(s)?9:ii.video[s];return i?(2*i+e)/(e?3:2):(ii.audio[s]+e)/(e?2:1)},0)}function ph(e,t=!0){return e.replace(ni,e=>function(e,t=!0){if(ri[e])return ri[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(uh(s[r],"audio",t))return ri[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=dl(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function vh(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(yh(e,"audio")||yh(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function yh(e,t){return dh(e,t)&&uh(e,t)}function Sh(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function Eh(e){const t=dl(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function bh(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function Th(e,t){return{supported:!1,configurations:t,decodingInfoResults:[ai],error:e}}function wh(e,t,s,i,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,s)=>{if(s){const i=t.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(t=>{e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>th(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(r,8e6))||!!c&&Ss(d)&&Object.keys(c).some(e=>parseInt(e)>d)}function Ih(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(oi);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Ah(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map(e=>{const t={contentType:fh(Sh(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Ah(e);return r&&e.audioGroups?e.audioGroups.reduce((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:fh(t,"audio"),bitrate:s?Lh(t,n):n};i&&(r.channels=""+i),e.push(r)})}return e},e):e},[]):[]}(e,t,o>0),h=l.length;for(let e=o||1*h||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),h){t.audio=l[e%h];const s=t.audio.bitrate;t.video&&s&&(t.video.bitrate-=s)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>th(e))&&hh())return Promise.resolve(Th(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:s,video:i}=e;return i&&(t+=`${bh(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`),s&&(t+=`${i?"_":""}${bh(s.contentType)}_c${s.channels}`),t}(e);return i[t]||(i[t]=s.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Lh(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Ah(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function kh(e,t,s){const i=encodeURIComponent(t),r=`${i}=${encodeURIComponent(s)}`;let n=!1;const a=[];e.search.substring(1).split("&").forEach(e=>{e===i||e.startsWith(i+"=")?n||(a.push(r),n=!0):e&&a.push(e)}),n||a.push(r),e.search=a.join("&")}function Rh(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?di.v2:di.Yes:di.No}function Ch(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Ph(e,t){Gs.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Dh(e){return e.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Mh(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function _h(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let i=0;i<t.length;i++)if(Oh(e,t[i],s))return i;return-1}function Oh(e,t,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const s=e.split(","),i=t.split(",");return s.length===i.length&&!s.some(e=>-1===i.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===s||s(e,t))}function xh(e,t){const{audioCodec:s,channels:i}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Fh(e,t,s){for(let i=t;i>-1;i--)if(s(e[i]))return i;for(let i=t+1;i<e.length;i++)if(s(e[i]))return i;return-1}function Bh(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}function Uh(e,t){return!t||-1!==t.indexOf(e)}function Nh(e,t){if(t||e){const s=zo({},t);return e&&(e.videoCodec&&(s.videoCodec=e.videoCodec),e.videoRange&&(s.allowedVideoRanges=[e.videoRange])),s}}function $h(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Gh(s,i,n)||function(e,t,s){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=pi.search(t,Gh.bind(null,s,i));return!a||a===e&&n?n:a}function Gh(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function Hh(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function Wh(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),pi.search(i,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0)),n||null}return null}function qh(e,t,s){return s&&t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}function jh(e){const t=e.details;return t===ws.BUFFER_ADD_CODEC_ERROR||t===ws.MEDIA_SOURCE_REQUIRES_RESET||t===ws.BUFFER_APPEND_ERROR&&!Kh(e)}function Kh(e){return e.details===ws.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function Vh(e){const t={action:vi.DoNothing,flags:yi.None};return e&&(t.resolved=!0),t}function Yh(e){var t,s,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(r=e.range.subs)&&r.partial)}function zh(e){return`${e.type}_${e.level}_${e.sn}`}function Qh(e,t){return e.filter(e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s})}function Xh(e,t=null,s){const i=t||e,r={type:Cs.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=Jh(e,t,s);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function Jh(e,t=null,s){const i={},r=t||e,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;var o,l;if(Ss(n)&&Ss(a))if("initSegment"!==e.sn&&!s||"AES-128"!==(l=null==(o=e.decryptdata)?void 0:o.method)&&"AES-256"!==l)i.byteRange={start:n,end:a};else{let e=16*Math.floor(n/16);const t=16*Math.ceil(a/16);i.decryptRange={start:n-e,end:a-e},e>=16&&(i.resetIV=!0,e-=16),i.byteRange={start:e,end:t}}return i}function Zh(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:Ts.MEDIA_ERROR,details:ws.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Ci(i)}function ed(e){return Oi.test(e)}function td(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(Oi,t=>{const i=t.substring(2,t.length-1),r=null==s?void 0:s[i];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),t):r})}return t}function sd(e,t,s){let i,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=e.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else i=t.NAME,r=t.VALUE;i in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function id(e,t,s){const i=t.IMPORT;if(s&&i in s){let t=e.variableList;t||(e.variableList=t={}),t[i]=s[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function rd(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function nd(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}function ad(e,t){return e.length===t.length&&!e.some((e,s)=>e!==t[s])}function od(e,t){return!e&&!t||!(!e||!t)&&ad(e,t)}function ld(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function hd(e){switch(e){case"AES-128":case"AES-256":return Ti.cbc;case"AES-256-CTR":return Ti.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function dd(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function cd(e){const t=function(e,t,s){const i=e[t];e[t]=e[s],e[s]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ud(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),i=e[e.length-1].split(",");if(2===i.length){const t="base64"===i[0],r=i[1];t?(e.splice(-1,1),s=Pl(r)):s=function(e){const t=dd(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}(r)}}return s}function fd(e){switch(e){case Hi.FAIRPLAY:return Gi.FAIRPLAY;case Hi.PLAYREADY:return Gi.PLAYREADY;case Hi.WIDEVINE:return Gi.WIDEVINE;case Hi.CLEARKEY:return Gi.CLEARKEY}}function gd(e){switch(e){case Gi.FAIRPLAY:return Hi.FAIRPLAY;case Gi.PLAYREADY:return Hi.PLAYREADY;case Gi.WIDEVINE:return Hi.WIDEVINE;case Gi.CLEARKEY:return Hi.CLEARKEY}}function md(e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?[Gi.FAIRPLAY,Gi.WIDEVINE,Gi.PLAYREADY,Gi.CLEARKEY].filter(e=>!!t[e]):[];return!i[Gi.WIDEVINE]&&s&&i.push(Gi.WIDEVINE),i}function pd(e){const t=Dl(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),s=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=Pl(e).subarray(0,16);return cd(t),t}}return null}function vd(e){const t=null==e?void 0:e[Hi.PLAYREADY];if(t){const e=ud(t.uri);if(e)return pd(e)}return null}function yd(e,t,s,i,r,n){var a;if(void 0===t)return null;const o=td(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Ji.resolve(o,s)},h=e.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),wd(e.CODECS,l);const d=e["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},wd(d,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function Sd(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=Ed(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function Ed(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;var a;if(t>=o||0===i)if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length)for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}return r}}return-1}function bd(e,t,s){var i,r;const n=new Bi(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Gs.error(`Invalid IV: ${n.IV}`);const c=o?Ji.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ki(a,c,d,u,l,n.KEYID)}function Td(e){const t=new Bi(e).decimalFloatingPoint("TIME-OFFSET");return Ss(t)?t:null}function wd(e,t){let s=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text","image"].forEach(e=>{const i=s.filter(t=>dh(t,e));i.length&&(t[`${e}Codec`]=i.map(e=>e.split("/")[0]).join(","),s=s.filter(e=>-1===i.indexOf(e)))}),t.unknownCodecs=s}function Id(e,t,s){const i=t[s];i&&(e[s]=i)}function Ld(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ad(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function kd(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||i.push(e)}function Rd(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Cd(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function Pd(e,t){const s=t.startPTS;if(Ss(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Dd(e,t,s,i,r,n,a,o){i-s<=0&&(o.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let l=s,h=i;const d=t.startPTS,c=t.endPTS;if(Ss(d)){const a=Math.abs(d-s);e&&a>e.totalduration?o.warn(`media timestamps and playlist times differ by ${a}s for level ${t.level} ${e.url}`):Ss(t.deltaPTS)?t.deltaPTS=Math.max(a,t.deltaPTS):t.deltaPTS=a,l=Math.max(s,d),s=Math.min(s,d),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,h=Math.min(i,c),i=Math.max(i,c),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const u=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=l,t.startDTS=r,t.endPTS=i,t.minEndPTS=h,t.endDTS=n;const f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let g;const m=f-e.startSN,p=e.fragments;for(p[m]=t,g=m;g>0;g--)Pd(p[g],p[g-1]);for(g=m;g<p.length-1;g++)Pd(p[g],p[g+1]);return e.fragmentHint&&Pd(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function Md(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function _d(e,t,s=!0,i){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==i||i.log(`Aligning playlists based on SN ${t.startSN} (diff: ${o})`);else if(a&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==i||i.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${o})`);else if(a&&s)o=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==i||i.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${o})`)}return function(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function Od(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function xd(e,t,s){var i;if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,(null==(i=r)?void 0:i.sn)===t?r:s&&t<e.startSN&&s.sn===t?s:null)}function Fd(e,t,s){return e?Bd(e.partList,t,s):null}function Bd(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Ud(e){e.forEach((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Nd(e,t){return!(e===t||!t)&&$d(e)!==$d(t)}function $d(e){return e.replace(/\?[^?]*$/,"")}function Gd(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function Hd(e,t){const s=e.start+t;e.setStart(s)}function Wd(e,t){const s=t.fragments;for(let t=0,i=s.length;t<i;t++)Hd(s[t],e);t.fragmentHint&&Hd(t.fragmentHint,e),t.alignedSliding=!0}function qd(e,t,s){e&&(function(e,t,s){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),r=Gd(t.fragments,i),n=Gd(e.fragments,i);if(!r||!n)return;const a=r.start-n.start;s.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Wd(a,e)}(t,e,s),t.alignedSliding||function(e,t,s){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,r=t.fragments;if(!i.length||!r.length)return;let n,a;const o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(n=Gd(r,o),a=Gd(i,o)),n&&a||(n=r[Math.floor(r.length/2)]||r.filter(e=>!!e)[0],a=Gd(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,h=a.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,e.totalduration))return void s.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${e.totalduration})`);const c=d-(a.start-n.start);s.log(`Aligning playlists using PDT (diff: ${c})`),Wd(c,e)}(t,e,s),t.alignedSliding||t.skippedSegments||_d(e,t,!1,s))}function jd(e,t,s){Kd(e,t,s),e.addEventListener(t,s)}function Kd(e,t,s){e.removeEventListener(t,s)}function Vd(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t}function Yd(e,t,s){if(t)for(let i=t.length;i--;){const r=t[i].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(e.start>=n&&e.end<=a)return!0;if(s>e.start&&e.end>n&&e.start<a)return!0}}return!1}function zd(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}function Qd(e,t){return 255===e[t]&&240==(246&e[t+1])}function Xd(e,t){return 1&e[t+1]?7:9}function Jd(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Zd(e,t){return t+1<e.length&&Qd(e,t)}function ec(e,t){if(Zd(e,t)){const s=Xd(e,t);if(t+s>=e.length)return!1;const i=Jd(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||Zd(e,r)}return!1}function tc(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h,d=n;5!==a&&29!==a||(d-=3);const c=(14&d)>>1,u=(1&d)<<7|o<<3;let f=0;if(1===a&&n>=6){f=5;const e=n-3;h=[f<<3|c,u|(14&e)>>1,(1&e)<<7|8,0]}else h=[a<<3|c,u];const g="mp4a.40."+(f||a);return Gs.log(`manifest codec:${i}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${n} esds config:[${h.join(",")}])`),{config:h,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:i}}(t,s,i,r);if(!n)return;zo(e,n)}}function sc(e){return 9216e4/e}function ic(e,t,s,i,r){const n=i+r*sc(e.samplerate),a=function(e,t){const s=Xd(e,t);if(t+s<=e.length){const i=Jd(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;return o=new Uint8Array(l),o.set(t.subarray(s,t.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function rc(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}function nc(e,t,s,i,r){if(s+24>t.length)return;const n=ac(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function ac(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*dr[14*(3===s?3-i:3===i?3:4)+r-1],h=cr[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=ur[s][i],u=fr[i],f=8*c*u,g=Math.floor(c*l/h+a)*u,m=lh();return!!m&&m<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function oc(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function lc(e,t){return t+1<e.length&&oc(e,t)}function hc(e,t){if(t+1<e.length&&oc(e,t)){const s=4,i=ac(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||lc(e,n)}return!1}function dc(e,t,s,i,r){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const h=t[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(t[s+6]<<8|t[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}function cc(e,t){return Ss(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}function uc(e,t){return((31&e[t+1])<<8)+e[t+2]}function fc(e,t){return(31&e[t+10])<<8|e[t+11]}function gc(e,t,s,i,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<h;){const h=uc(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){pc("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=h);break;case 21:-1===l.id3Pid&&(l.id3Pid=h);break;case 219:if(!i){pc("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=h);break;case 3:case 4:s.mpeg||s.mp3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){pc("AC-3",n);break}case 129:s.ac3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0){let i=t+5,r=d;for(;r>2;){switch(e[i]){case 106:-1===l.audioPid&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=h,n.log(`KLV metadata PID found: ${h}`))}const t=e[i+1]+2;i+=t,r-=t}}break;case 194:case 135:return mc(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=h,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=d+5}return l}function mc(e,t,s,i,r){r.warn(`parsing error: ${t.message}`),e.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:s,error:t,reason:t.message})}function pc(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function vc(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=eh(l[0],l[1]),l.splice(1,1);if(s=l[0],1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}function yc(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}function Sc(e,t=!1){return yc(e,1e3,1/$r,t)}function Ec(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}function bc(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}function Tc(e,t){let s;if(null===t)return e;for(s=t<e?-Gr:Gr;Math.abs(e-t)>4294967296;)e+=s;return e}function wc(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=Tc(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=Tc(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Ic(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let n=0;n<i;n++){const i=e.samples[n];i.pts=Tc(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function Lc(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function Ac(e,t,s){const i=e.codec;return i&&i.length>4?i:t===Ds.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?ph(i,!1):(s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):"mjpg"===i?i:(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}function kc(e){return"then"in e&&e.then instanceof Function}function Rc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!Cc(e[s].attrs,t[s].attrs))return!1;return!0}function Cc(e,t,s){const i=e["STABLE-RENDITION-ID"];return i&&!s?i===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>e[s]!==t[s])}function Pc(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Dc(e){return"audio"===e?1:0}function Mc(e,t){return`${e?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function _c(e){return`${e.type}_${e.sn}_${e.level}`}function Oc(e,t){const{start:s,end:i}=t;let r=0;for(let t=0;t<e.length;t++){const n=e[t];if(n.start>=i)break;const a=Math.max(s,n.start),o=Math.min(i,n.end);o>a&&(r+=o-a)}return r}function xc(e,t){return t.duration-e<=nn}function Fc(e,t,s){return function(e,t,s,i){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}("serialize",e,t,s)}function Bc(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Fc(e,mn);return e.toString()}function Uc(e){const t=fl(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Fc(e,gn);const s=t.toString();return s.includes(".")?s:`${s}.0`}function Nc(e){const t=(s=e).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Fc(t,Sn);return t}function $c(e){switch(typeof e){case"number":if(!Ss(e))throw Fc(e,cn);return Number.isInteger(e)?Bc(e):Uc(e);case"string":return function(e){if(vn.test(e))throw Fc(e,pn);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Nc(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fc(e,un);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Bc(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw Fc(e,fn);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}(e);if(e instanceof yn)return Nc(e);default:throw Fc(e,cn)}}function Gc(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fc(e,En);return e}function Hc(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${Gc(e)}`:`;${Gc(e)}=${$c(t)}`).join("")}function Wc(e){return e instanceof hn?`${$c(e.value)}${Hc(e.params)}`:$c(e)}function qc(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Fc(e,dn);const s=e instanceof Map?e.entries():Object.entries(e),i=null!=t&&t.whitespace?" ":"";return Array.from(s).map(([e,t])=>{t instanceof hn==0&&(t=new hn(t));let s=Gc(e);var i;return!0===t.value?s+=Hc(t.params):(s+="=",Array.isArray(t.value)?s+=`(${(i=t).value.map(Wc).join(" ")})${Hc(i.params)}`:s+=Wc(t)),s}).join(`,${i}`)}(e,t)}function jc(e){return Gn.test(e)}function Kc(e){return Hn.has(e)||jc(e)}function Vc(e){return qn.has(e)}function Yc(e){return Kc(e)||Vc(e)||jn.has(e)}function zc(e){return Yn.has(e)||jc(e)}function Qc(e){return zn.has(e)}function Xc(e){return"number"==typeof e?Ss(e):null!=e&&""!==e&&!1!==e}function Jc(e,t){if(Array.isArray(e)){let s;return t&&(s=e.find(e=>{var s;return(null==(s=e.params)?void 0:s.ot)===t})),s||(s=e[0]),Jc(s)}return e instanceof hn?e.value:e}function Zc(e,t={}){const s={};if(null==e||"object"!=typeof e)return s;const i=t.version||e.v||Pn,r=t.reportingMode||Un,n=1===i?function(e){const t={};for(const[i,r]of Object.entries(e))if(null!=r)if("nor"===i){const e=(Array.isArray(r)?r:[r])[0];var s;e instanceof hn?(t.nor=e.value,null!=(s=e.params)&&s.r&&(t.nrr=e.params.r)):t.nor=e}else Kn.has(i)?t[i]=Jc(r,e.ot):t[i]=r;else t[i]=r;return t}(e):e,a=1===i?zc:Qn[r];let o=Object.keys(n).filter(a);n.e&&n.e!==_n&&(o=o.filter(e=>!Vc(e)));const l=t.filter;"function"==typeof l&&(o=o.filter(l));const h=r===Bn;if(h){const e=n.e;o.includes("e")||null==e||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==n.cen||e!==On||o.push("cen");const t=e?Fn.get(e):void 0;t&&null!=n[t]&&!o.includes(t)&&o.push(t)}if(0===o.length)return s;i>1&&!o.includes("v")&&o.push("v");const d={version:i,reportingMode:r,baseUrl:t.baseUrl};o.sort();for(const e of o){var c,u;let r=n[e];const a=null!=(c=null==(u=t.formatters)?void 0:u[e])?c:Cn[e];if("function"==typeof a&&(r=a(r,d)),"v"===e){if(1===i)continue;r=i}if("pr"===e&&1===r&&(!h||n.e!==Dn))continue;h&&"ts"===e&&!Ss(r)&&(r=Date.now());const o=h&&!1===r&&"bg"===e&&n.e===Mn;(Xc(r)||o)&&(Qc(e)&&"string"==typeof r&&(r=new yn(r)),s[e]=r)}return s}function eu(e){return qc(e,{whitespace:!1})}function tu(e,t,s){var i;const r=new Set(null!=(i=t.enabledKeys)?i:[]);return{version:t.version||Pn,reportingMode:e,filter:e=>r.has(e),baseUrl:s}}function su(e){const{url:t}=e,s=Jo(e,bn);return fetch(t,s)}function iu(e){return Object.keys(e).every(jc)}function ru(e,t,s,i){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=zo({},e);return n.details=void 0,n.attrs=new Bi(n.attrs),n.url=n.attrs.URI=nu(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n});e.push(...n)})}function nu(e,t,s,i){if(t){const{[s]:e}=i;if(e){const s=e[t];if(s)return s}}const{HOST:r,PARAMS:n}=i,a=new self.URL(e);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(e=>{e&&kh(a,e,n[e])}),a.href}function au(e,t){const s=e.keyId,i=t.mediaKeysSession;if(s&&i){const e=t.mediaKeysSession.keyStatuses;if(e.size)return e.has(s)?e.get(s):t.keyStatuses[Rl(s)]}}function ou(e,t){const s="output-restricted"===e,i=s?ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Sa({type:Ts.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}function lu(e){return new Promise((t,s)=>e.resolved?t():e.errored?s(e.errored):(e.on("error",s),void e.on("resolved",t)))}function hu(e){function t(e,t,s,i){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(i||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}function du(e,t,s,i){const r=i?e.split(i):[e];for(const e in r){if("string"!=typeof r[e])continue;const i=r[e].split(s);2===i.length&&t(i[0],i[1])}}function cu(e,t,s){const i=e;function r(){const t=hu(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const i=new Ia;du(e,function(e,t){let r;switch(e){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===t){i.set(e,s[r].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),i.integer(e,r[0]),i.percent(e,r[0])&&i.set("snapToLines",!1),i.alt(e,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Aa,"end"]);break;case"position":r=t.split(","),i.percent(e,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Aa,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",Aa,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===La.line&&(r=-1),t.line=r,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",Aa);let n=i.get("position","auto");"auto"===n&&50===La.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function uu(e){return e.replace(/<br(?: \/)?>/gi,"\n")}function fu(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}function gu(e,t,s){return fu(e.toString())+fu(t.toString())+fu(s)}function mu(e,t,s,i){const r=Gl(new Uint8Array(e),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>bl(e)),a=function(e,t,s=1,i=!1){return yc(e,t,1/s,i)}(t.baseTime,1,t.timescale);try{n.forEach(e=>s(function(e,t){const s=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(i).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||i[t],e),{}),n="preserve"!==s.getAttribute("xml:space"),a=vu(pu(s,"styling","style")),o=vu(pu(s,"layout","region")),l=pu(s,"body","[begin]");return[].map.call(l,e=>{const s=yu(e,n);if(!s||!e.hasAttribute("begin"))return null;const i=bu(e.getAttribute("begin"),r),l=bu(e.getAttribute("dur"),r);let h=bu(e.getAttribute("end"),r);if(null===i)throw Eu(e);if(null===h){if(null===l)throw Eu(e);h=i+l}const d=new Ta(i-t,h-t,s);d.id=gu(d.startTime,d.endTime,d.text);const c=function(e,t,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&s.hasOwnProperty(n)&&(r=s[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((s,n)=>{const a=Su(t,i,n)||Su(e,i,n)||Su(r,i,n);return a&&(s[n]=a),s},{})}(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:u}=c;if(u){const e=Oa[u];e&&(d.lineAlign=e),d.align=u}return zo(d,c),d}).filter(e=>null!==e)}(e,a)))}catch(e){i(e)}}function pu(e,t,s){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function vu(e){return e.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function yu(e,t){return[].slice.call(e.childNodes).reduce((e,s,i)=>{var r;return"br"===s.nodeName&&i?e+"\n":null!=(r=s.childNodes)&&r.length?yu(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent},"")}function Su(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function Eu(e){return new Error(`Could not parse ttml timestamp ${e}`)}function bu(e,t){if(!e)return null;let s=hu(e);return null===s&&(Ma.test(e)?s=function(e,t){const s=Ma.exec(e),i=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/t.frameRate}(e,t):_a.test(e)&&(s=function(e,t){const s=_a.exec(e),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),s}function Tu(e,t,s,i="",r="disabled"){const n=e.ownerDocument.createElement("track");return n.kind=t,n.label=s,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=r,e.appendChild(n),n}function wu(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){Gs.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(e){Gs.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===s&&(e.mode=s)}function Iu(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function Lu(e,t){const s=Au(e.main);if(s&&s.start<=t)return s;const i=Au(e.audio);return i&&i.start<=t?i:null}function Au(e){if(!e)return null;switch(e.state){case Zi.IDLE:case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:return null}return e.frag}function ku(e,t){return t.getAppendedFrag(e,Ps.MAIN)||t.getPartialFragment(e)}function Ru(e,t,s,i){const r=i.latestLevelDetails,n=ku(t,s);if(zd(i.config)&&!e.nextStart&&r&&n&&i.interstitialsManager){const s="type"in n?n:n.fragment,a=qh(r,s.sn,!0);(null==a?void 0:a.level)===s.level&&Yd(a,i.interstitialsManager.playerQueue,t)&&(e.nextStart=a.start)}}function Cu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Pu(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,gi(r?Xo({type:r},i):i))}return n}function Du(){return self.SourceBuffer||self.WebKitSourceBuffer}function Mu(){if(!dl())return!1;const e=Du();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function _u(){if(!Mu())return!1;const e=dl();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(fh(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(fh(t,"audio"))))}function Ou(e,t,s){return`${e.identifier}-${s+1}-${fu(t)}`}function xu(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Va)?t.start:t.start+t.duration}function Fu(e,t,s){const i=new self.URL(e,s);return"data:"!==i.protocol&&kh(i,"_HLS_primary_id",t),i}function Bu(e,t){for(;null!=(s=e.assetList[++t])&&s.error;)var s;return t}function Uu(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}function Nu(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}function $u(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Gu(e,t){return`[${e}] Advancing timeline position to ${t}`}function Hu(e,t,s){s.a=e,s.b=t}function Wu(e,t,s){return s.a===e&&s.b===t}function qu(e,t,s,i){return Math.min(t,i)-Math.max(e,s)}function ju(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}function Ku(e,t){return new self.Request(e.url,t)}function Vu(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Vu):Object.keys(e).reduce((t,s)=>(t[s]=Vu(e[s]),t),{}):e}function Yu(e,t){return ch(e,"audio",t)}function zu(e,t){return ch(e,"video",t)}function Qu(e,t){let{audioCodec:s,videoCodec:i}=e;s&&(e.audioCodec=s=ph(s,t)||void 0),i&&(i=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&"avc1"===s[0]&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}(i));const{unknownCodecs:r}=e;return!((null==r?void 0:r.length)||s&&!Yu(s,t)||i&&!zu(i,t))}function Xu(e){const t={};e.forEach(e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++})}function Ju(e,t=ws.KEY_LOAD_ERROR,s,i,r){return new Ci({type:Ts.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i||null})}function Zu(e){const{type:t}=e;switch(t){case Cs.AUDIO_TRACK:return Ps.AUDIO;case Cs.SUBTITLE_TRACK:return Ps.SUBTITLE;default:return Ps.MAIN}}function ef(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}h(Go,{AbrController:()=>mi,AttrList:()=>Bi,AudioStreamController:()=>Jr,AudioTrackController:()=>en,BaseLoader:()=>ko,BasePlaylistController:()=>Zr,BaseSegment:()=>Ms,BaseStreamController:()=>er,BufferController:()=>on,CMCDController:()=>va,CapLevelController:()=>ln,ChunkMetadata:()=>Di,ContentSteeringController:()=>ya,Cues:()=>Ao,DateRange:()=>Ui,EMEController:()=>Ea,ErrorActionFlags:()=>yi,ErrorController:()=>Si,ErrorDetails:()=>ws,ErrorTypes:()=>Ts,Events:()=>Is,FPSController:()=>ba,FetchLoader:()=>Co,Fragment:()=>_s,Hls:()=>No,HlsSkip:()=>di,HlsUrlParameters:()=>ci,KeySystemFormats:()=>Hi,KeySystems:()=>Gi,Level:()=>ui,LevelDetails:()=>Ni,LevelKey:()=>Ki,LoadStats:()=>Rs,LoaderContextType:()=>Cs,M3U8Parser:()=>Ji,MetadataSchema:()=>or,NetworkErrorAction:()=>vi,Part:()=>Os,PlaylistLevelType:()=>Ps,SubtitleStreamController:()=>so,SubtitleTrackController:()=>xa,TimelineController:()=>Io,XhrLoader:()=>_o,default:()=>No,fetchSupported:()=>ju,getMediaSource:()=>dl,isMSESupported:()=>Mu,isSupported:()=>_u,requestMediaKeySystemAccess:()=>qi});var tf=o({"../../node_modules/hls.js/dist/hls.mjs"(){var e,t,s,i,r,n;Ss=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Es=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=bs},bs=Number.MAX_SAFE_INTEGER||9007199254740991,Ts=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ws=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),Is=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),Ls={exports:{}},As||(As=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,t=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,r={buildAbsoluteURL:function(e,s,i){if(i=i||{},e=e.trim(),!(s=s.trim())){if(!i.alwaysNormalize)return e;var n=r.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=r.normalizePath(n.path),r.buildURLFromParts(n)}var a=r.parseURL(s);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=r.normalizePath(a.path),r.buildURLFromParts(a)):s;var o=r.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=t.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=r.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?r.normalizePath(a.path):a.path),r.buildURLFromParts(h)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},Ls.exports=r),ks=Ls.exports,Rs=class{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}}},Cs={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},Ps={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Ds={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Ms=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,Vo(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Ds.AUDIO]:null,[Ds.VIDEO]:null,[Ds.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Rs),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=ks.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ds.AUDIO]=null,e[Ds.VIDEO]=null,e[Ds.AUDIOVIDEO]=null,this.url=null}},_s=class extends Ms{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Ss(e)&&Ss(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=Ss(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){Ss(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Wo(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}},Os=class extends Ms{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===Ps.SUBTITLE&&this.stats.loaded)}},xs=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Fs=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new xs(e),this.fast_=new xs(t),this.defaultTTFB_=i,this.ttfb_=new xs(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new xs(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new xs(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new xs(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;const s=Math.min(this.minDelayMs_,t/1e5),i=8*t,r=Math.max(e,s)/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Bs=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Us,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},Ns={trace:Us=function(){},debug:Us,log:Us,warn:Us,info:Us,error:Us},$s=ll(),Gs=$s,Hs="utf-16",Ws="utf-16be",qs="utf-16le",js="utf-8",Ks=10,Vs=10,Ys=Math.pow(2,32)-1,zs={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Qs={video:1,audio:2,id3:3,text:4},Js=oh("userAgent"),Zs=oh("vendor"),ii={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}},ri={},ni=/flac|opus|mp4a\.40\.34/i,ai={supported:!1,smooth:!1,powerEfficient:!1},oi={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},li=["NONE","TYPE-0","TYPE-1",null],hi=["SDR","PQ","HLG"],di={No:"",Yes:"YES",v2:"v2"},ci=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&kh(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&kh(t,"_HLS_part",this.part.toString()),this.skip&&kh(t,"_HLS_skip",this.skip),t.href}},ui=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Ch(this._audioGroups,e)}hasSubtitleGroup(e){return Ch(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}},fi=e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}},gi=(e,t)=>JSON.stringify(e,fi(t)),mi=class extends Bs{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this;if(!r)return;const{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!e||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(2*y)*1e3))return;const S=p?p.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,b=l.loaded&&E>-1,T=this.getBwEstimate(),w=r.levels,I=w[u],L=Math.max(l.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8));let A=b?d-E:d;A<1&&b&&(A=Math.min(d,8*l.loaded/T));const k=b?1e3*l.loaded/A:0,R=v/1e3,C=k?(L-l.loaded)/k:8*L/T+R;if(C<=S)return;const P=k?8*k:T,D=!0===(null==(t=(null==e?void 0:e.details)||r.latestLevelDetails)?void 0:t.live),M=r.config.abrBandWidthUpFactor;let _,O=Number.POSITIVE_INFINITY;for(_=u-1;_>c;_--){const e=w[_].maxBitrate,t=!w[_].details||D;if(O=this.getTimeToLoadFrag(R,P,h*e,t),O<Math.min(S,h+R))break}if(O>=C)return;if(O>10*h)return;b?this.bwEstimator.sample(d-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(d);const x=w[_].maxBitrate;this.getBwEstimate()*M>x&&(this.firstAutoFloor=Math.min(_,r.firstLevel),this.resetEstimator(x));const F=this.findBestLevel(x,c,_,0,S,1,1);F>-1&&(_=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${Ss(T)?0|T:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|x} bps`),r.nextLoadLevel=r.nextAutoLevel=_,this.clearTimer();const B=()=>{this.clearTimer();const e=this.hls;if(this.fragCurrent===s&&e.loadLevel===_&&_>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${_>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,_>c){let s=this.findBestLevel(e.levels[c].bitrate,c,_,0,t,1,1);-1===s&&(s=c),e.nextLoadLevel=e.nextAutoLevel=s,this.firstAutoFloor=Math.min(s,e.firstLevel),this.resetEstimator(e.levels[s].bitrate)}}};g||C>2*O?B():this.timer=self.setInterval(B,1e3*O),r.trigger(Is.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new Fs(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Is.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;var i;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ws.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&jo(e,s)){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;Ss(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;const{frag:i,part:r}=t,n=r?r.stats:i.stats;if(i.type===Ps.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(s=this.hls)&&s.config.abrMaxWithRealBitrate){const e=r?r.duration:i.duration,t=this.hls.levels[i.level],s=(t.loaded?t.loaded.bytes:0)+n.loaded,a=(t.loaded?t.loaded.duration:0)+e;t.loaded={bytes:s,duration:a},t.realBitrate=Math.round(8*s/a)}if(i.bitrateTest){const e={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(Is.FRAG_BUFFERED,e),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==Ps.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:s}=e,i=this.getBwEstimate(),r=this.getStarvationDelay(),n=e.config.maxStarvationDelay,a=this.findBestLevel(i,s,t,r/2,n,1,1);if(a>-1)return a;const o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,h=Math.min(Math.max(o,s),t,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;e&&(c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1)}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,i,r,n,a){const{hls:o,lastLoadedFragLevel:l,fragCurrent:h,partCurrent:d}=this;if(!o)return-1;const c=i+r,u=-1===l?o.firstLevel:l,{levels:f,allAudioTracks:g,loadLevel:m,latestLevelDetails:p,config:v}=o;if(1===f.length)return 0;const y=f[u],S=!(null==p||!p.live),E=-1===m||-1===l;let b,T="SDR",w=(null==y?void 0:y.frameRate)||0;const{audioPreference:I,videoPreference:L}=v,A=this.audioTracksByGroup||(this.audioTracksByGroup=Dh(g));let k=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce((e,s,i)=>{if(!s.codecSet)return e;const r=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]}))}),e},{})}(f,A,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:S}=function(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||hi.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}(t,r);for(let t=n.length;t--;){const s=e[n[t]];d||(d=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),S.filter(e=>s.videoRanges[e]>0).length>0&&(c=!0)}u=Ss(u)?u:0,f=Ss(f)?f:0;const E=Math.max(1080,u),b=Math.max(30,f);g=Ss(g)?g:s,s=Math.max(g,s),c||(t=void 0);const T=n.length>1;return{codecSet:n.reduce((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?S.filter(e=>r.videoRanges[e]>0):[],T){if(r.minBitrate>s)return Ph(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return Ph(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Ph(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return Ph(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return Ph(i,"no renditions with stereo sound found"),t;if(r.minHeight>E)return Ph(i,`min resolution of ${r.minHeight} > maximum of ${E}`),t;if(r.minFramerate>b)return Ph(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),t;if(!v.some(e=>r.videoRanges[e]>0))return Ph(i,`no variants with VIDEO-RANGE of ${gi(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Ph(i,`video codec preference "${l}" not found`),t;if(r.maxScore<p)return Ph(i,`max score of ${r.maxScore} < selected max of ${p}`),t}return t&&(mh(i)>=mh(t)||r.fragmentError>e[t].fragmentError)?t:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(i,T,e,I,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;k=h,b=n,T=d?a[a.length-1]:a[0],w=o,e=Math.max(e,l),this.log(`picked start tier ${gi(r)}`)}else b=null==y?void 0:y.codecSet,T=null==y?void 0:y.videoRange;const R=d?d.duration:h?h.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=t;o--){var D;const t=f[o],h=o>u;if(!t)continue;if(v.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&wh(t,A,T,w,e,I)?(t.supportedPromise=Ih(t,A,s,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,i=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${gi(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${gi(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${gi(e)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=oi}if((b&&t.codecSet!==b||T&&t.videoRange!==T||h&&w>t.frameRate||!h&&w>0&&w<t.frameRate||null!=(D=t.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(e=>!1===e.smooth))&&(!E||o!==k)){P.push(o);continue}const g=t.details,p=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||R||1;let y;y=h?a*e:n*e;const L=R&&i>=2*R&&0===r?t.averageBitrate:t.maxBitrate,M=this.getTimeToLoadFrag(C,y,L*p,!g||g.live);if(y>=L&&(o===l||0===t.loadError&&0===t.fragmentError||ol(t,v.errorPenaltyExpireMs))&&(M<=C||!Ss(M)||S&&!this.bitrateTestDelay||M<c)){const e=this.forcedAutoLevel;return o===m||-1!==e&&e===m||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${b}" ${T}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-L)} ttfb:${C.toFixed(1)} avgDuration:${p.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},pi={search:function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null}},vi={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},yi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},Si=class extends Bs{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Is.ERROR,this.onError,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Is.ERROR,this.onError,this),e.off(Is.ERROR,this.onErrorOut,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Ps.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(e=>i.indexOf(e.groupId)>=0).some(e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ws.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=Vh());case ws.FRAG_GAP:case ws.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=vi.SendAlternateToPenaltyBox);case ws.PLAYLIST_UNCHANGED_ERROR:case ws.LEVEL_EMPTY_ERROR:case ws.LEVEL_PARSING_ERROR:{var n;const e=t.parent===Ps.MAIN?t.level:i.loadLevel;t.details===ws.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ws.LEVEL_LOAD_ERROR:case ws.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case ws.AUDIO_TRACK_LOAD_ERROR:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.SUBTITLE_LOAD_ERROR:case ws.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===Cs.AUDIO_TRACK&&e.hasAudioGroup(r.groupId)||r.type===Cs.SUBTITLE_TRACK&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=vi.SendAlternateToPenaltyBox,void(t.errorAction.flags=yi.MoveAllAlternatesMatchingHost)}return;case ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingHDCP});case ws.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ws.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingKey});case ws.BUFFER_ADD_CODEC_ERROR:case ws.REMUX_ALLOC_ERROR:case ws.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case ws.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=yi.ResetMediaSource|yi.SwitchToSDR);case ws.INTERNAL_EXCEPTION:case ws.BUFFER_APPENDING_ERROR:case ws.BUFFER_APPEND_NO_PROGRESS:case ws.BUFFER_FULL_ERROR:case ws.LEVEL_SWITCH_ERROR:case ws.BUFFER_STALLED_ERROR:case ws.BUFFER_SEEK_OVER_HOLE:case ws.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Vh())}t.type===Ts.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Vh())}getPlaylistRetryOrSwitchAction(e,t){const s=sl(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(nl(s,i,Zo(e),e.response))return{action:vi.RetryRequest,flags:yi.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=sl(el(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(i&&(e.details!==ws.FRAG_GAP&&i.fragmentError++,!tl(e))&&nl(a,o,Zo(e),e.response))return{action:vi.RetryRequest,flags:yi.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),t===ws.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===Ps.AUDIO&&t===ws.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&jh(e))&&h.some(({audioCodec:e})=>i.audioCodec!==e),m="video"===e.sourceBufferName&&jh(e)&&h.some(({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let r=h.length;r--;){const n=(r+d)%h.length;if(n!==d&&n>=c&&n<=u&&(0===h[n].loadError||ol(h[n],s.config.errorPenaltyExpireMs))){var a,o;const s=h[n];if(t===ws.FRAG_GAP&&f===Ps.MAIN&&e.frag){const t=h[n].details;if(t){const s=$h(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===Cs.AUDIO_TRACK&&s.hasAudioGroup(v)||p===Cs.SUBTITLE_TRACK&&s.hasSubtitleGroup(v))continue;if(f===Ps.AUDIO&&null!=(a=i.audioGroups)&&a.some(e=>s.hasAudioGroup(e))||f===Ps.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(e=>s.hasSubtitleGroup(e))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.audioCodec!==s.audioCodec)continue}l=n;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:vi.SendAlternateToPenaltyBox,flags:yi.None,nextAutoLevel:l}}return{action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,i;switch(null==(s=t.errorAction)?void 0:s.action){case vi.DoNothing:break;case vi.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ws.FRAG_GAP||t.details===ws.PLAYLIST_UNCHANGED_ERROR||Kh(t)||(t.fatal=!0);case vi.RetryRequest:}((null==(i=t.errorAction)?void 0:i.flags)||0)&yi.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===yi.None)this.switchLevel(e,i);else if(s.flags&yi.SwitchToSDR){const e=this.hls.levels;for(let t=e.length;t--;)"SDR"!==e[t].videoRange?(e[t].fragmentError++,e[t].loadError++):void 0===i&&(i=t)}else if(s.flags&yi.MoveAllAlternatesMatchingHDCP){const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];s.hdcpLevel=n;const a="NONE"===n;n&&!a?(t.maxHdcpLevel=li[li.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=yi.MoveAllAlternatesMatchingKey)}if(s.flags&yi.MoveAllAlternatesMatchingKey){const t=e.decryptdata;if(t){const i=this.hls.levels,a=i.length;for(let s=a;s--;){var r,n;this.variantHasKey(i[s],t)&&(this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(r=i[s].audioGroups)?void 0:r.join(",")}" (${null==(n=e.frag)?void 0:n.type} fragment) ${Rl(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s))}const o=e.frag;if(this.hls.levels.length<a)s.resolved=!0;else if(o&&o.type!==Ps.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ws.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=bh(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}},Ei={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},bi=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const i=s[t];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);const a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o||!this.hls)return;const l=o.body;if(a>=l.sn)return;if(!o.buffered&&(!o.loaded||n))return void(l.type===s&&this.removeFragment(l));const h=o.range[e];if(h)if(0!==h.time.length){if(h.time.some(e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(l),s}),i&&i!==l&&lh()){const e=i.endPTS,t=l.startPTS;if(e&&t&&o.range.video){const s=t-e;s<0&&s>-.1&&(this.removeFragment(l),this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:e+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(l)})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i,id:r}=e;if(!t||!Wo(s))return;const n=zh(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(e=>{const n=s.elementaryStreams[e];if(!n)return;const l=t[e],h=o||!0===n.partial;a.range[e]=this.getBufferedTimes(s,i,h,l),this.detectEvictedFragments(e,l,r,s,i)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,s),Yh(a)||this.removeParts(s.sn-1,s.type),!i){const e=Math.min(.004,s.duration);l.some(t=>{var i;const r=null==(i=a.range[t])?void 0:i.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<e;return n&&this.addAsGap(s),n})}}else this.removeFragment(s)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Qh(s,t=>t.fragment.sn>=e))}fragBuffered(e,t){const s=zh(e);let i=this.fragments[s];return!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<i.length;e++){const t=i.start(e)-this.bufferPadding,s=i.end(e)+this.bufferPadding;if(l>=t&&o<=s){r.time.push({startPTS:Math.max(n,i.start(e)),endPTS:Math.min(a,i.end(e))});break}if(n<s&&a>t){const t=Math.max(n,i.start(e)),s=Math.min(a,i.end(e));s>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Yh(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Yh(t))}getState(e){const t=zh(e),s=this.fragments[t];return s?s.buffered?Yh(s)?Ei.PARTIAL:Ei.OK:Ei.APPENDING:Ei.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Wo(t.frag)||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=zh(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(!Wo(s))return;const n=s.type;if(i){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(i)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=zh(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}getBackBufferEvictionEnd(e,t,s){const{fragments:i}=this;let r=0,n=0;const a=Object.keys(i);for(let o=0;o<a.length;o++){const l=i[a[o]];if(!l||!l.buffered||l.body.type!==t)continue;const h=l.body;if(h.gap)return 0;const d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=e&&d&&(r+=d,n=Math.max(n,h.end),r>=s))return n}return n>0?n:0}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=zh(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=Qh(s,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}},Ti={cbc:0,ctr:1},wi=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Ti.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ti.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Ii=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),v=new Int32Array(p.length);let y,S,E,b,T,w,I,L,A,k,R,C,P,D;const M=this.networkToHostOrderSwap;for(;t<p.length;){for(A=M(p[t]),k=M(p[t+1]),R=M(p[t+2]),C=M(p[t+3]),T=A^r[0],w=C^r[1],I=R^r[2],L=k^r[3],P=4,D=1;D<i;D++)y=o[T>>>24]^l[w>>16&255]^h[I>>8&255]^d[255&L]^r[P],S=o[w>>>24]^l[I>>16&255]^h[L>>8&255]^d[255&T]^r[P+1],E=o[I>>>24]^l[L>>16&255]^h[T>>8&255]^d[255&w]^r[P+2],b=o[L>>>24]^l[T>>16&255]^h[w>>8&255]^d[255&I]^r[P+3],T=y,w=S,I=E,L=b,P+=4;y=n[T>>>24]<<24^n[w>>16&255]<<16^n[I>>8&255]<<8^n[255&L]^r[P],S=n[w>>>24]<<24^n[I>>16&255]<<16^n[L>>8&255]<<8^n[255&T]^r[P+1],E=n[I>>>24]<<24^n[L>>16&255]<<16^n[T>>8&255]<<8^n[255&w]^r[P+2],b=n[L>>>24]<<24^n[T>>16&255]<<16^n[w>>8&255]<<8^n[255&I]^r[P+3],v[t]=M(y^u),v[t+1]=M(b^f),v[t+2]=M(E^g),v[t+3]=M(S^m),u=A,f=k,g=R,m=C,t+=4}return v.buffer}},Li=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case Ti.cbc:return"AES-CBC";case Ti.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}},Ai=class{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,!0!==t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);this.reset();const i=this.decryptRange;return i?0===i.start&&i.end>=s.length?s:s.slice(i.start,i.end):function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==Ti.cbc||16!==t.byteLength)return Gs.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=eh(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ii),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Li(this.subtle,t,i)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new wi(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Gs.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Gs.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},ki=Math.pow(2,17),Ri=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,s,i){const r=e.url;if(!r)return Promise.reject(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,o=n.loader;return new Promise((l,h)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void h(Zh(e));e.gap=!1}const d=this.loader=a?new a(n):new o(n),c=Xh(e,null,t);e.loader=d;const u=rl(n.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ki};d.stats.retry=e.stats.retry,e.stats=d.stats;const g={onSuccess:(t,s,i,r)=>{this.resetLoader(e,d);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,i,n)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Xo({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:t}))}};if(s){const t=this.gateProgress(s,i);g.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})}d.load(c,f,g)})}gateProgress(e,t){let s=e;if(t){const i=[];let r=!1;t.then(()=>{r=!0,i.forEach(t=>e(t)),i.length=0}).catch(()=>{}),s=t=>{r?e(t):i.push(t)}}return s}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Zh(e,t));const l=this.loader=r?new r(i):new n(i),h=Xh(e,t);e.loader=l;const d=rl(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ki};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Xo({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}},Ci=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Pi=class extends Bs{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Di=class{constructor(e,t,s,i=0,r=-1,n=!1,a,o,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}},Mi={length:0,start:()=>0,end:()=>0},_i=class e{static isBuffered(t,s){if(t){const i=e.getBuffered(t);for(let e=i.length;e--;)if(s>=i.start(e)&&s<=i.end(e))return!0}return!1}static bufferedRanges(t){if(t){const s=e.getBuffered(t);return e.timeRangesToArray(s)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(t,s,i){if(t){const r=e.bufferedRanges(t);if(r.length)return e.bufferedInfo(r,s,i)}return{len:0,start:s,end:s,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let i=-1,r=[];if(s)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<s?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const h=r[e].start,d=r[e].end;if(-1===i&&t>=h&&t<=d&&(i=e),t+s>=h&&t<d)o=h,l=d,a=l-t;else if(t+s<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Mi}catch(e){return Gs.log("failed to get media.buffered",e),Mi}}},Oi=/\{\$([a-zA-Z0-9-_]+)\}/g,xi=/^(\d+)x(\d+)$/,Fi=/(.+?)=(".*?"|.*?)(?:,|$)/g,Bi=class e{constructor(t,s){"string"==typeof t&&(t=e.parseAttrList(t,s)),zo(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=xi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(Fi.lastIndex=0;null!==(s=Fi.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=td(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Gs.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}},Ui=class{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){Gs.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=zo(new Bi({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const s=(null==t?void 0:t.endDate)||new Date(e["END-DATE"]);Ss(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Gs.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ss(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Ss(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:Ss(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}},Ni=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&Ss(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}},$i="undefined"!=typeof self?self:void 0,Gi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Wi={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"},qi=null!=$i&&null!=(n=$i.navigator)&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,ji={},Ki=class e{static clearKeyUriToKeyIdMap(){ji={}}static setKeyIdForUri(e,t){ji[e]=t}static addKeyIdForUri(e){const t=Object.keys(ji).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),ji[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ld(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Cl(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ad(e.keyFormatVersions,this.keyFormatVersions)&&od(e.iv,this.iv)&&od(e.keyId,this.keyId)}isSupported(){if(this.method){if(ld(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Hi.FAIRPLAY:case Hi.WIDEVINE:case Hi.PLAYREADY:case Hi.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,s){var i;if(!this.encrypted||!this.uri)return null;if(ld(this.method)){let s=this.iv;return s||("number"!=typeof t&&(Gs.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),s=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const t=ji[this.uri];if(t&&!ad(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=ud(this.uri);if(r)switch(this.keyFormat){case Hi.WIDEVINE:if(this.pssh=r,!this.keyId){const e=nh(r.buffer).filter(e=>e.systemId===Wi.WIDEVINE);if(e.length){var n;const t=e[0];this.keyId=null!=(n=t.kids)&&n.length?t.kids[0]:null}}this.keyId||(this.keyId=vd(s));break;case Hi.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(e,...t){const s=t.length;let i=8,r=s;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,s)}(e,0,r),this.keyId=pd(r);break}default:{let e=r.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(16!==(null==(i=this.keyId)?void 0:i.byteLength)){let t;t=function(e){const t=null==e?void 0:e[Hi.WIDEVINE];return t?t.keyId:null}(s),t||(t=vd(s),t||(t=ji[this.uri])),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}},Vi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Yi=/#EXT-X-MEDIA:(.*)/g,zi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Xi=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Ji=class e{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return ks.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return zi.test(e)}static parseMasterPlaylist(t,s){const i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ed(t)},r=[];if(Vi.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;null!=(n=Vi.exec(t));)if(n[1]){const e=yd(new Bi(n[1],i),n[2],s,i,r);e&&i.levels.push(e)}else if(n[3]){const t=n[3],a=n[4];switch(t){case"I-FRAME-STREAM-INF":{const e=new Bi(a,i),t=yd(e,e.URI,s,i,r,!0);t&&i.iframeVariants.push(t)}break;case"SESSION-DATA":{const e=new Bi(a,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=bd(a,s,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):Gs.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${a}"`);break}case"DEFINE":sd(i,new Bi(a,i),s);break;case"CONTENT-STEERING":{const t=new Bi(a,i);i.contentSteering={uri:e.resolve(t["SERVER-URI"],s),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Td(a)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,s,i){let r;const n={},a=i.levels,o={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Yi.lastIndex=0;null!==(r=Yi.exec(t));){const t=new Bi(r[1],i),a=t.TYPE;if(a){const i=o[a],r=n[a]||[];n[a]=r;const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:l++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:a,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?e.resolve(t.URI,s):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const t=e.findGroup(i,g.groupId)||i[0];Id(g,t,"audioCodec"),Id(g,t,"textCodec")}r.push(g)}}return n}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new Ni(t),h=l.fragments,d=[];let c,u,f,g,m=null,p=0,v=0,y=0,S=0,E=0,b=null,T=new _s(i,o),w=-1,I=!1,L=null;if(Qi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ed(e),"#EXTM3U"!==(null==(a=Qi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Qi.exec(e));){I&&(I=!1,T=new _s(i,o),T.playlistOffset=y,T.setStart(y),T.sn=p,T.cc=S,E&&(T.bitrate=E),T.level=s,m&&(T.initSegment=m,m.rawProgramDateTime&&(T.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),L&&(T.setByteRange(L),L=null)));const e=c[1];if(e){T.duration=parseFloat(e);const t=(" "+c[2]).slice(1);T.title=t||null,T.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(Ss(T.duration)){var A;T.playlistOffset=y,T.setStart(y),f&&kd(T,f,l),T.sn=p,T.level=s,T.cc=S;const e=(" "+c[3]).slice(1);T.relurl=td(l,e),Ld(T,b,d),b=T,y+=T.duration,p++,v=0;const t=T.byteRange;if(2===t.length&&(T.bitrate=8*(t[1]-t[0])/T.duration|0),l.iframesOnly&&t[0]&&(null==(A=m)?void 0:A.cc)!==S){const e=new _s(i,o);e.relurl=T.relurl,e.setByteRange(`${Math.min(t[0],1316)}@0`),e.level=s,e.sn="initSegment",f&&(e.levelkeys=f,f.identity&&(e._decryptdata=f.identity.getDecryptData(0))),m=e,T.initSegment=m}h.push(T),I=!0}}else{if(c=c[0].match(Xi),!c){Gs.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":b?T.setByteRange(r,b):T.setByteRange(r);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=r,T.tagList.push(["PROGRAM-DATE-TIME",r]),-1===w&&(w=h.length);break;case"PLAYLIST-TYPE":l.type&&Rd(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Rd(l,e,c):null!==b&&Cd(l,e,c),l.startSN=parseInt(r),p=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&Rd(l,e,c);const t=new Bi(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(Ss(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);p+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Rd(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Rd(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||Rd(l,e,c),l.live=!1;break;case"#":(r||a)&&T.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":S++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([e]);break;case"BITRATE":T.tagList.push([e,r]),E=1e3*parseInt(r),Ss(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const e=new Bi(r,l),t=new Ui(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Gs.log(`Ignoring invalid DATERANGE tag: ${t.invalidReason}: ${r}`),T.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new Bi(r,l);"IMPORT"in e?id(l,e,n):sd(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC&&Rd(l,e,c),l.startCC=S=parseInt(r),h.forEach(e=>e&&(e.cc=S));break;case"KEY":{const e=bd(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=zo({},f)),f[e.keyFormat]=e)}else Gs.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Td(r);break;case"MAP":{const e=new Bi(r,l);if(T.duration){const t=new _s(i,o);Ad(t,e,s,f),m=t,T.initSegment=m,m.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=m.rawProgramDateTime)}else{const t=T.byteRangeEndOffset;if(t){const e=T.byteRangeStartOffset;L=`${t-e}@${e}`}else L=null;Ad(T,e,s,f),m=T,I=!0}m.cc=S;break}case"SERVER-CONTROL":g&&Rd(l,e,c),g=new Bi(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Rd(l,e,c);const t=new Bi(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new Bi(r,l),n=new Os(i,T,o,s,t);e.push(n),T.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new Bi(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Bi(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Gs.warn(`line parsed but not handled: ${c}`)}}}b&&!b.relurl?(h.pop(),y-=b.duration,l.partList&&(l.fragmentHint=b)):l.partList&&(Ld(T,b,d),T.cc=S,l.fragmentHint=T,f&&kd(T,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=h.length,R=h[0],C=h[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&C){l.averagetargetduration=y/k;const e=C.sn;l.endSN="initSegment"!==e?e:0,l.live||(C.endList=!0),w>0&&(function(e,t,s){if(s||(s=e[t]),s)for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,w,w>k-1?T:null),R&&d.unshift(R))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&R&&Sd(d,l),l.endCC=S,l}},Zi={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"},er=class extends Pi{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Zi.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=_i.bufferInfo(i||s,n,e.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Zi.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(!o||r<a.start||i>a.end){const e=n<i,s=n>r;(e||s)&&(!t.loader||!s&&this.isFragmentNearlyDownloaded(t)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${t.sn}) - ${e?"backward":"forward"} seek`),t.abortRequests(),this.resetLoadingState()))}}if(s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${e}`),this.loadingParts=t)}const l=!_i.isBuffered(s,n);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,l&&(this.startPosition=n)),o<1&&this.state===Zi.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Ri(e.config),this.initFragmentLoader=new Ri(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ai(e.config)}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Zi.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Zi.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(-1===t&&e){const t=this.getLevelDetails();return null!=t&&t.live?(this.hls.liveSyncPosition||t.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=_i.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return _i.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;jd(s,"seeking",this.onMediaSeeking),jd(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Zi.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Kd(i,"seeking",this.onMediaSeeking),Kd(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Zi.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(t);const s=++t.stats.chunkCount;this.log(`load progress ${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} chunk: ${s}`),this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===Zi.FRAG_LOADING||!this.fragCurrent&&t===Zi.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=Zi.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level} (bytes ${s.stats.loaded})`),this.hls.trigger(Is.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Zi.STOPPED&&this.state!==Zi.ERROR&&(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ei.APPENDING){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ei.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){const e=t.getPartialFragment(s.end);e&&(t.removeFragment(e),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(Is.BUFFER_FLUSHING,i)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(Is.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(e=>{var t;const s=e.frag;if(!this.levels||!jo(s,null==(t=this.fragCurrent)?void 0:t.initSegment))throw new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:s,networkDetails:null});return e}).then(e=>{const{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ld(r.method)){const n=self.performance.now(),{decryptRange:a}=Jh(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,hd(r.method),a).catch(e=>{throw t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),this.fragmentLoader.abort(),e}).then(i=>{const r=self.performance.now();return t.trigger(Is.FRAG_DECRYPTED,{frag:s,part:null,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;var s;if(!this.bitrateTest&&Wo(e)&&t&&!t.data)return(!t.encrypted||null!=(s=t.decryptdata)&&s.key?this._loadInitSegment(t):this.keyLoader.load(t).then(()=>this._loadInitSegment(t))).catch(t=>{if(this.state===Zi.STOPPED||this.state===Zi.ERROR)throw t;throw"data"in t&&(t.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(t)),this.resetFragmentLoading(e),t})}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(s.message),!(!e||e.mediaKeys)&&(this.hls.trigger(Is.ERROR,{type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!jo(e,t)}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Vd(_i.getBuffered(s)):"(detached)"})`),Wo(e)){var i;if(e.type!==Ps.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Zi.IDLE)}const s=null==(i=this.levels)?void 0:i[e.level];null!=s&&s.fragmentError&&(t||this.fragmentTracker.getState(e)!==Ei.PARTIAL)&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0,e.stats.retry=0)}this.state=Zi.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const s=e.frag,{part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),{decryptRange:a}=Jh(s,i),o=new Di(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n,s.duration,this.iframesOnly,a);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),t.flush(o)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){var i;let r=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)):(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Zi.KEY_LOADING,r=this.keyLoader.load(e,s).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Is.KEY_LOADED,e),this.state===Zi.KEY_LOADING&&(this.state=Zi.IDLE),e}),this.hls.trigger(Is.KEY_LOADING,{frag:e})),r}_doFragLoad(e,t,s=null,i){this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const n=this.fragPrevious;if(!qo(e,n)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==n?void 0:n.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts){const a=r.partList;if(a&&i){s>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const o=this.getNextPart(a,e,s);if(o>-1){const l=a[o];if(!qo(e=this.fragCurrent=l.fragment,n)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,l)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(l,t.details))return Promise.resolve(null);const h=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);let d;this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${a.length-1}) of ${this.fragInfo(e,!1,l)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${s}${l.byteRange.length?` range:${l.byteRange.join("-")}`:""}`),this.nextLoadPosition=l.start+l.duration,this.state=Zi.FRAG_LOADING;const c=this.loadInitSegmentIfNeeded(e);if(h||c){const s=!!h;d=Promise.all([h,c]).then(([r])=>!s||r&&!this.fragContextChanged(r.frag)?this.doFragPartsLoad(e,l,t,i):null).catch(e=>this.handleFragLoadError(e))}else d=this.doFragPartsLoad(e,l,t,i).catch(e=>this.handleFragLoadError(e));return this.hls.trigger(Is.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(a,s))return Promise.resolve(null)}}var a;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${e.sn} loaded parts: ${null==(a=r.partList)?void 0:a.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const o=this.loadInitSegmentIfNeeded(e),l=this.loadKeyFor(e,r,o);var h;if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${null==(h=this.fragCurrent)?void 0:h.relurl}`),null==o||o.catch(()=>null),null==l||l.catch(()=>null),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),Ss(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Zi.FRAG_LOADING;const d=this.config.progressive&&e.type!==Ps.SUBTITLE;let c;return c=d&&l?l.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,o)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,d?i:void 0,d?o:void 0),l,o]).then(([e])=>(!d&&i&&i(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Is.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([c,o]).then(([e])=>e)}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then(i=>{o[t.index]=i;const n=i.part;this.hls.trigger(Is.FRAG_LOADED,i);const a=Fd(s.details,e.sn,t.index+1)||Bd(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ws.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ts.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(Is.ERROR,t)}else this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Zi.PARSING)return void(this.fragCurrent||this.state===Zi.STOPPED||this.state===Zi.ERROR||(this.state=Zi.IDLE));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;const i=e.partList[0];if(t>=i.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Fd(o,r,n):null,h=l?l.fragment:xd(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==Zi.PARSING)return;Wo(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:n,data2:a}=e;let o=n;if(a&&(o=eh(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(Is.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!_i.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=_i.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.playhead,r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=_i.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return _i.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){const i=e.nextStart;if(i&&s.start>i){const i=e.buffered;if(i){let r=e.len;const n=e.bufferedIndex;for(let e=i.length-1;e>n;e--)i[e].start<s.start&&(r+=i[e].end-i[e].start);return r>=t}}return!1}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t/2),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;o=this.getInitialLiveFragment(t);const s=this.config.startPosition,i=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let h,d;if(-1!==i&&i>=n?(h=i,d=i===s?"config":"next load start"):r?(h=r,d="live edge"):(h=e,d="buffer pos"),h<a&&(h=a,d="live frag start"),h<n&&(h=n,d="playlist start"),this.startPosition!=h||this.nextLoadPosition!=h){const l=t.live&&!this.filterReplacedPrimary(o,t)?-1:h;this.log(`Setting startPosition to ${l} next load ${h} ${-1===i?"":`(from ${s}) `}based on ${d}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${e}`),this.startPosition=l,this.nextLoadPosition=h}}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);return!h&&o&&(h=qh(t,o.sn,this.loadingParts),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const s=this.fragmentTracker.getState(e);if(s===Ei.OK)return!0;if(s===Ei.PARTIAL){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){var e;if(zd(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}filterReplacedPrimary(e,t){if(!e)return e;if(zd(this.config)&&("type"in e?e:e.fragment).type!==Ps.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(!s.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(Yd(e,null==s?void 0:s.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded||o.gap;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(i=a),r=l&&!o.gap}const a=e[i];return a&&a.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${a.start} (sn: ${t.sn} -> ${a.fragment.sn})`),i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!Ss(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(Hh(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Wh(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;var u;(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===Ei.NOT_LOADED&&(r=null),e<t)?c=$h(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l):c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Ei.OK||t===Ei.PARTIAL&&c.gap)&&(r=c),qo(c,r)&&(!d||h[0].fragment.sn>c.sn||!s.live)){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Ei.OK?t:null}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&Ss(r);if(n||!a&&!r){qd(s,e,this);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;if(null!==n&&Ss(n))s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){const e=this.hls.liveSyncPosition;s=e||t,this.log(`Setting startPosition to -1 to start at ${e?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t;const e=null==(t=this.media)?void 0:t.currentTime;return Ss(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==Ps.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Wo(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Zi.FRAG_LOADING_WAITING_RETRY)||(this.state=Zi.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const{frag:s,part:i}=t;if(!s||!this.levels||s.type!==e)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const n=t.details===ws.FRAG_GAP;n&&this.fragmentTracker.addAsGap(s);const a=t.errorAction;if(!a)return void(this.state=Zi.ERROR);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===vi.RetryRequest,f=c&&!a.resolved&&l&yi.MoveAllAlternatesMatchingHost,g=this.hls.latestLevelDetails,m=null==g?void 0:g.live;if(!u&&f&&Wo(s)&&m&&s.sn<g.endSN&&!tl(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(s),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var p;const i=al(null==(p=t.response)?void 0:p.code),r=il(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Zi.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===vi.RemoveAlternatePermanently||(a.resolved=!0)}else o===vi.SendAlternateToPenaltyBox?this.state=Zi.WAITING_LEVEL:this.state=Zi.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!al(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Zi.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Zi.PARSING||this.state===Zi.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===Ps.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Ps.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Zi.STOPPED&&(this.state=Zi.IDLE)}afterBufferFlushed(e,t){if(!e)return;const s=_i.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===Zi.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Zi.STOPPED&&(this.state=Zi.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(r){if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i.partial?0:Dd(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this.iframesOnly,this);return this.hls.trigger(Is.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var n,a,o,l;const i=null===(null==(n=this.transmuxer)?void 0:n.error),r=null!=(null==(a=this.transmuxer)?void 0:a.error),h=(null!=(o=null==(l=this.levels)?void 0:l.length)?o:0)>1;if((0===s.fragmentError||i&&(s.fragmentError<2||e.endList)||r&&h)&&this.treatAsGap(e,s),i){const i=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Zi.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(Is.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN}-${null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}isFragmentNearlyDownloaded(e){var t;const s=null==(t=e.loader)?void 0:t.stats;if(!s)return!1;const i=s.loading.first>0,r=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&r<=.15}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let s=0;const{hls:i,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var h;const t=o===Ps.AUDIO?Lh(e.audioCodec,128e3):e.maxBitrate,r=1+i.ttfbEstimate/1e3,a=i.bandwidthEstimate*n.abrBandWidthUpFactor;s=r+t*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/a,e.details||(s+=r)}const d=this.playhead;return{fetchdelay:s,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-d>1.5*s}}scheduleTrackSwitch(e,t,s){const{media:i,playlistType:r}=this;if(!i||!e)return;const n=s?this.getBufferedFrag(this.playhead+t):null;if(n){const e=this.followingBufferedFrag(n);if(e){var a;this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>i)return;const o=r===Ps.MAIN?null:"audio";this.flushMainBuffer(i,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const e=t===Ps.AUDIO;this.flushMainBuffer(0,s.start-(e?0:1),e?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Zi.KEY_LOADING:case Zi.FRAG_LOADING:case Zi.FRAG_LOADING_WAITING_RETRY:case Zi.PARSING:case Zi.PARSED:this.state=Zi.IDLE}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(_i.isBuffered(e,s)?t=this.getAppendedFrag(s):_i.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!qo(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:s,config:i,playlistType:r}=this;if(null!=t&&t.readyState&&e&&s&&i){const t=this.getBufferOutput(),i=this.getFwdBufferInfo(t,r);if(!i)return;const n=e[r===Ps.AUDIO?s.nextAudioTrack:s.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,i);this.scheduleTrackSwitch(i,a,o)}this.tickImmediate()}},tr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}},sr={exports:{}},ir||(ir=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(sr)),rr=Ho(sr.exports),nr="1.7.0",ar={},or=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({}),lr=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=eh(this.cachedData,e),this.cachedData=null);let s,i=Sl(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?kl(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Ss(o))&&(this.basePTS=hr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:or.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else vl(e,r)?(i=Sl(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:or.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=eh(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:rc(),id3Track:a,textTrack:rc()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:rc(),id3Track:this._id3Track,textTrack:rc()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},hr=(e,t,s)=>Ss(e)?90*e:9e4*t+(s?9e4*s.baseTime/s.timescale:0),dr=[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],cr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ur=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fr=[0,1,1,4],gr=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ai(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ti.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,s),this.decrypter.isSync())))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)s.set(e.subarray(t,t+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)e.set(s.subarray(i,i+16),t);return e}decryptAvcSample(e,t,s,i,r){const n=rh(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}},mr=class extends lr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Sl(e,0);let i=(null==s?void 0:s.length)||0;if(hc(e,i))return!1;for(let s=e.length;i<s;i++)if(ec(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Qd(e,t)&&Jd(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){tc(e,this.observer,t,s,e.manifestCodec);const i=ic(e,t,s,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}demuxSampleAes(e,t,s){const i=this.demux(e,s),r=this.sampleAes=new gr(this.observer,this.config,t);return new Promise(e=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{e(i)})})}},pr=(e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s},vr=class extends lr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=dc(e,t,s,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Sl(e,0);if(!t)return!1;const s=t.length;if(11===e[s]&&119===e[s+1]&&void 0!==kl(t)){if(pr(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}},yr=class extends lr{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Sl(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==kl(t)&&pr(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(hc(e,s))return Gs.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return oc(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return nc(e,t,s,this.basePTS,this.frameIndex)}},Sr=/\/emsg[-/]ID3/i,Er=class{constructor(e,t,s,i=Gs){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=i}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=rc("video",1),n=this.audioTrack=rc("audio",1),a=this.txtTrack=rc("text",1);if(this.id3Track=rc("id3",1),this.initData=void 0,this.timeOffset=0,null==e||!e.byteLength)return;const o=this.initData=ql(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=Qs.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=_l(e,s);if(i>8&&_l(e,s+4)===zs.moof)return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t,s){this.timeOffset=t;let i=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=eh(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=Gl(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,t),o=this.parseFragment(r,n,t,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(e,t){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(i,this.timeOffset),a=this.parseFragment(i,r,s,t);return{videoTrack:i,audioTrack:rc(),id3Track:n,textTrack:rc(),initData:this.initData,sampleData:a}}parseFragment(e,t,s,i){const r=this.initData;if(r&&i){const{samples:n,sampleData:a}=function(e,t,s,i,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:Zl(t.samples,s,i,r,{isHEVCFlavor:th(t.codec),samples:n,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(s,e,r,this.logger,i.iframe);return t.samples=n,a}t.samples=function(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return Gl(i,["moof"]).map(o=>{const l=o.byteOffset-8;Gl(o,["traf"]).map(o=>{const h=Gl(o,["tfdt"]).map(e=>{const t=e[0];let s=_l(e,4);return 1===t&&(s*=Math.pow(2,32),s+=_l(e,8)),s/r})[0];return void 0!==h&&(e=h),Gl(o,["tfhd"]).map(h=>{const d=_l(h,4),c=16777215&_l(h,0),u=!!(1&c);let f=0;const g=!!(2&c),m=!!(8&c);let p=0;const v=!!(16&c);let y=0;const S=!!(32&c),E=!u&&!!(131072&c);let b=8;d===n&&(u?(f=_l(h,b),b+=4,f*=Math.pow(2,32),f+=_l(h,b),b+=4):E&&(f=l),g&&(b+=4),m&&(p=_l(h,b),b+=4),v&&(y=_l(h,b),b+=4),S&&(b+=4),"video"===t.type&&(a=th(t.codec)),Gl(o,["trun"]).map(n=>{const o=n[0],l=16777215&_l(n,0),h=!!(1&l);let d=0;const c=!!(4&l),u=!!(256&l);let g=0;const m=!!(512&l);let v=0;const S=!!(1024&l),E=!!(2048&l);let b=0;const T=_l(n,4);let w=8;h&&(d=_l(n,w),w+=4),c&&(w+=4);let I=f+d;for(let l=0;l<T;l++){if(u?(g=_l(n,w),w+=4):g=p,m?(v=_l(n,w),w+=4):v=y,S&&(w+=4),E&&(b=0===o?_l(n,w):Fl(n,w),w+=4),t.type===Ds.VIDEO){let t=0;for(;t<v;){const n=_l(i,I);I+=4,sh(a,i[I])&&ih(i.subarray(I,I+n),a?2:1,e+b/r,s),I+=n,t+=n+4}}e+=g/r}}))})})}),s}(s,e)}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Gl(e.samples,["emsg"]);i&&i.forEach(e=>{const i=function(e){const t=e[0];let s,i="",r="",n=0,a=0,o=0,l=0,h=4;if(0===t){const t=xl(e,h),s=null!==t?xl(e,h+t.length):null;null!==t&&null!==s?(i=t,r=s,h+=t.length+s.length,n=_l(e,h),h+=4,a=_l(e,h),h+=4,o=_l(e,h),h+=4,l=_l(e,h),h+=4):(Gs.warn(`Unterminated ${null===t?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=e.length)}else if(1===t){n=_l(e,h),h+=4;const t=_l(e,h);h+=4;const a=_l(e,h);h+=4,s=2**32*t+a,Es(s)||(s=Number.MAX_SAFE_INTEGER,Gs.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=_l(e,h),h+=4,l=_l(e,h),h+=4;const d=xl(e,h),c=null!==d?xl(e,h+d.length):null;null!==d&&(i=d,h+=d.length),null!==c?(r=c,h+=c.length):(Gs.warn(`Unterminated ${null===d?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===d?"strings and payload":"value and payload"}`),h=e.length)}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Sr.test(i.schemeIdUri)){const e=cc(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:or.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata){const e=this.config.emsgKLVSchemaUri||or.misbklv;if(i.schemeIdUri.startsWith(e)){const e=cc(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:or.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},br=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;if(0===i)return[];const r=e.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,h=-1,d=0;for(-1===r&&(h=0,d=this.getNALuType(t,0),l=1);l<i;){const s=t.indexOf(1,l);if(-1===s)break;l=s+1;let r=s;for(;r>0&&0===t[r-1];)r--;if(!(s-r+(0===r?n:0)<2)){if(h>=0)a.push({data:t.subarray(h,r),type:d});else{const s=this.getLastNalUnit(e.samples);s&&(r>0?s.data=eh(s.data,t.subarray(0,r)):n>0&&(s.data=s.data.subarray(0,s.data.byteLength-n)),s.state=0)}if(!(l<i)){o=-1,h=-1;break}h=l,d=this.getNALuType(t,l)}}if(-1!==o){let e=i;for(;e>0&&0===t[e-1];)e--;o=i-e+(0===e?n:0)}if(h>=0)a.push({data:t.subarray(h),type:d,state:o});else if(0===a.length&&-1!==o){const s=this.getLastNalUnit(e.samples);s&&(s.data=eh(s.data,t),s.state=o)}return e.naluState=o,a}},Tr=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&Gs.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}},wr=class extends br{parsePES(e,t,s,i,r){const n=r.iframe,a=this.parseNALu(e,s.data,i);let o,l=this.VideoSample,h=!1;s.data=null,l&&a.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(i=>{var r,a;switch(i.type){case 1:{if(n)break;let t=!1;o=!0;const r=i.data;if(h&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;t&&null!=(d=l)&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=t;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,ih(i.data,1,s.pts,t.samples);break;case 7:{var c,u;o=!0,h=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(c=e.pixelRatio)?void 0:c[0])!==s.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:o=!0,e.pps=[i.data];break;case 9:o=!0,e.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1}l&&o&&l.units.push(i)}),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Tr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new Tr(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const S=c(),E=c(),b=d(1);0===b&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let T=[1,1];if(u()&&u())switch(h()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*n-2*a),height:(2-b)*(E+1)*16-(b?2:4)*(o+l),pixelRatio:T}}},Ir=class extends br{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null;const l=e=>(a=this.VideoSample=this.createVideoSample(e,s.pts,s.dts),a);r.forEach((i,r)=>{var h,d;if(this.startsNewAccessUnit(a,e,i,r)){this.pushAccessUnit(a,e);const t=i.type>=16&&i.type<=23;a=l(t),o=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;n=!0,o&&null!=(c=a)&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,ih(i.data,2,s.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=zo(e.params,this.readVPS(i.data)),this.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],i.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(i.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const s in t.params)e.params[s]=t.params[s]}this.pushParameterSet(e.sps,i.data,e.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(i.data);for(const s in t)e.params[s]=t[s]}this.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(d=a)&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=l(!1));break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;const{type:r,data:n}=s;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Tr(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Tr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[];for(let e=0;e<s;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let e=s;e<8;e++)t.readBits(2);for(let e=0;e<s;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const S=t.readUEG();3==S&&t.skipBits(1);const E=t.readUEG(),b=t.readUEG(),T=t.readBoolean();let w=0,I=0,L=0,A=0;T&&(w+=t.readUEG(),I+=t.readUEG(),L+=t.readUEG(),A+=t.readUEG());const k=t.readUEG(),R=t.readUEG(),C=t.readUEG();for(let e=t.readBoolean()?0:s;e<=s;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++)if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let D=0;for(let e=0;e<P;e++){let s=!1;if(0!==e&&(s=t.readBoolean()),s){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let s=0;for(let e=0;e<=D;e++){const e=t.readBoolean();let i=!1;e||(i=t.readBoolean()),(e||i)&&s++}D=s}else{const e=t.readUEG(),s=t.readUEG();D=e+s;for(let s=0;s<e;s++)t.readUEG(),t.readBoolean();for(let e=0;e<s;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<C+4;e++)t.readBits(1);t.readBits(1)}}let M=0,_=1,O=1,x=!0,F=1,B=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),O=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(F=t.readBits(32),B=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const e=t.readBoolean(),i=t.readBoolean();let r=!1;(e||i)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){x=t.readBoolean();let s=!1;x||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(i)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let N=E,$=b;if(T){let e=1,t=1;1===S?e=t=2:2==S&&(e=2),N=E-e*I-e*w,$=b-t*A-t*L}const G=i?["A","B","C"][i]:"",H=a<<24|o<<16|l<<8|h;let W=0;for(let e=0;e<32;e++)W=(W|(H>>e&1)<<31-e)>>>0;let q=W.toString(16);return 1===n&&"2"===q&&(q="6"),{codecString:`hvc1.${G}${n}.${q}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:R,min_spatial_segmentation_idc:M,chroma_format_idc:S,frame_rate:{fixed:x,fps:B/F}},width:N,height:$,pixelRatio:[_,O]}}readPPS(e){const t=new Tr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),i=t.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return Dl(e).substring(3)===Dl(t).substring(3)}},Lr=188,Ar=class e{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,s){const i=e.syncOffset(t);return i>0&&s.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let s=Math.min(940,t-Lr)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=Lr){if(71!==e[o]||t-o!==Lr&&71!==e[o+Lr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-Lr)+1)),r||(r=0===uc(e,o)),r&&a>1&&(0===n&&a>2||o+Lr>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qs[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(t,s,i,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new kr(this.logger):null,this._audioTrack=e.createTrack("audio",r),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=i,t&&this.demux(t,0,a,"SAMPLE-AES"===(null==n?void 0:n.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,s,i,r=!1,n=!1){let a;r||(this.sampleAes=null);const o=this._videoTrack,l=this.videoIntegrityChecker,h=this._audioTrack,d=this._id3Track,c=this._txtTrack,u=i.iframe;let f=o.pid,g=o.pesData,m=h.pid,p=d.pid,v=this._klvPid,y=h.pesData,S=d.pesData,E=null,b=null,T=this.pmtParsed,w=this._pmtId,I=t.length;if(this.remainderData&&(I=(t=eh(this.remainderData,t)).length,this.remainderData=null),I<Lr&&!n)return this.remainderData=t,{audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};const L=Math.max(0,e.syncOffset(t));I-=(I-L)%Lr,I<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,I,t.buffer.byteLength-I));let A=0;for(let e=L;e<I;e+=Lr)if(71===t[e]){const s=!!(64&t[e+1]),n=uc(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+Lr)continue}else I=e+4;switch(n){case f:s&&(!g||null!=l&&l.isCorrupted||!(a=vc(g,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,c,a,!1,i)),g={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(e)),g&&(g.data.push(t.subarray(I,e+Lr)),g.size+=e+Lr-I);break;case m:if(u)break;if(s){if(y&&(a=vc(y,this.logger)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,a,i);break;case"mp3":this.parseMPEGPES(h,a);break;case"ac3":this.parseAC3PES(h,a)}y={data:[],size:0}}y&&(y.data.push(t.subarray(I,e+Lr)),y.size+=e+Lr-I);break;case p:if(u)break;s&&(S&&(a=vc(S,this.logger))&&this.parseID3PES(d,a),S={data:[],size:0}),S&&(S.data.push(t.subarray(I,e+Lr)),S.size+=e+Lr-I);break;case v:if(u)break;s&&(E&&(a=vc(E,this.logger))&&this.parseKlvPES(d,a),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+Lr)),E.size+=e+Lr-I);break;case 0:s&&(I+=t[I]+1),w=this._pmtId=fc(t,I);break;case w:{s&&(I+=t[I]+1);const n=gc(t,I,this.typeSupported,r,this.observer,this.logger,this.config,i);f=n.videoPid,f>0&&(o.pid=f,o.segmentCodec=n.segmentVideoCodec),m=n.audioPid,m>0&&(h.pid=m,h.segmentCodec=n.segmentAudioCodec),p=n.id3Pid,p>0&&(d.pid=p),v=n.klvPid,v>0&&(this._klvPid=v),null===b||T||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${b}'. Backtracking to sync byte @${L} to parse all TS packets.`),b=null,e=L-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=n}}else A++;A>0&&mc(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=g,h.pesData=y,d.pesData=S;const k={audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};return n&&this.extractRemainingSamples(k,i),k}flush(e,t){const{remainderData:s}=this;let i;return this.remainderData=null,i=s?this.demux(s,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=s.pesData,l=r.pesData,h=this.videoIntegrityChecker;let d;if(!a||null!=h&&h.isCorrupted||!(d=vc(a,this.logger))?i.pesData=a:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,n,d,!0,t),i.pesData=null)),o&&(d=vc(o,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,d,t);break;case"mp3":this.parseMPEGPES(s,d);break;case"ac3":this.parseAC3PES(s,d)}s.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=o;l&&(d=vc(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s,i){const r=this.demux(e,s,i,!0,!this.config.progressive),n=this.sampleAes=new gr(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new wr:"hevc"===e&&(this.videoParser=new Ir))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){let i=0;const r=this.aacOverFlow;let n,a,o,l=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)l=eh(r.sample.unit,l);else{const n=s-t;r.sample.unit.set(l.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(n=i,a=l.length;n<a-1&&!Zd(l,n);n++);if(n!==i){let e;const t=n<a-1;if(e=t?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",mc(this.observer,new Error(e),s,t,this.logger),!t)return}if(tc(e,this.observer,l,n,this.audioCodec),void 0!==t.pts)o=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=sc(e.samplerate);o=r.sample.pts+t}}let h,d=0;for(;n<a;){if(h=ic(e,l,n,o,d),n+=h.length,h.missing){this.aacOverFlow=h;break}for(d++;n<a-1&&!Zd(l,n);n++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(lc(s,n)){const t=nc(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=dc(e,s,o,i,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=zo({},t,{type:this._videoTrack?or.emsg:or.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;const i=null!=(s=t.pts)?s:t.dts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=t.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const s=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const e=127&o;if(0===e||e>4||n+e>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let t=0;t<e;t++)l=l<<8|r[n+t];n+=e}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=n+l,d=r.subarray(s,h),c={data:d,len:d.byteLength,pts:i,dts:null!=(a=t.dts)?a:i,type:or.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(c),n=h}}},kr=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return"ok"!==this.integrityState}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=uc(e,0);if(t!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);const s=(48&e[3])>>4;if(0===s)return;const i=15&e[3],r=this.lastContinuityCounter;this.lastContinuityCounter=i;const n=!!(1&s);if(2&s&&0!=e[4]&&128&e[5])return;if(r<0)return;const a=n?r+1&15:r;return i!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${i}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),void(this.integrityState="tei-bit")):void 0}},Rr=class{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}},Pr={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Dr=new Uint8Array([0,0,0,0,0,0,0,0]),Mr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_r=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Or=new Uint8Array([0,0,0,0,0,0,0,0]),xr=new Uint8Array([0,0,0,0,0,0,0,1]),Fr=new Uint8Array([105,115,111,109]),Br=new Uint8Array([97,118,99,49]),Ur=new Uint8Array([0,0,0,1]),Cr=Nr=class e{static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(Bl(n,0,s),Bl(n,4,e),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(t){return e.box(zs.hdlr,Pr[t])}static mdat(t){return e.box(zs.mdat,t)}static mdhd(t,s){s*=t;const i=Math.floor(s/(Ys+1)),r=Math.floor(s%(Ys+1));return e.box(zs.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return e.box(zs.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(zs.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?e.box(zs.minf,e.box(zs.smhd,Or),e.DINF,e.stbl(t)):e.box(zs.minf,e.box(zs.vmhd,_r),e.DINF,e.stbl(t))}static moof(t,s,i){return e.box(zs.moof,e.mfhd(t),e.traf(i,s))}static moov(t){let s=t.length;const i=[];for(;s--;)i[s]=e.trak(t[s]);return e.box.apply(null,[zs.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}static mvex(t){let s=t.length;const i=[];for(;s--;)i[s]=e.trex(t[s]);return e.box.apply(null,[zs.mvex,...i])}static mvhd(t,s){s*=t;const i=Math.floor(s/(Ys+1)),r=Math.floor(s%(Ys+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 e.box(zs.mvhd,n)}static sdtp(t){const s=t.samples||[],i=new Uint8Array(4+s.length);let r,n;for(r=0;r<s.length;r++)n=s[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return e.box(zs.sdtp,i)}static stbl(t){return e.box(zs.stbl,e.stsd(t),e.box(zs.stts,Dr),e.box(zs.stsc,Dr),e.box(zs.stsz,Mr),e.box(zs.stco,Dr))}static avc1(t){let s,i,r,n=[],a=[];for(s=0;s<t.sps.length;s++)i=t.sps[s],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));for(s=0;s<t.pps.length;s++)i=t.pps[s],r=i.byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));const o=e.box(zs.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return e.box(zs.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,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(zs.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(zs.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(t){return e.box(zs.mp4a,e.audioStsd(t),e.box(zs.esds,e.esds(t)))}static mp3(t){return e.box(zs[".mp3"],e.audioStsd(t))}static ac3(t){return e.box(zs["ac-3"],e.audioStsd(t),e.box(zs.dac3,t.config))}static stsd(t){const{segmentCodec:s}=t;if("audio"===t.type){if("aac"===s)return e.box(zs.stsd,xr,e.mp4a(t));if("ac3"===s&&t.config)return e.box(zs.stsd,xr,e.ac3(t));if("mp3"===s&&"mp3"===t.codec)return e.box(zs.stsd,xr,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===s)return e.box(zs.stsd,xr,e.avc1(t));if("hevc"===s&&t.vps)return e.box(zs.stsd,xr,e.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${s}/${t.codec})`)}static tkhd(t){const s=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,n=t.height||0,a=Math.floor(i/(Ys+1)),o=Math.floor(i%(Ys+1));return e.box(zs.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,255&s,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,r>>8&255,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(t,s){const i=e.sdtp(t),r=t.id,n=Math.floor(s/(Ys+1)),a=Math.floor(s%(Ys+1));return e.box(zs.traf,e.box(zs.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),e.box(zs.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,e.box(zs.trak,e.tkhd(t),e.mdia(t))}static trex(t){const s=t.id;return e.box(zs.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,s){const i=t.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,h,d,c,u;for(s+=8+n,a.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s],0),o=0;o<r;o++)l=i[o],h=l.duration,d=l.size,c=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,255&h,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*o);return e.box(zs.trun,a)}static initSegment(t){const s=e.moov(t);return eh(e.FTYP,s)}static hvc1(t){const s=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,s.general_profile_space<<6|(s.general_tier_flag?32:0)|s.general_profile_idc,s.general_profile_compatibility_flags[0],s.general_profile_compatibility_flags[1],s.general_profile_compatibility_flags[2],s.general_profile_compatibility_flags[3],s.general_constraint_indicator_flags[0],s.general_constraint_indicator_flags[1],s.general_constraint_indicator_flags[2],s.general_constraint_indicator_flags[3],s.general_constraint_indicator_flags[4],s.general_constraint_indicator_flags[5],s.general_level_idc,240|s.min_spatial_segmentation_idc>>8,255&s.min_spatial_segmentation_idc,252|s.parallelismType,252|s.chroma_format_idc,248|s.bit_depth_luma_minus8,248|s.bit_depth_chroma_minus8,0,parseInt(s.frame_rate.fps),3|s.temporal_id_nested<<2|s.num_temporal_layers<<3|(s.frame_rate.fixed?64:0),i.length]);let n=r.length;for(let e=0;e<i.length;e+=1){n+=3;for(let t=0;t<i[e].length;t+=1)n+=2+i[e][t].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=i.length-1;for(let e=0;e<i.length;e+=1){a.set(new Uint8Array([32+e|(e===o?128:0),0,i[e].length]),n),n+=3;for(let t=0;t<i[e].length;t+=1)a.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),n),n+=2,a.set(i[e][t],n),n+=i[e][t].length}const l=e.box(zs.hvcC,a),h=t.width,d=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return e.box(zs.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,255&h,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,e.box(zs.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(zs.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}},Nr.FTYP=Cr.box(zs.ftyp,Fr,Ur,Fr,Br),Nr.DINF=Cr.box(zs.dinf,Cr.box(zs.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]))),$r=9e4,Gr=8589934592,Hr=class extends Bs{constructor(e,t,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Ec(t):t} > ${e?Ec(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=Tc(r,s),n=r-e),n>0?e:r},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o,l){let h,d,c,u,f,g,m=r,p=r;const v=!l.iframe&&e.pid>-1,y=t.pid>-1,S=t.samples.length,E=e.samples.length>0,b=a&&S>0||S>1;if((!v||E)&&(!y||b)||this.ISGenerated||a){if(this.ISGenerated){var T,w,I,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(w=e.pixelRatio)?void 0:w[0])||(null==(I=t.pixelRatio)?void 0:I[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&b||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(b&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,a>0){this.warn(`Dropped ${a} out of ${S} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(E&&b&&r){const s=this.getVideoStartPts(t.samples),i=(Tc(e.samples[0].pts,s)-s)/t.inputTimeScale;m+=Math.max(0,i),p+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,m,this.isAudioContiguous,n,y||b||o===Ps.AUDIO?p:void 0,l),b){const i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),h=this.remuxVideo(t,p,s,i,l)}}else b&&(h=this.remuxVideo(t,p,s,0,l));h&&(h.firstKeyFrame=a,h.independent=-1!==a,h.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=wc(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Ic(i,r,this._initPTS))),{audio:d,video:h,initSegment:c,independent:g,text:u,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Tc(e,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r;)n+=Gr;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS,h=!l||i;let d,c,u,f="audio/mp4",g=-1;if(h&&(d=c=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Nr.initSegment([e]),metadata:{channelCount:e.channelCount}},h){g=e.id,u=e.inputTimeScale;const t=this.computeInitPts(r[0].pts,u,s,"audio");(!l||u!==l.timescale||0===s&&t<l.baseTime)&&(d=c=t)}}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Nr.initSegment([t]),metadata:{width:t.width,height:t.height}},h){g=t.id,u=t.inputTimeScale;const e=this.getVideoStartPts(n),i=Tc(n[0].dts,e),r=this.computeInitPts(i,u,s,"video"),a=this.computeInitPts(e,u,s,"video");(!l||u!==l.timescale||Ss(d)||0===s&&a<l.baseTime)&&(c=Math.min(c,r),d=Math.min(d,r))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h&&Ss(d)?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/u} (${d}/${u}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:u,trackId:g},this._initDTS={baseTime:c,timescale:u,trackId:g}):d=u=void 0,{tracks:o,initPTS:d,timescale:u,trackId:g}}remuxVideo(e,t,s,i,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,h=this._initPTS,d=h.baseTime*n/h.timescale;let c,u,f=this.nextVideoTs,g=8,m=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!s||null===f){const e=d+t*n,i=a[0].pts-Tc(a[0].dts,a[0].pts);lh()&&null!==f&&Math.abs(e-i-(f+d))<15e3?s=!0:f=e-i-d}const S=f+d;for(let e=0;e<l;e++){const t=a[e];t.pts=Tc(t.pts,S),t.dts=Tc(t.dts,S),t.dts<a[e>0?e-1:e].dts&&(y=!0)}y&&a.sort(function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i}),c=a[0].dts,u=a[a.length-1].dts;const E=u-c,b=E?Math.round(E/(l-1)):m||e.inputTimeScale/30;if(s){const s=c-S,i=s>b,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Sc(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Sc(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||S>=a[0].pts||lh())){c=S;const e=a[0].pts-s;if(i)a[0].dts=c,a[0].pts=e;else{let t=!0;for(let i=0;i<a.length&&!(a[i].dts>e&&t);i++){const e=a[i].pts;if(a[i].dts-=s,a[i].pts-=s,i<a.length-1){const s=a[i+1].pts;t=s<=a[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Sc(e,!0)}/${Sc(c,!0)}, delta: ${Sc(s,!0)} ms`)}}c=Math.max(0,c);let T=0,w=0,I=c;for(let e=0;e<l;e++){const t=a[e],s=t.units,i=s.length;let r=0;for(let e=0;e<i;e++)r+=s[e].data.length;w+=r,T+=i,t.length=r,t.dts<I?(t.dts=I,I+=b/4|0||1):I=t.dts,p=Math.min(t.pts,p),v=Math.max(t.pts,v)}u=a[l-1].dts;const L=w+4*T+8;let A;try{A=new Uint8Array(L)}catch(e){return void this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MUX_ERROR,details:ws.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:e,bytes:L,reason:`fail allocating video mdat ${L}`})}Bl(A,0,L),Bl(A,4,zs.mdat);let k=!1,R=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let e=0;e<l;e++){const t=a[e],h=t.units;let c,u=0;for(let e=0,t=h.length;e<t;e++){const t=h[e],s=t.data,i=t.data.byteLength;Bl(A,g,i),g+=4,A.set(s,g),g+=i,u+=4+i}if(e<l-1)m=a[e+1].dts-t.dts,c=a[e+1].pts-t.pts;else{const s=this.config,r=e>0?t.dts-a[e-1].dts:b;if(c=e>0?t.pts-a[e-1].pts:b,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(s.maxBufferHole*n),a=(i?p+i*n:this.nextAudioTs+d)-t.pts;a>e?(m=a-r,m<0?m=r:k=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=r}else m=r}let f=Math.round(t.pts-t.dts);if(R=Math.min(R,m),P=Math.max(P,m),C=Math.min(C,c),D=Math.max(D,c),!s&&0===e&&f>m){const e=Math.round(f/b)*b;e-f===1&&(this.log(`pad first CTS ${f} -> ${e} of sn: ${r.sn}`),f=e)}o.push(bc(t.key,m,u,f))}if(o.length){const e=lh();if(e){if(e<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(function(){if(void 0===si){const e=Js.match(/Safari\/(\d+)/i);si=e?parseInt(e[1]):0}return si}()&&D-C<P-R&&b/P<.025&&0===o[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,s=o.length;t<s;t++){const i=e+o[t].duration,r=e+o[t].cts;if(t<s-1){const e=i+o[t+1].cts;o[t].duration=e-r}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=i}}}m=k||!m?b:m;const M=u+m;this.nextVideoTs=f=M-d,this.videoSampleDuration=m,this.isVideoContiguous=!0,r.iframe&&(1===o.length?(o[0].duration=m=r.duration*n,this.nextVideoTs=f=c+m-d):this.warn(`Not adjusting IFrame duration (sample count ${o.length})`));const _={data1:Nr.moof(r.sn,c,zo(e,{samples:o})),data2:A,startPTS:(p-d)/n,endPTS:(v+m-d)/n,startDTS:(c-d)/n,endDTS:f/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,_}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r,n){const a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),l=this.getSamplesPerFrame(e),h=l*o,d=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],f=void 0!==r;let g=e.samples,m=c?0:8,p=this.nextAudioTs||-1;const v=d.baseTime*a/d.timescale,y=v+t*a;if(this.isAudioContiguous=s=s||g.length&&p>0&&(i&&Math.abs(y-(p+v))<9e3||Math.abs(Tc(g[0].pts,y)-(p+v))<20*h),g.forEach(function(e){e.pts=Tc(e.pts,y)}),!s||p<0){const e=g.length;if(g=g.filter(e=>e.pts>=0),e!==g.length&&this.warn(`Removed ${g.length-e} of ${e} samples (initPTS ${v} / ${a})`),!g.length)return;p=0===r?0:i&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=p+v;s<g.length;s++){const r=g[s],n=r.pts,o=n-i,l=Math.abs(1e3*o/a);if(o<=-t*h&&f)0===s&&(this.warn(`Audio frame @ ${(n/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/a)} ms.`),this.nextAudioTs=p=n-v,i=n);else if(o>=t*h&&l<1e4&&f){let t=Math.round(o/h);for(i=n-t*h;i<0&&t&&h;)t--,i+=h;0===s&&(this.nextAudioTs=p=i-v),this.warn(`Injecting ${t} audio frames @ ${((i-v)/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);for(let n=0;n<t;n++){let t=Rr.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),g.splice(s,0,{unit:t,pts:i}),i+=h,s++}}r.pts=i,i+=h}}let S,E=null,b=null,T=0,w=g.length;for(;w--;)T+=g[w].unit.byteLength;for(let t=0,i=g.length;t<i;t++){const i=g[t],r=i.unit;let a=i.pts;if(null!==b)u[t-1].duration=Math.round((a-b)/o);else{if(s&&"aac"===e.segmentCodec&&(a=p+v),E=a,!(T>0))return;T+=m;try{S=new Uint8Array(T)}catch(e){return void this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MUX_ERROR,details:ws.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}c||(Bl(S,0,T),Bl(S,4,zs.mdat))}S&&S.set(r,m);const h=r.byteLength;m+=h,u.push(bc(!0,l,h,0)),b=a}const I=u.length;if(!I)return;const L=u[u.length-1];p=b-v,this.nextAudioTs=p+o*L.duration;const A=c?new Uint8Array(0):Nr.moof(e.sequenceNumber++,E/o,zo({},e,{samples:u}));e.samples=[];const k=(E-v)/a,R=this.nextAudioTs/a,C={data1:A,data2:S,startPTS:k,endPTS:R,startDTS:k,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}},Wr=class extends Bs{constructor(e,t,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=s||ql(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;16===(null==s?void 0:s.byteLength)&&t.isCommonEncryption&&Ql(e,(e,t)=>{const i=e.subarray(8,24);i.some(e=>0!==e)||(Gs.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Rl(i)} -> ${Rl(s)}`),e.set(s,8))})}(e,t);else{const e=n||a;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}n&&(i=Ac(n,Ds.AUDIO,this)),a&&(r=Ac(a,Ds.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n,a,o,l,h,d){var c,u;let{initPTS:f,lastEndTime:g}=this;const m={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Ss(g)||(g=this.lastEndTime=r||0);const p=t.samples;if(!p.length)return m;const v=this.pendingInitSegment;v&&(this.pendingInitSegment=void 0,this.generateInitSegment(v,this.decryptdata,h));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let S=this.initData;if(null!=(c=S)&&c.length||(this.generateInitSegment(p),S=this.initData),null==(u=S)||!u.length)return this.warn("Failed to generate initSegment."),m;if(l.iframe&&S.audio&&S.video){var E;const e=null==(E=this.initTracks)||null==(E=E.audiovideo)?void 0:E.initSegment,t=e?function(e){const t=Gl(e,["moov"]);if(1!==t.length||Gl(e,["moof"]).length)return null;const s=e.byteOffset,i=[],r=[];let n=!1;const a=Gl(t[0],["trak"]);for(let e=0;e<a.length;e++){const t=a[e],o=Gl(t,["mdia","hdlr"])[0];if("vide"===(o?Dl(o.subarray(8,12)):"")){n=!0;continue}const l=Gl(t,["tkhd"])[0];if(!l)return null;const h=l[0];r.push(_l(l,0===h?12:20)),i.push(Nl(t,s))}if(!n||!i.length)return null;const o=Gl(t[0],["mvex"])[0];let l=0;if(o){const e=Gl(o,["trex"]);for(let t=0;t<e.length;t++){const n=e[t];-1!==r.indexOf(_l(n,4))&&(i.push(Nl(n,s)),l+=n.byteLength+8)}}const{result:h,dropped:d,droppedBefore:c}=$l(e,i);if(Bl(h,t[0].byteOffset-s-8,t[0].byteLength+8-d),o&&l){const e=o.byteOffset-s-8;Bl(h,e-c(e),o.byteLength+8-l)}return h}(e):null;var b;t&&(this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(t,this.decryptdata),null!=(b=this.initData)&&b.length&&(S=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0))}this.emitInitSegment&&(y.tracks=this.initTracks,m.initSegment=y,this.emitInitSegment=!1);const T=l.iframe,w=!d||T&&!d.includeSampleDetails?function(e,t,s,i,r=!0){return Zl(e,t,i,r)}(p,S,0,this,T):d.tracks,I=S.audio?w[S.audio.id]:null,L=S.video?w[S.video.id]:null,A=!!S.audio,k=!!S.video;let R="";A&&(R+="audio"),k&&(R+="video");const C=Lc(L,1/0),P=Lc(I,1/0),D=Lc(L,0,!0),M=Lc(I,0,!0);let _=r,O=0;L&&I&&S.audio&&(P>D||C>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${C}-${D} a: ${P}-${M}}`,L,I);const x=!!I&&(!L||!f&&P<C||!!f&&f.trackId===S.audio.id),F=x?I:L;if(!F)return this.log(`No media samples found in ${o} ${l.level} ${-1===l.part?"":`part: ${l.part} of`} sn: ${l.sn} at playlist time: ${r}`),m;let B,U=p;if(L&&L.sampleCount>=1&&S.video&&l.iframe){const{trun:e,start:t}=L,s=1===e.length,i=e.length?s?e[0].samples:e[0].samples.concat(...e.slice(1).map(e=>e.samples)):[];if(i.length){const r=e[0];let n=r;for(let t=e.length;t--;)if(e[t].samples.length){n=e[t];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,h=Math.abs(l.duration-(D-C))>.05,d=i.length<L.sampleCount;if(h||d||this.videoOnlyRemux||!s){const e=d?n.sampleOffset+n.samples.reduce((e,t)=>e+t.size,0):void 0,s=h?l.duration:D-C,r=function(e,t,s,i){if(void 0!==s){const i=e[e.length-1];let r=t;for(let t=0;t<e.length-1;t++)r-=e[t].duration;return r<=0&&(r=i.duration),i.duration=r,{durationOffset:s,value:r}}if(void 0===i)return;const r=Math.round(t/e.length);for(let t=0;t<e.length;t++)e[t].duration=r;return{durationOffset:i,value:r}}(i,s*S.video.timescale,a,o),c=function(e,t,s,i,r){if(s<1)return null;const n=Gl(e,["moof"]);if(1!==n.length)return null;const a=n[0],o=e.byteOffset,l=[],h=[],d=Gl(a,["traf"]);let c=!0;for(let e=0;e<d.length;e++){const s=d[e],i=Gl(s,["tfhd"])[0];if(!i)return null;_l(i,4)===t?(l.push(s),131072&_l(i,0)||(c=!1)):h.push(Nl(s,o))}if(!l.length)return null;if(h.length&&!c)return null;if(void 0!==i){let t=s;for(let s=0;s<l.length;s++){const i=l[s];let r=0;const n=Gl(i,["trun"]);for(let s=0;s<n.length;s++){const i=n[s],a=Math.min(t,_l(i,4));if(a){Bl(e,i.byteOffset-o+4,a);const t=16777215&_l(i,0);Ul(e,i,8+(1&t?4:0)+(4&t?4:0)+a*((256&t?4:0)+(512&t?4:0)+(1024&t?4:0)+(2048&t?4:0)))}else Bl(e,i.byteOffset-o-4,zs.free);t-=a,r+=a}const a=Gl(i,["senc"])[0];a&&Bl(e,a.byteOffset-o+4,r);const h=Gl(i,["saiz"])[0];if(h){let t=4;1&(h[1]<<16|h[2]<<8|h[3])&&(t+=8);const s=h[t];t+=1,Bl(e,h.byteOffset-o+t,r),Ul(e,h,t+4+(0===s?r:0))}}const r=Gl(e,["mdat"]);if(1===r.length){const t=r[0].byteOffset-o-8;Bl(e,t,i-t)}}let u=e,f=0,g=()=>0;if(h.length){({result:u,dropped:f,droppedBefore:g}=$l(e,h)),Bl(u,a.byteOffset-o-8,a.byteLength+8-f);for(let e=0;e<l.length;e++){const t=l[e],s=g(t.byteOffset-o),i=Gl(t,["trun"]);for(let e=0;e<i.length;e++){const t=i[e];1&_l(t,0)&&Bl(u,t.byteOffset-o-s+8,_l(t,8)-f)}if(s){const e=Gl(t,["saio"]);for(let t=0;t<e.length;t++){const i=e[t],r=0===i[0]?4:8;let n=1&_l(i,0)?12:4,a=_l(i,n);for(n+=4;a--;n+=r){const e=n+r-4;Bl(u,i.byteOffset-o-s+e,_l(i,e)-s)}}}}}if(r){const{durationOffset:e,value:t}=r;Bl(u,e-g(e),t)}return void 0!==i?u.subarray(0,i-f):u}(p,S.video.id,i.length,e,r);c?(U=c,B=function(e,t){let s=e,i=e;for(let e=0;e<t.length;e++){const{cts:r,duration:n}=t[e];i=Math.max(i,s+(r||0)+n),s+=n}return i}(t,i)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),O=c&&r?s:D-C}else O=D-C}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${e.length})`),O=D-C}else O=x?M-P:D-C;if(this.videoOnlyRemux&&U===p)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),m;const N=F.timescale,$=F.start-r*N,G=x?S.audio.id:S.video.id;if(_=F.start/N,(n||!f)&&(function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>=r}(f,_,r,O)||N!==f.timescale)){let e=!1;const t=x?"audio":"video";if(f){const s=0!==r?_/r:1+_/1;e=_>=0&&Math.abs(1-s)<.001,this.log(`${t} timestamps in track ${G} at playlist time: ${n?"":"~"}${r} maps to ${_} with initPTS: ${f.baseTime/f.timescale} (${$/N-f.baseTime/f.timescale}s diff) (${R}) drift estimate: ${s} ${e?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}e||(this.log(`Found initPTS in ${t} track ${G} at playlist time: ${r} offset: ${_-r} (${$}/${N})`),f=null,y.initPTS=$,y.timescale=N,y.trackId=G)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=_,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const H=_-f.baseTime/f.timescale,W=H+O,q=k&&void 0!==(null==F?void 0:F.ptsMin)?F.ptsMin/F.timescale-f.baseTime/f.timescale:H,j=void 0!==B&&L?B/L.timescale-f.baseTime/f.timescale:k&&null!=F&&F.ptsMax?F.ptsMax/F.timescale-f.baseTime/f.timescale:W;O>0?this.lastEndTime=W:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K={data1:U,data2:void 0,startPTS:q,startDTS:H,endPTS:j,endDTS:W,type:R,hasAudio:A,hasVideo:k,nb:1,dropped:0,encrypted:!!S.audio&&S.audio.encrypted||!!S.video&&S.video.encrypted};m.audio=A&&!k?K:void 0,m.video=k?K:void 0;const V=this.isVideoContiguous,Y=null==L?void 0:L.sampleCount;if(Y){const e=L.keyFrameIndex,t=-1!==e;K.nb=Y,K.dropped=0===e||V?0:t?e:Y,K.independent=t,K.firstKeyFrame=e,t&&L.keyFrameStart&&(K.firstKeyFramePTS=(L.keyFrameStart-f.baseTime)/f.timescale),V||(m.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),K.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${Y} dropped: ${K.dropped} start: ${K.firstKeyFramePTS||"NA"}`)}return m.initSegment=y,m.id3=wc(s,r,f,f),i.samples.length&&(m.text=Ic(i,r,f)),m}};try{qr=self.performance.now.bind(self.performance)}catch(e){qr=Date.now}(jr=[{demux:Er,remux:Wr},{demux:Ar,remux:Hr},{demux:mr,remux:Hr},{demux:yr,remux:Hr}]).splice(2,0,{demux:vr,remux:Hr}),Kr=class{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){if(!this.observer)return Vr(s);const r=s.transmuxing;r.executeStart=qr();const n=new Uint8Array(e),{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,S=function(e,t){let s=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t),s}(n,t);if(S&&ld(S.method)){const e=this.getDecrypter(),t=hd(S.method);return this.asyncResult=!0,this.decryptionPromise=e.decrypt(n,S.key.buffer,S.iv.buffer,t,s.decryptRange).then(e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t}),this.decryptionPromise}const E=this.needsProbing(h,d);if(E){const e=s.iframe&&y&&Ar.probe(y,this.logger)?y:n,t=this.configureTransmuxer(e);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=qr(),Vr(s)}(h||d||f||E)&&this.resetInitSegment(y,g,m,v,t,s),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const b=this.transmux(n,S,u,c,s);this.asyncResult=kc(b);const T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,r.executeEnd=qr(),b}flush(e){const t=e.transmuxing;t.executeStart=qr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=qr();const s=[Vr(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a,e);return kc(h)?(this.asyncResult=!0,h.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=qr()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(e,t,s,i,r,n),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,s,i,r){let n;return n="SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Vr(i);const a=r.demux(e,t,i,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:h,textTrack:d}=a;return{remuxResult:n.remux(o,l,h,d,t,s,!1,this.id,i,a.initData,a.sampleData),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,r).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id,r,e.initData,e.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let t=0,s=jr.length;t<s;t++){var n;if(null!=(n=jr[t].demux)&&n.probe(e,this.logger)){r=jr[t];break}}}catch(e){return e}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,h=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(s,t,i,this.logger),this.probe=l.probe),o&&o instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(s,t,i,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ai(this.config)),e}},Vr=e=>({remuxResult:{},chunkMeta:e}),Yr=class{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},zr=class{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}},Qr=0,Xr=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Qr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Is.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new rr,this.observer.on(Is.FRAG_DECRYPTED,n),this.observer.on(Is.ERROR,n);const a=Eh(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=ar[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return ar[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=ar[nr];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return ar[nr]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:gi(r)})}catch(i){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Kr(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Kr(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Qr++;const t=this.hls.config,s=Eh(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:gi(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=ar[e||nr];if(t&&1===t.clientCount--){const{worker:s,objectURL:i}=t;delete ar[e||nr],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!p||r.cc!==p.cc,y=!p||l.level!==p.level,S=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,b=0===S&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),T=!y&&(1===S||0===S&&(1===E||b&&E<=0)),w=self.performance.now();(y||S||0===r.stats.parsing.start)&&(r.stats.parsing.start=w),!n||!E&&T||(n.stats.parsing.start=w);const I=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),L=new zr(v,T,o,y,g,I);if(!T||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${T}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const e=new Yr(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,L);kc(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);kc(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Jr=class extends er{constructor(e,t,s){super(e,t,s,"audio-stream-controller",Ps.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Is.BUFFER_RESET,this.onBufferReset,this),e.on(Is.BUFFER_CREATED,this.onBufferCreated,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Is.BUFFER_RESET,this.onBufferReset,this),e.off(Is.BUFFER_CREATED,this.onBufferCreated,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:s,id:i,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=t;if(i===Ps.MAIN){const e=s.cc,t=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${e} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=s,this.state===Zi.WAITING_INIT_PTS){const t=this.waitingData;(!t&&!this.loadingParts||t&&t.frag.cc!==e)&&this.syncWithAnchor(s,null==t?void 0:t.frag)}else!this.hls.hasEnoughToStart&&t&&t.cc!==e?(t.abortRequests(),this.syncWithAnchor(s,t)):this.state===Zi.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(e=this.switchingTrack)?void 0:e.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(t&&(null==i?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=Wh(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===Zi.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Zi.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=Zi.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case Zi.IDLE:this.doTickIdle();break;case Zi.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Zi.WAITING_INIT_PTS}break}case Zi.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Zi.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Zi.FRAG_LOADING;const e={frag:t,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=Zi.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Zi.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ds.AUDIO));const h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(Is.BUFFER_EOS,{type:"audio"}),void(this.state=Zi.ENDED);const d=h.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:h.end;if(this.switchingTrack&&i){const e=g;o.PTSKnown&&e<f&&e>=this.timelineOffset&&(h.end>f||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${e} -> ${f} + 0.05`),i.currentTime=f+.05)}if(d>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,h,Ps.MAIN,c)),!p)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,c,p))return;let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Wo(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ei.OK&&(this.mainFragLoading=v=null),v&&Wo(v))){if(p.start>v.end){const e=this.fragmentTracker.getFragAtPos(m,Ps.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new ui(e))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Zi.STOPPED&&(this.setInterval(100),this.state=Zi.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Is.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=t;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Zi.STOPPED&&(this.state=Zi.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||null!=(s=h.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;h.details&&(d=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details)),r.alignedSliding||(qd(l,r,this),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(Is.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==Zi.WAITING_TRACK||this.waitForCdnTuneIn(r)||(this.state=Zi.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Xr(this.hls,Ps.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=i?i.index:-1,n=-1!==t,a=new Di(s.level,s.sn,s.stats.chunkCount,r.byteLength,t,n,s.duration);c.push(r,f,d,"",s,i,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new tr,complete:!1};e.push(new Uint8Array(r)),this.state!==Zi.STOPPED&&(this.state=Zi.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ps.MAIN&&Wo(t.frag)&&(this.mainFragLoading=t,this.state===Zi.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type===Ps.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Wo(s)){const e=this.switchingTrack;e&&(this.bufferedTrack=e)}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==Ps.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,Ps.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const t=this.fragPlaying,s=null==e?void 0:e.level;return t&&t.level===s||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal)this.state=Zi.ERROR;else switch(t.details){case ws.FRAG_GAP:case ws.FRAG_PARSING_ERROR:case ws.FRAG_DECRYPT_ERROR:case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ps.AUDIO,t);break;case ws.AUDIO_TRACK_LOAD_ERROR:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Zi.WAITING_TRACK||(null==(s=t.context)?void 0:s.type)!==Cs.AUDIO_TRACK||(this.state=Zi.IDLE);break;case ws.BUFFER_APPEND_NO_PROGRESS:if("audio"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ws.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ws.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Ds.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ds.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Zi.ENDED&&(this.state=Zi.IDLE);const e=this.getBufferOutput();e&&(this.afterBufferFlushed(e,t),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(this.fragContextChanged(o)||!d)return this.fragmentTracker.removeFragment(o),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=Zi.PARSING,c&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:e}=this,t=e.nextAudioTrackBufferFlushForwardOffset,s=Math.max(this.getLoadPosition()+t,o.start);super.flushMainBuffer(s,Number.POSITIVE_INFINITY,Ps.AUDIO)}if(null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,e,n),i.trigger(Is.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Ds.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Ds.AUDIO,e,t,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=zo({id:s,frag:o,details:d},f);i.trigger(Is.FRAG_PARSING_METADATA,e)}if(u){const e=zo({id:s,frag:o,details:d},u);i.trigger(Is.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,s,i){if(this.state!==Zi.PARSING)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=Ps.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(Is.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(Is.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||i===Ei.NOT_LOADED||i===Ei.PARTIAL)if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Zi.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&qd(s,t.details,this)}else super.loadFragment(e,t,s);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Oh({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},e,xh)||(Bh(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Is.AUDIO_TRACK_SWITCHED,Xo({},e))}get nextAudioTrack(){return this.nextTrackId}},Zr=class extends Bs{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=i[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&Rh(s);return new ci(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=i.fragments,a=self.performance.now(),o=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;i.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const e=Math.max(l||0,0);i.appliedTimelineOffset=e,n.forEach(t=>{null==t||t.setStart(t.playlistOffset+e)})}if(i.live||null!=s&&s.live){var h;const l="levelInfo"in t?t.levelInfo:t.track;i.reloaded(s);const d=null==(h=n[n.length-1])?void 0:h.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const e=new Error(`${d} playlist ${l.id} hit max allowed unchanged reloads.`);this.warn(e);const{networkDetails:s,context:n}=t;return void this.hls.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level,parent:d,context:n,networkDetails:s,stats:r})}if(s){!function(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){i=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){var i;const r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let i=n;i<=a;i++){const n=h[o+i];let a=l[i];if(r&&!a&&n&&(a=t.fragments[i]=n),n&&a){s(n,a,i,l);const r=n.relurl,o=a.relurl;if(r&&Nd(r,o))return void(t.playlistParsingError=Md(`media sequence mismatch ${a.sn}:`,e,t,0,a));if(n.cc!==a.cc)return void(t.playlistParsingError=Md(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,e,t,0,a))}}}(e,t,(e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}Ss(e.startPTS)&&Ss(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=zo({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;return a?(Object.keys(i).forEach(e=>{const t=n[e],r=new Ui(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${gi(i[e].attr)}"`)}),n):i}(e.dateRanges,t,s));const i=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&Ld(o[e],o[e-1],i);Sd(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=xd(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}(function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}})(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),n?(t.iframesOnly&&(n.type,Ps.MAIN),Dd(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,0,s)):_d(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){const{networkDetails:n}=t;return void s.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level,parent:d,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,f=Od(i,1e3*(i.edge-u));i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled<=a&&(i.requestScheduled+=f);const g=t.deliveryDirectives;if(this.log(`live playlist ${e} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${g?` | requested ${g.msn} - ${g.part}`:""})`}`),!this.canLoad||!i.live)return;let m,p,v;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,o=i.lastPartIndex,h=r===n;-1!==o?h?(p=n+1,v=e?0:o):(p=r,v=e?o+1:i.maxPartIndex):p=n+1;const d=i.age,c=d+i.ageHeader;let u=Math.min(c-i.partTarget,1.5*i.targetduration);if(u>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${u} with playlist age: ${i.age}`),u=0;else{const e=Math.floor(u/i.targetduration);p+=e,void 0!==v&&(v+=Math.round(u%i.targetduration/i.partTarget)),this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${u} skip sn ${e} to part ${v}`)}i.tuneInGoal=u}if(m=this.getDeliveryDirectives(i,t.deliveryDirectives,p,v),e||!h)return i.requestScheduled=a,void this.loadingPlaylist(l,m)}else(i.canBlockReload||i.canSkipUntil)&&(m=this.getDeliveryDirectives(i,t.deliveryDirectives,p,v));m&&void 0!==p&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(l,m,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,i){let r=Rh(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=di.No),new ci(s,i,r)}checkRetry(e){const t=e.details,s=Zo(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===vi.RetryRequest||!i.resolved&&r===vi.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;const s=al(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),s)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const e=il(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),e)}}e.levelRetry=!0,i.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),al(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}},en=class extends Zr{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(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Is.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>Uh(e.groupId,s));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const s=_h(t,e,xh);if(s>-1)r=e[s];else{const e=_h(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(Is.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.AUDIO_TRACK&&t.context.id===this.trackId&&Uh(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Oh(e,i,xh))return i;const r=_h(e,this.tracksInGroup,xh);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),t}if(i){let i=t.loadLevel;-1===i&&(i=t.firstAutoLevel);const r=function(e,t,s,i,r){const n=t[i],a=t.reduce((e,t,s)=>{const i=t.uri;return(e[i]||(e[i]=[])).push(s),e},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Fh(t,i,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const i=t.audioGroups,n=s.filter(e=>Uh(e.groupId,i));return _h(e,n,r)>-1});return d>-1?d:Fh(t,i,t=>{const i=t.audioGroups,n=s.filter(e=>Uh(e.groupId,i));return _h(e,n,r)>-1})}(e,t.levels,s,i,xh);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=_h(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e,t=!0){const s=this.tracksInGroup;if(e<0||e>=s.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Is.AUDIO_TRACK_SWITCHING,Xo(Xo({},r),{},{flushImmediate:t})),n)return;const a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||Oh(e,i,xh)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++)if(Oh({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],xh))return e;for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Bh(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(Is.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},tn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"===s||"async-blocker-prepend"===s?(e[0].execute(),e.splice(0,1)):"block-audio"===s&&e.splice(0,1)})}insertNext(e,t){null!==this.queues&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(e=>"block-audio"===e.label)}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){var s;if(i.onError(t),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[e])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}},sn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rn="HlsJsTrackRemovedError",nn=.001,an=class extends Error{constructor(e){super(e),this.name=rn}},on=class extends Bs{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(Kd(s,"sourceopen",this._onMediaSourceOpen),Kd(t,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Is.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const e=this.media.error,{appendError:t,appendErrors:s}=this;let i=!1;!t&&e&&(i=Math.max(++s.audio,++s.video,++s.audiovideo)>=this.hls.config.appendErrorMaxRetry);const r=new Error(`MediaSource closed while media attached${Mc(i,e)}`);this.warn(r),this.hls.trigger(Is.ERROR,zo({fatal:i},t,{type:Ts.MEDIA_ERROR,details:ws.MEDIA_SOURCE_REQUIRES_RESET,error:r}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this._onMediaError=()=>{const{media:e}=this;var t,s;e&&this.log(`Media error (code: ${null==(t=e.error)?void 0:t.code}): ${null==(s=e.error)?void 0:s.message}`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=dl(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.BUFFER_RESET,this.onBufferReset,this),e.on(Is.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Is.BUFFER_EOS,this.onBufferEos,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.FRAG_PARSED,this.onFragParsed,this),e.on(Is.FRAG_CHANGED,this.onFragChanged,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.BUFFER_RESET,this.onBufferReset,this),e.off(Is.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.BUFFER_EOS,this.onBufferEos,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.FRAG_PARSED,this.onFragParsed,this),e.off(Is.FRAG_CHANGED,this.onFragChanged,this),e.off(Is.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===t?zo(s,i.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(s[t]=zo({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=dl(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(r),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&r instanceof t,Pc(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e}jd(s,"emptied",this._onMediaEmptied),jd(s,"error",this._onMediaError)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),jd(e,"sourceopen",this._onMediaSourceOpen),jd(e,"sourceended",this._onMediaSourceEnded),jd(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(jd(e,"startstreaming",this._onStartStreaming),jd(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${gi(s,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${gi(i,(e,t)=>"initSegment"===e?void 0:t)}}`),!cl(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(Is.MEDIA_DETACHING,{}),this.onMediaAttaching(Is.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=_i.getBuffered(e);i.detectEvictedFragments(t,s,r,null,null,!0)}const n=Dc(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Kd(r,"sourceopen",this._onMediaSourceOpen),Kd(r,"sourceended",this._onMediaSourceEnded),Kd(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Kd(r,"startstreaming",this._onStartStreaming),Kd(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Kd(i,"emptied",this._onMediaEmptied),Kd(i,"error",this._onMediaError),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Pc(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Dc(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new tn(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!i[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=vh(m,p),y=null==v?void 0:v.replace(sn,"$1");let S=vh(o,l);const E=null==(r=S)?void 0:r.replace(sn,"$1");S&&v&&y!==E&&("audio"===e.slice(0,5)&&(S=ph(S,this.appendSource)),this.log(`switching codec ${m} to ${S}`),S!==(u.pendingCodec||u.codec)&&(u.pendingCodec=S),u.container=h,this.appendChangeType(e,h,S))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,Ps.MAIN))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e,t;(this.lastVideoAppendEnd>i||_i.isBuffered(null==(e=this.tracks.video)?void 0:e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,Ps.MAIN))?void 0:t.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],c=Wo(a)&&!o&&!a.gap&&!l.partial&&!l.iframe;let u=null,f=!1;const{sn:g,cc:m}=a,p=self.performance.now();d.start=p;const v=a.stats.buffering,y=o?o.stats.buffering:null;0===v.start&&(v.start=p),0===(null==y?void 0:y.start)&&(y.start=p);const S=s.audio;let E=!1;"audio"===r&&"audio/mpeg"===(null==S?void 0:S.container)&&(E=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const b=s.video,T=null==b?void 0:b.buffer;if(T&&"initSegment"!==g&&void 0!==h){const e=null==S?void 0:S.buffer,t=o||a;if("audio"===r&&"main"!==n&&!b.ending&&!b.ended&&e&&_i.getBuffered(e).length){const e=t.start+.05*t.duration,s=_i.getBuffered(T),i=this.currentOp("video");s.length||i?!_i.isBuffered(T,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}else if("video"===r){const e=t.end,s=this.lastVideoAppendEnd-e;this.lastVideoAppendEnd=e,s<0||s>t.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const w=(o||a).start,I={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(c&&(u=_i.timeRangesToArray(_i.getBuffered(t)),f=xc(Oc(u,a),a)),E?this.updateTimestampOffset(t,w,.1,r,g,m):void 0!==h&&Ss(h)&&this.updateTimestampOffset(t,h,1e-6,r,g,m)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const e=self.performance.now();d.executeEnd=d.end=e,0===v.first&&(v.first=e),0===(null==y?void 0:y.first)&&(y.first=e);const t={};if(this.sourceBuffers.forEach(([e,s])=>{e&&(t[e]=_i.getBuffered(s))}),c){const e=this.getFragmentAppendProgress(a),s=t[r];if(s&&u){const t=Oc(_i.timeRangesToArray(s),a);e.progressed||(e.progressed=t-Oc(u,a)>nn);const i=f&&xc(t,a);e.fullyBuffered[r]=(void 0===e.fullyBuffered[r]||e.fullyBuffered[r])&&i}}this.hls.trigger(Is.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:n,timeRanges:t})},onError:e=>{var t;this.clearBufferAppendTimeoutId(this.tracks[r]);const s=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(s&&!this._quotaEvictionPending[r]){const e=this.getBackBufferEvictionTarget(r,i.byteLength,a.type);if(e>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${e.toFixed(3)}s and retrying`);const t=this.getFlushOp(r,0,e),s=this.getClearEvictionPendingOp(r);return void this.insertNext([t,I,s],r)}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}c&&(this.getFragmentAppendProgress(a).errored=!0);const h={type:Ts.MEDIA_ERROR,parent:n,details:ws.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},d=null==(t=this.media)?void 0:t.error;if(e.name!==rn||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var u;s&&(h.details=ws.BUFFER_FULL_ERROR);const t=++this.appendErrors[r],i=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${t}/${i+1} times to append segment in "${r}" sourceBuffer with error: ${e.message}`),t>=i&&(h.fatal=!s);const n=null==(u=this.mediaSource)?void 0:u.readyState;("ended"===n||"closed"===n||d)&&(this.warn(`MediaSource readyState "${n}" during SourceBuffer${Mc(h.fatal,d)}`),h.details=ws.MEDIA_SOURCE_REQUIRES_RESET)}else h.errorAction=Vh(!0);this.appendError=h,this.hls.trigger(Is.ERROR,h),s&&this.hls&&this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${o?" p: "+o.index:""} of ${n} playlist ${a.level} cc: ${m} offset: ${h} bytes: ${i.byteLength}`),this.append(I,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var i;const r=null==(i=this.tracks[e])?void 0:i.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${r?Vd(_i.getBuffered(r)):"(detached)"}`),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s&&"audio"!==s||this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)})}onFragParsed(e,t){const{frag:s,part:i,chunkMeta:r}=t,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[Ds.AUDIOVIDEO]?n.push("audiovideo"):(a[Ds.AUDIO]&&n.push("audio"),a[Ds.VIDEO]&&n.push("video")),0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,n),this.hls&&(this.hls.trigger(Is.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type,chunkMeta:r}),!i&&s.gap&&t.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${t.retry}`))},n).catch(e=>{this.warn(`Fragment buffered callback ${e.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,t.frag,t.previousFrag);const o=t.frag.elementaryStreams,{appendErrors:l}=this,h=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(o).forEach(e=>{o[e]&&(l[e]=0,e===h&&(this.appendError=void 0),"audio"===e||"video"===e?(l.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;"open"===(null==e?void 0:e.readyState)?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Is.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(Is.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ws.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;Ss(e)&&e!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,t):0}getFragmentAppendProgress(e){var t;const s=_c(e);let i=this.fragmentAppendProgress[s];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(e,t,s,i){if(t||!Wo(e)||e.gap||s.iframe||s.partial)return;const r=_c(e),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const a=(null==n?void 0:n.stats)===e.stats?n:void 0;if(null!=a&&a.errored)return;const o=i.length>0&&i.every(e=>!0===(null==a?void 0:a.fullyBuffered[e]));if(null!=a&&a.progressed||o)return void delete this.appendsWithoutProgress[r];if(!a&&0===i.length)return;const l=(this.appendsWithoutProgress[r]||0)+1,h=this.hls;l>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=l,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${l} time${l>1?"s":""} without buffered range growth`),h.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:l,error:new Error(`Fragment append did not increase buffered coverage (${l})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,s,i){const{hls:r,details:n,media:a}=this;if(!a||null===n)return;if(!this.sourceBufferCount)return;const o=r.config,l=a.currentTime,h=n.levelTargetDuration;t=n.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;let d=-1/0;if(Ss(t)&&t>=0){const e=Math.max(t,h);d=Math.floor(l/h)*h-e}if(s){const e=this.getLoopBackBufferFlushEnd(s,null!=i?i:null);e>0&&(d=Math.max(d,e))}if(d>0&&this.flushBackBuffer(l,h,d),Ss(e)&&e>0){const t=Math.max(o.maxBufferLength,e),s=Math.max(t,h),i=Math.floor(l/h)*h+s;this.flushFrontBuffer(l,h,i)}}getLoopBackBufferFlushEnd(e,t){var s;const{media:i}=this;if(!1===(null==(s=this.hls)?void 0:s.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;const{video:r,audiovideo:n}=e.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(e)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(e){const{audio:t,video:s,audiovideo:i}=e.elementaryStreams;let r=e.start;return i?r=Math.min(r,i.startDTS):(t&&(r=Math.min(r,t.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([e,t])=>{if(t){const a=_i.getBuffered(t);if(a.length>0&&s>a.start(0)){var i,r,n;this.hls.trigger(Is.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(Is.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([t,i])=>{if(i){const r=_i.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return Ss(r)?{duration:r}:null;const n=this.media.duration;return i>(Ss(s.duration)?s.duration:0)&&i>n||!Ss(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==e&&(Ss(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${gi(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(Is.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${gi(a)}`);try{const e=s.addSourceBuffer(r),i=Dc(n),o=[n,e];t[i]=o,a.buffer=e}catch(e){var i;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&ch(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)dh(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=vh(i,e.levelCodec);return r?"audio"===t.slice(0,5)?ph(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const s=t.removedRanges;null!=s&&s.length&&(this.log(`${e} buffer removed ${Vd(s)}`),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:s.start(0),end:s.end(s.length-1)}))})}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);if(i){if(i.onComplete(),null==(s=this.tracks[e])||null==(s=s.buffer)?void 0:s.updating)return this.log(`${e} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}onSBUpdateError(e,t){var s;const i=null==(s=this.mediaSource)?void 0:s.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,t),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const o=Ss(i.duration)?i.duration:1/0,l=Ss(r.duration)?r.duration:1/0,h=Math.max(0,t);var d;if(h>=l)return null==(d=this.currentOp(e))||d.onComplete(),void this.shiftAndExecuteNext(e);const c=Math.min(s,o,l);if(!(c>h)||n.ending&&!n.ended)throw new Error(`Cannot remove ${c<=h?`invalid range (${h} >= ${c}) `:""}from the ${e} SourceBuffer${n.ending?" while track ending":""}`);n.ended=!1,this.log(`Removing [${h},${c}] from the ${e} SourceBuffer`),a.remove(h,c)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new an(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const e=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,i,e),e)}i.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch(t){this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=10;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(null===this.media)return s;const i=_i.bufferInfo(e,this.media.currentTime,0);return i.len?(s=Math.max(1e3*i.len,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=2===t.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(e=>this.appendBlocker(e));return Promise.all(i).then(t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;!s||s.updating||"audio"===e&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),jd(r,t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(e=>{Kd(s,e.event,e.listener)}),t.listeners.length=0)}},ln=class e{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:e}=this;e&&(e.on(Is.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(Is.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){const s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping()}onLevelsUpdated(e,{levels:t}){(this.timer||this.observer)&&Ss(this.autoLevelCapping)?this.detectPlayerSize():void 0===this.observer&&void 0===this.timer&&t.length>1&&t.some(e=>!!e.videoCodec)&&this.startCapping()}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const e=this.hls.levels;if(e.length>1){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const s=this.hls.levels;if(!s.length)return-1;const i=s.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(e=>{var t;const s=null==(t=e[0])?void 0:t.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;const i=(e,t)=>!t||e.width!==t.width||e.height!==t.height;let r=e.length-1;const n=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=n||s.height>=n)&&i(s,e[t+1])){r=t;break}}return r}},hn=class e{constructor(t,s){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=s}},dn="Dict",cn="Bare Item",un="Boolean",fn="Byte Sequence",gn="Decimal",mn="Integer",pn="String",vn=/[\x00-\x1f\x7f]+/,yn=class{constructor(e){this.description=e}},Sn="Token",En="Key",bn=["url"],Tn=["version","eventTargets","sid","transmissionMode"],wn=["customData","headers"],In=e=>e instanceof hn?new hn(Math.round(e.value),e.params):Math.round(e),An=(e,t)=>Array.isArray(e)?e.map(e=>An(e,t)):e instanceof hn&&"string"==typeof e.value?new hn(An(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let s;try{s=new URL(e)}catch(t){return e}const i=new URL(t);if(s.origin!==i.origin)return e;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let e=0;e<a&&r[e]===n[e];e++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(e,function(e){const t="string"==typeof e?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}(t.baseUrl))),1===t.version?encodeURIComponent(e):e),kn=e=>e instanceof hn?new hn(100*Math.round(e.value/100),e.params):100*Math.round(e/100),Cn={br:Ln=e=>Array.isArray(e)?e.map(In):In(e),d:Ln,bl:Rn=e=>Array.isArray(e)?e.map(kn):kn(e),dl:Rn,mtp:Rn,nor:(e,t)=>{let s=e;return t.version>=2&&(e instanceof hn&&"string"==typeof e.value?s=new hn([e]):"string"==typeof e&&(s=[e])),An(s,t)},rtp:Rn,tb:Ln},Pn=2,Dn="pr",Mn="b",xn={BITRATE_CHANGE:"bc",ERROR:"e",RESPONSE_RECEIVED:_n="rr",CUSTOM_EVENT:On="ce"},Fn=new Map([["ps","sta"],[Dn,"pr"],["c","cid"],[Mn,"bg"],["bc","br"]]),Bn="event",Un="request",Nn=["cen","e","h","ts"],$n=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Gn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,Hn=new Set($n),Wn=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],qn=new Set(Wn),jn=new Set(Nn),Kn=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Vn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Yn=new Set(Vn),zn=new Set(["ot","sf","st","e","sta"]),Qn={[Bn]:Yc,[Un]:Kc},ta={REQUEST:Jn="CMCD-Request"},sa={ab:Xn="CMCD-Object",br:Xn,d:Xn,lab:Xn,lb:Xn,ot:Xn,tab:Xn,tb:Xn,tpb:Xn,bl:Jn,cs:Jn,dfa:Jn,dl:Jn,ltc:Jn,mtp:Jn,nor:Jn,nrr:Jn,pb:Jn,sn:Jn,sta:Jn,su:Jn,tbl:Jn,cid:Zn="CMCD-Session",msd:Zn,sf:Zn,sid:Zn,st:Zn,v:Zn,bg:ea="CMCD-Status",bs:ea,bsa:ea,bsd:ea,bsda:ea,cdn:ea,ec:ea,nr:ea,pr:ea,pt:ea,rtp:ea},ia="CMCD",ra=[...Vn,...$n,...Wn,...Nn].filter((e,t,s)=>s.indexOf(e)===t),na={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},aa={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},oa="query",la="headers",ha=Object.is,da=e=>e,ca=Array.from(Fn,([e,t])=>"br"===t?{event:e,field:t,equal:(e,t)=>void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++){const i=e[s],r=t[s];if(i===r)continue;if("number"==typeof i||"number"==typeof r)return!1;if(i.value!==r.value)return!1;const n=i.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(e,t),snapshot:e=>e.slice()}:{event:e,field:t,equal:ha,snapshot:da}),ua=new Map(ca.map(e=>[e.event,e])),fa=class{constructor(e,t=su){var s;this.timeOrigin=performance.timeOrigin||(null==(s=performance.timing)?void 0:s.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){const{version:t=Pn,eventTargets:s=[],sid:i=gl(),transmissionMode:r=oa}=e;return Xo(Xo({},Jo(e,Tn)),{},{version:t,transmissionMode:r,sid:i,eventTargets:s.reduce((e,t)=>{var s,i,r;return null!=t&&t.url&&null!=(s=t.events)&&s.length&&e.push({version:t.version||Pn,enabledKeys:(null==(i=t.enabledKeys)?void 0:i.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(r=t.interval)?r:30,batchSize:t.batchSize||1}),e},[])})}(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(const e of this.config.eventTargets)this.eventTargets.set(e,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),0===t.interval||!t.events.includes("t"))return;const s=()=>{this.recordTargetEvent(e,t,"t"),this.processEventTargets()};e.intervalId=setInterval(s,1e3*t.interval),s()})}stop(e=!1){e&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=Xo(Xo(Xo({},this.data),e),{},{msd:void 0});for(const t of ca)t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(e,t={}){const s=ua.get(e);if(s){const e=s.field,i=t[e];void 0!==i&&zo(this.data,{[e]:i});const r=this.data[e];if(void 0===r)return;if(s.equal(r,this.lastEmitted[e]))return;zo(this.lastEmitted,{[e]:s.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,s,i={}){var r;if(!t.events.includes(s))return;const n=Xo(Xo(Xo({},this.data),i),{},{e:s,ts:null!=(r=i.ts)?r:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(n.msd=this.msd,e.msdSent=!0),e.queue.push(n)}recordResponseReceived(e,t={}){var s,i,r;const{request:n}=e,a=null!=(s=t.url)?s:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(ia);const l={url:o.toString(),rc:e.status},h=e.resourceTiming;h&&(null!=h.startTime&&(l.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(l.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(l.ttlb=Math.round(h.duration)));const d=null!=(i=null==(r=n.customData)?void 0:r.cmcd)?i:{};this.recordEvent(_n,Xo(Xo(Xo({},d),l),t))}applyRequestReport(e){var t;return null!=(t=this.createRequestReport(e))?t:e}isRequestReportingEnabled(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}createRequestReport(e,t){var s;const{customData:i={},headers:r={}}=e,n=Xo(Xo({},Jo(e,wn)),{},{headers:Xo({},r),customData:Xo(Xo({},i),{},{cmcd:{}})});if(null==(s=this.config.enabledKeys)||!s.length||!n.url)return n;const a=new URL(n.url),o=Xo(Xo(Xo({},this.data),t),{},{sn:this.requestTarget.sn++}),l=tu(Un,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const h=n.customData.cmcd=Zc(o,l);switch(this.config.transmissionMode){case oa:const e=eu(h);e&&(a.searchParams.set(ia,e),n.url=a.toString());break;case la:zo(n.headers,function(e,t){const s={},i=function(e,t){const s={};if(!e)return s;const i=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var s;return null==(s=n[t])||s.forEach(s=>e[s]=t),e},{})):{};var n;for(const t of i){var a;const i=sa[t]||r[t]||ta.REQUEST;(null!=(a=s[i])?a:s[i]={})[t]=e[t]}return s}(e,t);for(const[e,t]of Object.entries(i)){const i=qc(t,{whitespace:!1});i&&(s[e]=i)}return s}(h,l.customHeaderMap))}return n}processEventTargets(e=!1){let t=!1;this.eventTargets.forEach((s,i)=>{const{queue:r}=s;if(!r.length)return;if(r.length<i.batchSize&&!e)return;const n=e?r.length:i.batchSize,a=r.splice(0,n);this.sendEventReport(i,a).catch(()=>{s.queue.unshift(...a)}),t||(t=r.length>0)}),t&&this.processEventTargets()}async sendEventReport(e,t){const s=tu(Bn,e),{status:i}=await this.requester({url:e.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:t.map(e=>function(e,t={}){return e?eu(Zc(e,t)):""}(e,s)).join("\n")+"\n"});if(410===i)this.disposeEventTarget(e);else if(429===i||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){const t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}resetSession(){this.eventTargets.forEach(e=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},ga={HLS:"h"},ma={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"},new Set(Vn),new Set(ra),pa=["includeKeys"],va=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(aa.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(aa.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(aa.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(aa.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(aa.SEEKING)},this.onSeeked=()=>{var e;this.initialized&&null!=(e=this.media)&&e.paused&&this.setPlayerState(aa.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=e=>{try{this.apply(e,{ot:na.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:n,part:a}=e,o=this.hls.levels[n.level],l=this.getObjectType(n,o),h={d:1e3*(a||n).duration,ot:l};if(l===na.VIDEO||l===na.AUDIO||l===na.MUXED||null==l&&("main"===n.type||"audio"===n.type)){var t;const e=o.bitrate/1e3;h.br=[e];const{cmcd:i}=this.config,r=null!=(t=null==i?void 0:i.rtpSafetyFactor)?t:5;if(h.rtp=100*Math.round(e*r/100),l===na.MUXED||null==l&&"main"===n.type){const e=this.getTopBandwidth()/1e3;Ss(e)&&(h.tb=[e]);const t=this.getLowestBandwidth()/1e3;Ss(t)&&(h.lb=[t])}const a=this.getBufferLength(n);if(Ss(a)){var s;h.bl=[a];const e=(null==(s=this.media)?void 0:s.playbackRate)||1;h.dl=100*Math.round(a/e/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const d=this.hls.maxAutoLevel;if(d>=0){const e=this.hls.levels[d];e&&(h.tpb=[e.bitrate/1e3])}}const d=a?this.getNextPart(a):this.getNextFrag(n);null!=d&&d.url&&d.url!==n.url&&(d.byteRange.length>0?h.nor=[(i=d.url,r={r:`${d.byteRange[0]}-${d.byteRange[1]}`},new hn(i,r))]:h.nor=[d.url]),this.apply(e,h)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}var i,r},this.recordFragmentResponse=(e,t,s)=>{var i;const{cmcd:r}=this.config,n=null==r||null==(i=r.eventTargets)?void 0:i.some(e=>{var t;return null==(t=e.events)?void 0:t.includes(xn.RESPONSE_RECEIVED)});if(this.reporter&&s.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:s.loading.start,responseStart:s.loading.first,duration:s.loading.end-s.loading.start,encodedBodySize:s.total}})}catch(e){this.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:s}=this.config;if(null==s)return;const i=s.version||1;if(this.reporter=new fa({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:!0===s.useHeaders?la:oa,enabledKeys:null!=(e=s.includeKeys)?e:[...i>=Pn?ra:Vn],eventTargets:(null!=(t=s.eventTargets)?t:[]).map(e=>{let{includeKeys:t}=e;return Xo(Xo({},Jo(e,pa)),{},{enabledKeys:null!=t?t:ra})})},s.loader),this.reporter.update({sf:ga.HLS,sta:this.playerState}),s.reporterCallback){const e=this.reporter,t={updateCustomData:t=>{iu(t)&&e.update(t)},recordCustomEvent:(t,s={})=>{iu(s)&&e.recordEvent(xn.CUSTOM_EVENT,Xo({cen:t},s))}};s.reporterCallback(t)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Is.MEDIA_ENDED,this.onMediaEnded,this),e.on(Is.ERROR,this.onError,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(Is.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(Is.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Is.MEDIA_ENDED,this.onMediaEnded,this),e.off(Is.ERROR,this.onError,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(Is.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(Is.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const s=this.media=t.media;this.setPlayerState(this.media.autoplay?aa.STARTING:aa.PRELOADING),jd(s,"waiting",this.onWaiting),jd(s,"play",this.onPlay),jd(s,"playing",this.onPlaying),jd(s,"pause",this.onPause),jd(s,"seeking",this.onSeeking),jd(s,"seeked",this.onSeeked),jd(s,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(Kd(e,"waiting",this.onWaiting),Kd(e,"play",this.onPlay),Kd(e,"playing",this.onPlaying),Kd(e,"pause",this.onPause),Kd(e,"seeking",this.onSeeking),Kd(e,"seeked",this.onSeeked),Kd(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(aa.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(aa.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(aa.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(xn.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;const i={br:[t.bitrate/1e3]},r=null==(s=t.details)?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,t)),this.reporter.recordEvent(xn.BITRATE_CHANGE,i)}onLevelSwitched(e,t){const s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?ma.LOW_LATENCY:ma.LIVE:ma.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(s=this.media)?void 0:s.playbackRate,st:this.getStreamType()});const i=t.ot===na.INIT||t.ot===na.VIDEO||t.ot===na.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=i;for(let t=r.length-1;t>=0;t--){const i=r[t];if(i.index===s&&i.fragment.sn===e)return r[t+1]}}}getObjectType(e,t){const{type:s}=e;if("subtitle"===s)return na.TIMED_TEXT;if("initSegment"===e.sn)return na.INIT;if("audio"===s)return na.AUDIO;if("main"===s){if(e.hasStreams){const t=e.elementaryStreams;if(t.audiovideo)return na.MUXED;if(t.video)return na.VIDEO;if(t.audio)return na.AUDIO}if(t){const{audioCodec:e,videoCodec:s}=t;if(!this.hls.audioTracks.length){if(e&&s)return na.MUXED;if(e)return na.AUDIO}if(s)return na.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(t=>{t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(t=>{t.bitrate<e&&(e=t.bitrate)}),Ss(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);const s=e||t;return s?1e3*s.len:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const s=this.getEventBufferLength();Ss(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=this.recordFragmentResponse,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e);const{onSuccess:n}=r;this.loader.load(e,i,Xo(Xo({},r),{},{onSuccess:(t,i,r,a)=>{n(t,i,r,a),s(e.url,t,i)}}))}}}},ya=class extends Bs{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===vi.SendAlternateToPenaltyBox&&s.flags&yi.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r,s.resolved||t.details===ws.BUFFER_APPEND_ERROR&&!t.fatal||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${gi(i)} penalized: ${gi(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(e=>{i-s[e]>3e5&&delete s[e]});for(let i=0;i<e.length;i++){const r=e[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ud(t),this.hls.trigger(Is.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===Cs.AUDIO_TRACK&&i[s].hasAudioGroup(e)||t===Cs.SUBTITLE_TRACK&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new Bi(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=nu(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new ui({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return h});t.push(...o),ru(this.audioTracks,s,a,r),ru(this.subtitleTracks,i,a,r)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);kh(i,"_HLS_pathway",this.pathwayId),kh(i,"_HLS_throughput",""+e)}const r={type:Cs.STEERING_MANIFEST,responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(Is.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},Sa=class 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}},(Ea=class e extends Bs{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,i=`"${e.type}" event: init data type: "${t}"`;if(this.log(i),null!==s){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=md(this.config));const t=e.map(gd).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{let n;const a=fd(r),o=this.activeLevelKeys();if(a===Gi.FAIRPLAY&&"sinf"===t)try{const e=Dl(new Uint8Array(s)),t=Xl(Pl(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${i} Failed to parse sinf: ${e}`)}else if(a===Gi.PLAYREADY)n=pd(new Uint8Array(s));else if(a===Gi.WIDEVINE){const e=nh(s).filter(e=>e.systemId===Wi.WIDEVINE);if(e.length){var l;const t=e[0];n=null!=(l=t.kids)&&l.length?t.kids[0]:null}}let h;if(n){const e=Rl(n);for(let i=0;i<o.length;i++){const r=o[i];if(r.keyId&&(ad(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(e))){r.pssh||(r.scheme=t,r.pssh=new Uint8Array(s),r.keyId=n,Ki.setKeyIdForUri(r.uri,n)),h=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!h){var d,c;if(o.length)return(d=o[0]).scheme||(d.scheme=t),(c=o[0]).pssh||(c.pssh=new Uint8Array(s)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${Rl(n)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return h}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,i=t.map(e=>e.audioCodec).filter(s),r=t.map(e=>e.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,i,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):s(t instanceof Sa?t:new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===qi&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=function(e,t,s,i){let r;switch(e){case Gi.FAIRPLAY:r=["cenc","sinf"];break;case Gi.WIDEVINE:case Gi.PLAYREADY:r=["cenc"];break;case Gi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,s,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,t,s,i)}(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${gi(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(s=>{this.throwIfDestroyed(),this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,i.then(t=>t?this.setMediaKeysServerCertificate(s,e,t):s)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(e,t,s,i){const{mediaKeySessions:r}=this,n=` key-session "${e}" keyId: ${Rl(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let e=0;e<r.length;e++){const t=r[e];if(!t.initialized&&t.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${n}`),t}this.log(`Creating${n}`);const a=t.createSession(),o={keySystem:e,mediaKeys:t,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(o),o}resetMediaKeys(){var e;const t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Rl(t.keyId||[])}\n } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>gd(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const t=gd(e);if(!t)throw new Error(`Unable to find format for key-system "${e}"`);return 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){const t=md(this.config),s=e.map(fd).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(s)}loadClear(e,t,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Wo(e)||!Wo(n)||e.sn<n.sn)||!s&&i==r-1)return this.selectKeySystemFormat(n).then(e=>{if(!this.hls)return;n.setKeyFormat(e);const t=fd(e);return t?this.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=md(this.config);if(e.length)return this.getKeySystemAccess(e)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=au(e,t[s]);if(i)return i}}loadKey(e){const t=e.decryptdata,s=this.getKeyStatus(t);if("internal-error"===s){const i=ou(s,t);return i.data.frag=e,this.error(`${i.message} (${Rl(t.keyId||[])})`),Promise.reject(i)}const i=e.type,r=this.activeKeys,n=r[i];n&&!t.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[i]),r[i]||(r[i]=e);for(let e=this.mediaKeySessions.length;e--;){const s=this.mediaKeySessions[e];if(t.keyId&&"expired"===s.keyStatuses[Rl(t.keyId)])return this.renewKeySession(t,s)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,s){const i=this.getSessionForKey(e,t);return i.catch(e=>this.handleError(e,s)),i.then(t=>e)}getSessionForKey(e,t){const s=this.findContextForKey(e);if(void 0!==s)return Promise.resolve(s);const i=e.uri,r=this.sessionSetupByUri[i];let n;n=void 0===r?this.resolveSessionForKey(e,t):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[i]=n;const a=()=>{this.sessionSetupByUri[i]===n&&delete this.sessionSetupByUri[i]};return n.then(a,a),n}findContextForKey(e){const{mediaKeySessions:t}=this;for(let s=t.length;s--;){const i=t[s];if(au(e,i))return i}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let s=this.mediaKeySessions.length;s--;){const i=this.mediaKeySessions[s];if(au(e,i))return i;const r=this.getUsableKeyPromise(i,e,t);if(r)return r}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,e,t))).then(s=>{this.throwIfDestroyed();const i=e.scheme||"cenc",r=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(s,e,i,r,t)})})}getUsableKeyPromise(e,t,s){const i=e.keyRequests[t.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${function(e){if(e.keyFormat===Hi.FAIRPLAY)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return Rl(e.keyId)}(t)} format: "${t.keyFormat}" URI: ${t.uri})`),lu(i).then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Sa){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Rl(s.keyId||[])})`:""}`),this.hls.trigger(Is.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Is.ERROR,{type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=fd(e.keyFormat),s=t?[t]:md(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=md(this.config)),0===e.length)throw new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${gi({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(e=>e.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(s)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===s.indexOf(e))})}filterInitData(e,t,s,i,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[e.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,s,i,zo({},e,{decryptdata:t,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");t.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return t.pssh=o?new Uint8Array(o):null,n}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(e,t,s,i,r){const n=this.getUsableKeyPromise(e,t,r);if(n)return n;const a=this.filterInitData(e,t,s,i,r);if(a&&(i=a.initData?a.initData:null,s=a.initDataType),null===i)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));const o=t.uri,l=new rr;l.status="initialized",l.requestErrors=[],e.keyRequests[o]=l;const h=s=>{const i=e.mediaKeysSession;if(!i){const e=new Error("invalid state");return l.errored=e,void l.emit("error",e)}const{messageType:r,message:n}=s;l.status=r,this.log(`"${r}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,t,n).catch(t=>{l.errored=t,l.eventNames().length?l.emit("error",t):this.handleError(t),this.removeSession(e)}):"license-release"===r?e.keySystem===Gi.FAIRPLAY&&this.updateKeySession(e,t,dd("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)};return l.onmessage=h,jd(e.mediaKeysSession,"message",h),this.generateRequest(e,t,s,i,r,!1)}generateRequest(e,t,s,i,r,n){if(n){const n=this.filterInitData(e,t,s,i,r);n&&(i=n.initData?n.initData:i,s=n.initDataType)}const a=t.uri,o=e.keyRequests[a],l=Rl(t.keyId||[]),h=e=>{let s;e.startsWith("usable")?(o.resolved=!0,o.emit("resolved")):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?s=ou(e,t):"expired"===e?s=new Error(`key expired (keyId: ${l})`):"released"===e?s=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${l})`),s&&(o.errored=s,o.eventNames().length?o.emit("error",s):this.handleError(s))},d=s=>{if(!e.mediaKeysSession){const e=new Error("invalid state");return o.errored=e,void o.emit("error",e)}const i=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;const r=this.activeLevelKeys();for(let s=0;s<r.length;s++){const a=Rl(r[s].keyId||[]);if("expired"===i[a]){var n;this.log(`Expired key ${gi(i)} in key-session "${null==(n=e.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(t,e).catch(e=>this.handleError(e));break}}let a=i[l];if(a)h(a);else{var d;const s=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(d=e.keyStatusTimeouts)[l]||(d[l]=self.setTimeout(()=>{var i;if(!e.mediaKeysSession)return;const r=this.getKeyStatus(t);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${l} in key-session "${null==(n=e.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),h(r);this.log(`key status for ${l} in key-session "${null==(i=e.mediaKeysSession)?void 0:i.sessionId}" timed out after ${s}ms`),a="internal-error",h(a)},s)),this.log(`No status for keyId ${l} (${gi(i)}).`)}};o.onkeystatuseschange=d,jd(e.mediaKeysSession,"keystatuseschange",d);const c=lu(o);return this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${a} (init data type: ${s} length: ${i.byteLength})`),o.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,i).then(()=>{var t;o.status="generated",this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l} URI: ${a}`)}).catch(e=>{throw this.log(`mediaKeysSession.generateRequest failed: ${e}`),new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>c).catch(t=>{var s;this.log(`mediaKeysSession.generateRequest failed: ${t}`);const i=null==(s=t.data)?void 0:s.details;return i!==ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(t=>"usable"===e.keyStatuses[t])?(o.removeAllListeners(),this.removeSession(e).then(()=>{throw t})):(this.handleError(t),e)}).then(()=>e)}getKeyStatuses(e){const t={},s=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){const e=r;r=i,i=e}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===Gi.PLAYREADY&&16===n.length){const e=Rl(n);t[e]=i,cd(n)}const a=Rl(n);this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${s}"`),t[a]=i}),t}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),i=function(e,t){const{drmSystems:s}=t,i=null==s?void 0:s[e];if(i)return i.serverCertificateUrl}(e,t);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={type:Cs.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{r(e.data)},onError:(t,s,r,o)=>{n(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Xo({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,r)=>{n(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,h)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(e=>{r(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(e=>{throw new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(e,t){const s=Dl(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let s=0,i=r.length;s<i;s++){var n,a;t=r[s];const i=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;i&&o&&e.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return dd(atob(l))}setupLicenseXHR(e,t,s,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,e,t,Xo(Xo({},s),{},{decryptdata:i}),r))).catch(a=>{if(!s.mediaKeysSession)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,Xo(Xo({},s),{},{decryptdata:i}),r)}).then(s=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:s||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,s){return new Promise((i,r)=>{const n=function(e,t){const{drmSystems:s,widevineLicenseUrl:i}=t,r=null==s?void 0:s[e];return r?r.licenseUrl:e===Gi.WIDEVINE&&i?i:void 0}(e.keySystem,this.config);if(!n)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const a=e.keyRequests[t.uri];if(!a)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${n}`);const o=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){a.requestErrors=[];let s=l.response;this.log(`License received ${s instanceof ArrayBuffer?s.byteLength:s}`);const r=this.config.licenseResponseCallback;if(r)try{s=r.call(this.hls,l,n,Xo(Xo({},e),{},{decryptdata:t}))}catch(e){this.error(e)}i(s)}else{const h=o.errorRetry,d=h?h.maxNumRetry:0;if(a.requestErrors.push({status:l.status,message:l.statusText}),a.requestErrors.length>d||l.status>=400&&l.status<500)r(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const n=d-a.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t,s).then(i,r)}}},a.licenseXhr&&a.licenseXhr.readyState!==XMLHttpRequest.DONE&&a.licenseXhr.abort(),a.licenseXhr=l,this.setupLicenseXHR(l,n,e,t,s).then(({xhr:t,licenseChallenge:s})=>{e.keySystem==Gi.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,jd(s,"encrypted",this.onMediaEncrypted),jd(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Kd(e,"encrypted",this.onMediaEncrypted),Kd(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const s=this.mediaResolved;if(s&&s(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ki.clearKeyUriToKeyIdMap();const n=r.length;e.CDMCleanupPromise=Promise.all(r.map(e=>this.removeSession(e)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(s=>{const i=e.keyRequests[s];i.onmessage&&(t.removeEventListener("message",i.onmessage),i.onmessage=void 0),i.onkeystatuseschange&&(t.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.onkeystatuseschange=void 0);const r=i.licenseXhr;r&&(r.readyState!==XMLHttpRequest.DONE&&r.abort(),i.licenseXhr=void 0),e.keyRequests[s]=void 0}),e.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(e=>self.clearTimeout(i[e]));const{drmSystemOptions:r}=this.config,n=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(r)?new Promise((e,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(s)}):Promise.resolve();return n.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).then(()=>t.closed).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}).CDMCleanupPromise=void 0,ba=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(Is.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Is.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},Ta=function(){if(null!=$i&&$i.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function i(e){return s(t,e)}function r(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=t,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",S=50,E="middle",b=50,T="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const i=function(t){return s(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return T},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),wa=class{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}},Ia=class{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}},La=new Ta(0,0,""),Aa="middle"===La.align?"middle":"center",ka=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new wa,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=uu(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const i=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),i}function i(e){du(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const i=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=s(),t.state){case"HEADER":/:/.test(e)?i(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Ta(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{cu(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Ra=/\r\n|\n\r|\n|\r/g,Ca="Missing initPTS for VTT ",Pa=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ss(t)&&Ss(s)&&Ss(i)&&Ss(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*i,t+=36e5*r,t},Da="stpp.ttml.im1t",Ma=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,_a=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oa={left:"start",center:"center",right:"end",start:"start",end:"end"},xa=class extends Zr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){var s;const i=null==(s=this.currentTrack.trackNode)?void 0:s.track.mode;"showing"===i?(e=this.trackId,t=!0):"hidden"===i&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){var i;const s=null==(i=this.tracksInGroup[t].trackNode)?void 0:i.track.mode;if("showing"===s){e=t;break}e<0&&"hidden"===s&&(e=t)}var r;e>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[e].trackNode)?void 0:r.track.mode)),this.setSubtitleTrack(e,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Is.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{e.trackNode||(e.trackNode=Tu(this.media,function(e){return e.forced&&(Zs.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Js))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}(e),e.name,e.lang))});const t=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==t?void 0:t.mode)&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const s=t.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{const t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s;const e=[];if(this.tracks.forEach(t=>{(t.textCodec===Da?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&(t.trackNode.remove(),t.trackNode=void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let s=0;s<e.length;s++)if(e[s]!==this.tracksInGroup[s]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const s=_h(t,e);if(s>-1)r=e[s];else{const e=_h(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(Is.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(i),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if((!s||r.default)&&(s||e)&&(!e||Oh(r,e)))return i}if(e){for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.SUBTITLE_TRACK&&t.context.id===this.trackId&&Uh(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Oh(e,s))return s;const i=_h(e,this.tracksInGroup);if(i>-1){const e=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),e}if(s)return null;{const s=_h(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(Is.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=t.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(e,t=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!Ss(e))return void this.warn(`Invalid subtitle track id: ${e}`);const i=this.currentTrack,r=s[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r)return void(i&&this.hls.trigger(Is.SUBTITLE_TRACK_SWITCH,{id:e}));const n=!!r.details&&!r.details.live;if(r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:h,url:d}=r;this.hls.trigger(Is.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:d});const c=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(c)}},Fa=class extends Pi{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Is.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;jd(s,"playing",this.onMediaPlaying),jd(s,"waiting",this.onMediaWaiting),jd(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Kd(s,"playing",this.onMediaPlaying),Kd(s,"waiting",this.onMediaWaiting),Kd(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Is.MEDIA_ENDED,{stalled:!1})));if(!_i.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const d=_i.bufferInfo(n,e,0),c=this.fragmentTracker;c&&this.hls&&Ru(d,e,c,this.hls);const u=d.nextStart||0;if(a&&c&&this.hls){const t=Lu(this.hls.inFlightFragments,e),s=d.len>2,i=!u||t||u-e>2&&!c.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(d.len>0||u))return;const t=Math.max(u,d.start||0)-e,s=null!=f&&f.live?2*f.targetduration:2,i=ku(e,c);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p&&this.moved)&&this.hls){var S;if("ended"===(null==(S=this.mediaSource)?void 0:S.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Is.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return;if(n.currentTime!==e){const t=e;return e=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${t} > ${e}`)}}const E=_i.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(E,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Is.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=_i.bufferedInfo(_i.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=_i.timeRangesToArray(i),r=_i.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=_i.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=ku(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=_i.bufferInfo(this.media,e,0);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=ku(s,n);if((h||null!=l&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,Ps.MAIN),r=s.getFragAtPos(i,Ps.MAIN);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${gi(e)})`);this.warn(i.message),t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:s,hls:i}=this,r=null==i?void 0:i.config;if(!s||!t||!r)return 0;const n=s.currentTime,a=_i.bufferInfo(s,n,0);Ru(a,n,t,i);const o=n<a.start?a.start:a.nextStart;if(o){const h=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(h||d)){if(c>r.maxBufferHole){let s=!1;if(0===n){const e=t.getAppendedFrag(0,Ps.MAIN);e&&o<e.end&&(s=!0)}if(!s&&e){var l;if(null==(l=i.loadLevelObj)||!l.details)return 0;if(Lu(i.inFlightFragments,o))return 0;let s=!1,r=e.end;for(;r<o;){const e=ku(r,t),i=e?e.duration:0;if(!(i>0)){s=!0;break}r+=i}if(s)return 0}}const{nudgeMaxRetry:h,skipBufferHolePadding:d}=r,u=++this.skipRetry>h,f=Math.max(o,n)+d;if(u||(this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,s.currentTime=f),null==e||!e.gap||u){const t=new Error(u?`Playhead still not moving after seeking over buffer hole from ${n} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${f}`),s={type:Ts.MEDIA_ERROR,details:ws.BUFFER_SEEK_OVER_HOLE,fatal:u,error:t,reason:t.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?s.part=e:s.frag=e),i.trigger(Is.ERROR,s)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}},Ba=(()=>{const e=Cu();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Ua=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Is.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return Tu(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Cu();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===or.emsg&&!s||!i)continue;const a=Il(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>Ba&&(l=Ba),l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!Ll(s)){this.updateId3CueEnds(o,t);const e=Pu(n,o,l,s,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.track.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===Ba&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===or.audioId3&&o:"video"===i?e=>e.type===or.emsg&&a:e=>e.type===or.audioId3&&o||e.type===or.emsg&&a,Iu(r.track,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Cu();if(s&&i&&!n){const{fragmentStart:t,fragmentEnd:i}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=i):a&&(r=this.assetCue=Pu(a,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.track.cues)&&c.length){const e=Object.keys(d).filter(e=>-1===h.indexOf(e));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach(e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(t)}catch(e){}}})}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&Ss(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=Ba;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const e=h.reduce((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(s.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!rd(l))continue;const h=o[l];if(h)!c||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=u):h.endTime=u;else if(a){let e=s.attr[l];nd(l)&&(e=Cl(e));const r=Pu(a,i,u,{key:l,data:e},or.dateRange);r&&(r.id=t,this.id3Track.track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}d[t]={cues:o,dateRange:s,durationKnown:c}}}}},Na={DISABLED:0,SWITCHING:1,SWITCHED:2},$a=class extends er{constructor(e,t,s){super(e,t,s,"stream-controller",Ps.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Na.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!Ss(t))return;if(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,Ps.MAIN,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${t} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Is.BUFFER_CREATED,this.onBufferCreated,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Is.BUFFER_CREATED,this.onBufferCreated,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=Zi.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Zi.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Zi.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=Zi.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Zi.IDLE;break}break}case Zi.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Zi.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={type:this.targetBufferType()};return this.hls.trigger(Is.BUFFER_EOS,e),void(this.state=Zi.ENDED)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===Zi.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=Zi.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=void 0);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&Wo(u)&&this.fragmentTracker.getState(u)!==Ei.OK){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=void 0);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Ds.AUDIO:Ds.VIDEO,t=(e===Ds.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}u=this.getNextFragmentLoopLoading(u,l,a,Ps.MAIN,d)}u&&(this.exceedsMaxBuffer(a,d,u)||this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ei.NOT_LOADED||i===Ei.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){var e;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Na.DISABLED)&&(((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"))}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Na.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const t=this.fragPlaying;if(t){const s=t.level;this.hls.trigger(Is.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==s&&this.hls.trigger(Is.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio!==Na.SWITCHED||this.audioOnly?null:"video"}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;jd(s,"playing",this.onMediaPlaying),jd(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Kd(s,"playing",this.onMediaPlaying),Kd(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Is.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Na.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=Du();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==Zi.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Zi.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==Zi.FRAG_LOADING&&this.state!==Zi.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(Is.LEVEL_UPDATED,{details:a,level:n}),this.state===Zi.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Zi.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.initPTS.some((e,t)=>{if(t>=a.startCC)return!0;delete this.initPTS[t]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i}`),"buffered"===this.config.liveSyncMode){var l;const e=_i.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=_i.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Xr(this.hls,Ps.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,{decryptRange:m,byteRange:p}=Jh(s,i,this.iframesOnly),v=new Di(s.level,s.sn,s.stats.chunkCount,p?p.end-p.start:r.byteLength,f,g,s.duration,this.iframesOnly,m),y=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,v,y)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==Na.DISABLED;if(Bh(t.url,s))this.altAudio=Na.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=Na.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(Is.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Is.AUDIO_TRACK_SWITCHED,t)}),void s.trigger(Is.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(Is.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Bh(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?Na.SWITCHED:Na.DISABLED,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===Ps.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Zi.PARSED&&(this.state=Zi.IDLE));let e=!1;if(Wo(s)&&(e=!!s.gap&&!s.tagList.some(e=>"GAP"===e[0])),this.fragBufferedComplete(s,i),e){var n;s.stats.retry++;const e=null==(n=this.levels)?void 0:n[s.level];e&&e.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&_i.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=Zi.ERROR;else switch(t.details){case ws.FRAG_GAP:case ws.FRAG_PARSING_ERROR:case ws.FRAG_DECRYPT_ERROR:case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ps.MAIN,t);break;case ws.LEVEL_LOAD_ERROR:case ws.LEVEL_LOAD_TIMEOUT:case ws.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Zi.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==Cs.LEVEL||(this.state=Zi.IDLE);break;case ws.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ws.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ws.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Zi.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ds.AUDIO||!this.altAudio){const e=(t===Ds.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=_i.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=Zi.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(Is.FRAG_LOADED,e),i.bitrateTest=!1}).catch(t=>{this.state!==Zi.STOPPED&&this.state!==Zi.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Zi.PARSING,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger(Is.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Ss(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e};const r=this.initPTS.slice(0);s.trigger(Is.INIT_PTS_FOUND,{timestampOffsets:r,frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Ds.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Ds.AUDIO,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(Is.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger(Is.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Wo(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==Zi.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=vh(r.codec,s);if("mp4a"===i&&(i="mp4a.40.5"),this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&!function(){if(void 0===ti){const e=Js.match(/Firefox\/(\d+)/i);ti=e?parseInt(e[1]):0}return ti}()&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&/Android/.test(Js)&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=Ps.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=Ps.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Is.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(Is.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,Ps.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Zi.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return Ss(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Ss(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?$h(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ga=class extends $a{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const e=this.media;null!=e&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:s}=t,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:this.state=Zi.IDLE}this.state===Zi.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(Is.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){const t=this.media;if(t){var s;const i=null==(s=this.getLevelDetails())?void 0:s.edge,r=void 0!==i?i:t.duration;if(e>=r&&(e=r-.01),_i.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,Ps.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const e=s.shift();if(!e.data){this.cached=s.filter(e=>!!e.data),this.cachedSize=s.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}this.cachedSize-=e.data.byteLength,e.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:s,payload:i}=e;this.cacheFragmentData&&!s&&null!=i&&i.byteLength&&!t.data&&Wo(t)&&this.cacheSet(t,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i!==Ei.NOT_LOADED&&i!==Ei.PARTIAL||!this.canReplayCached(e)?super.loadFragment(e,t,s):this.replayCachedFragment(e)}canReplayCached(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;const s=e.decryptdata;return"identity"!==(null==s?void 0:s.keyFormat)||!!s.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const s=e.stats=new Rs;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=Zi.FRAG_LOADING;const i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(Is.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=Zi.STOPPED,null!=s&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Vd(_i.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,t){if(t){const t=this.media;if(t){const s=_i.bufferInfo(t,e,0),i=s.len?s.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,Ps.MAIN),this.flushMainBuffer(i,1/0))}this.hls.once(Is.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(Is.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||i||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,Ps.MAIN);return!(null==t||!t.endList)}},Ha=class extends Ga{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const s=null==(t=this._img)?void 0:t.src;s&&self.URL.revokeObjectURL(s),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:this.state=Zi.IDLE}if(this.state===Zi.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Zi.IDLE){const t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{const s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){const i=e.data;i||this.fragmentTracker.removeFragment(e);const r=this._img;if(r&&i){const n=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const i=this.hls.levels[e.level];null!=i&&i.fragmentError&&(i.fragmentError=0,e.stats.retry=0);const r=self.performance.now(),n=t?t.stats:e.stats;n.buffering.end=e.stats.buffering.end=r,this.hls.trigger(Is.FRAG_BUFFERED,{frag:e,part:t,stats:n,id:e.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",e,t,s)};const a=r.src;a&&self.URL.revokeObjectURL(a);const o=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(o)}else this.state=Zi.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,i){if(!this.hls)return;const r=new Error(e);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,s,i){super.bufferFragmentData(e,t,s,i,!0);const r=Gl(new Uint8Array(e.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",t,s,i);const n=t;this.cacheSet(n,r[0]),this.updateImage(n,s,i)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){const e=this.getAppendedFrag(t);if(e&&!qo(e,this.fragPlaying))return this.fragPlaying=e,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},Wa={seekOnAppend:!0},Ka=class extends Bs{constructor(e,t){var s;super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,qa||(s=t,qa=class extends s{constructor(e,t,s,i){e.streamController||(e.streamController=Ga),super(e),this._url=t,this.streamController.setInitPts(s),this.streamController.initDetails=i}loadSource(){}loadMediaAt(e,t=Wa){if(e<0)return;const s=Xo(Xo({},Wa),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,s)}}),ja||(ja=function(e){return class extends e{constructor(e,t,s,i){e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=Ha),e.capLevelController=void 0,e.bufferController=void 0,super(e,t,s,i)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error("Image I-Frame player does not accept HTMLMediaElements")}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}(qa)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Is.MANIFEST_LOADING,this.clearAsset,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MANIFEST_LOADING,this.clearAsset,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var s;const i=null==(s=this.hls)?void 0:s.pathwayPriority;t.length&&i&&this.iframeInstances.forEach(e=>{e.pathwayPriority=i})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===Ps.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;const i=this.hls;i&&i.hasEnoughToStart&&((null==(s=i.mainForwardBufferInfo)?void 0:s.len)||0)>10&&this.iframeInstances.forEach(e=>{var t;e.loadingEnabled||e.startLoad((null==(t=this.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}createIFramePlayer(e){var t;return this.createInstance(qa,null==(t=this.hls)?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const s=null==(t=this.hls)?void 0:t.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(ja,s,e,"image-")}createInstance(e,t,s,i){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:a,latestLevelDetails:o,loadLevelObj:l,loadLevel:h,bandwidthEstimate:d,sessionId:c}=r,{stats:u,variableList:f}=this;if(null==t||!t.length||!u||!n)return null;const g=`${i||""}iframe-player-${this.instanceCounter++}`,m=r.levels,p=l||m[h],v=Nh(p,a.videoPreference),y=(null==p?void 0:p.pathwayId)||".",S=new e(Xo(Xo({},a),{},{loggerId:g,primarySessionId:c,videoPreference:v,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),n,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(S),S.trigger(Is.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:u,networkDetails:null,url:n,variableList:f}),S}},Va=.025,Ya=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({}),za=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return!(e<=0||isNaN(s))&&(0===s||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>s)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return xu(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-xu(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Ss(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return xu(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Va))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ya.Range:Ya.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}},Qa=class{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Is.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(Is.LEVEL_LOADED,n),r.once(Is.AUDIO_TRACK_LOADED,n),r.once(Is.SUBTITLE_TRACK_LOADED,n),r.on(Is.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(Is.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(Is.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Fu(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if(null!=(s=this.hls)&&s.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),n=_i.bufferInfo(e,r,.02);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=_i.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;null==(i=this.hls)||i.on(e,t)}once(e,t,s){var i;null==(i=this.hls)||i.once(e,t)}off(e,t,s){var i;null==(i=this.hls)||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Uu(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Xa=.033,Ja=class extends Bs{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];t&&"primary"!==t&&(r=r[t]);const n=r.start,a=s[i].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(e===n||e>n&&e<o)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const e=s[i].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if((null==(s=t[i].event)?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let e=0;e<i;e++){const r=s[e];if(!r.error){const s=r.timelineStart;if(t===s||t>s&&(t<s+(r.duration||0)||e===i-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,s=e[e.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,s=0){const i=e.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},t),o=Object.keys(r),l=n?n.filter(e=>-1===o.indexOf(e.identifier)):[];a.length&&a.sort((e,t)=>{const s=e.cue.pre,i=e.cue.post,r=t.cue.pre,n=t.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=e.startTime,i=t.startTime;if(s!==i)return s-i}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,l.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,l,s)}updateSchedule(e,t=[],s=0,i=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(r,e,s);(i||t.length||(null==n?void 0:n.length)!==a.length||a.some((e,t)=>Math.abs(e.playout.start-n[t].playout.start)>.005||Math.abs(e.playout.end-n[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new za(o,t),this.eventMap[a]=e,!1===s&&(e.appendInPlace=s)),i.push(e)}}return i}parseSchedule(e,t,s=0){const i=[],r=t.main.details,n=r.live?1/0:r.edge;let a=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let l=0,h=0;if(e.forEach((t,o)=>{const d=t.cue.pre,c=t.cue.post,u=e[o-1]||null,f=t.appendInPlace,g=c?n:t.startOffset,m=t.duration,p=t.timelineOccupancy===Ya.Range?m:0,v=d&&r.live?s+(t.resumeOffset||0):0,y=v||t.resumptionOffset,S=(null==u?void 0:u.startTime)===g,E=g+t.cumulativeDuration;let b=f?E+m:g+y;if(d||!c&&g<=0){const e=h;h+=p,t.timelineStart=E;const s=a;a+=m,i.push({event:t,start:E,end:b,playout:{start:s,end:a},integrated:{start:e,end:h}})}else{if(!(g<=n))return;{if(!S){const s=g-l;if(s>Xa){const r=l,n=h;h+=s;const d=a;a+=s;const c={previousEvent:e[o-1]||null,nextEvent:t,start:r,end:r+s,playout:{start:d,end:a},integrated:{start:n,end:h}};i.push(c)}else s>0&&u&&(u.cumulativeDuration+=s,i[i.length-1].end=g)}c&&(b=E),t.timelineStart=E;const s=h;h+=p;const r=a;a+=m,i.push({event:t,start:E,end:b,playout:{start:r,end:a},integrated:{start:s,end:h}})}}const T=v||t.resumeTime;l=c||T>n?n:!d&&b&&t.appendInPlaceStarted&&T-b>Xa?b:T}),l<n){var o;const e=l,t=h,s=n-l;h+=s;const r=a;a+=s,i.push({previousEvent:(null==(o=i[i.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:e+s,playout:{start:r,end:a},integrated:{start:t,end:h}})}this.setDurations(n,a,h)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:n,playout:{start:e,end:n},integrated:{start:e,end:n}}),this.setDurations(n,n,n)}return i}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,d=l?0:h?i:a.startTime;this.updateAssetDurations(a),n===d?a.cumulativeDuration=r:(r=0,n=d),!h&&a.snapOptions.in&&(a.resumeAnchor=$h(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<e.length&&e[o+1].startTime-e[o].resumeTime<Xa&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const c=Ss(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Va?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(i=>{const r=t[i].details,n=r.edge;if(s>=n)return this.log(`"${e.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=$h(null,r.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Va+o||Math.abs(a.end-s)<Va+o||(this.log(`"${e.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),0))})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error),s+=a.error?0:a.duration||0}e.duration=i&&!r?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}},Za=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Fu(s,this.hls.sessionId,e.baseUrl)}catch(t){const i=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(Is.ERROR,i)}t&&"data:"!==i.protocol&&kh(i,"_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={type:Cs.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,s,i,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,ws.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(Is.ERROR,t)}e.assetListResponse=n,this.hls.trigger(Is.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,s,i,r)=>{const n=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,r,i);this.hls.trigger(Is.ERROR,n)},onTimeout:(t,s,i)=>{const r=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,i);this.hls.trigger(Is.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(Is.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:Ts.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}},eo=class extends Bs{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=e,this.bufferedPos=e;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),s&&e<i.start||e>=i.end){var r;const t=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const t=i.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&e<a||e>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;s&&e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>Nu(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,d=null;i&&(h=this.updateItem(i,this.timelinePos),this.itemsMatch(i,h)?this.playingItem=h:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const c=this.bufferingItem;if(c&&(d=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,d)?this.bufferingItem=d:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,s=e.timelineOffset-t;if(s)try{e.timelineOffset=t}catch(i){Math.abs(s)>Va&&this.warn(`${i} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(Is.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.indexOf(i.event.identifier)>-1)return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(h,i),c&&d!==h&&this.trimInPlace(d,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Za(e),this.schedule=new Ja(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Is.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Is.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Is.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Is.MEDIA_ENDED,this.onMediaEnded,this),e.on(Is.ERROR,this.onError,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Is.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Is.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Is.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Is.MEDIA_ENDED,this.onMediaEnded,this),e.off(Is.ERROR,this.onError,this),e.off(Is.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Kd(e,"play",this.onPlay),Kd(e,"pause",this.onPause),Kd(e,"seeking",this.onSeeking),Kd(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;jd(s,"seeking",this.onSeeking),jd(s,"timeupdate",this.onTimeupdate),jd(s,"play",this.onPlay),jd(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=t=>t?e.getAssetPlayer(t.identifier):t,i=(t,i,n,a,o)=>{if(t){let l=t[i].start;const h=t.event;if(h){if("playout"===i||h.timelineOccupancy!==Ya.Point){const e=s(n);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else l+=("bufferedPos"===a?r():e[a])-t.start;return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var s,i;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,r),d=null==(a=e.schedule.items)?void 0:a[h],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){const n=s(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=t;if("primary"!==r){const e=t-d[r].start;s=d.start+e}const i=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(i)e.timelinePos=s,e.checkBuffer();else{const e=d.event.assetList,s=t-(d[r]||d).start;for(let t=e.length;t--;){const i=e[t];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=t;break}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=s)}}},o=()=>{const s=e.effectivePlayingItem;if(e.isInterstitial(s))return s;const i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=t(),r=e.bufferingItem;var n;return r&&r===s&&(i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),s=e.effectivePlayingItem;return s&&s===t?i(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(t){const s=o(),i=e.effectivePlayingItem;i&&i===s&&a(t+i.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const s=null==(t=o())?void 0:t.event.assetList;return s?s.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const s=null==(t=o())?void 0:t.event;return s&&e.effectivePlayingAsset?s.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((t,s)=>{var i;if(0!==t&&null!=(i=e.schedule)&&i.length){var r;const i=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[i];if(n)return t+(n[s].start-n.start)}return t})(e.seekableStart,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,s=null==t?void 0:t.event;if(s&&!s.restrictions.skip){const i=e.findItemIndex(t);if(s.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&s)&&this.findItemIndex(t)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);const r=null==(t=i)?void 0:t.currentTime;return void 0!==r&&Ss(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${gi(s)}`),this.detachedData=s}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else{const e=this.getBufferingPlayer();e?(r=e.transferMedia(),this.detachedData=r,h=`${e}`):h=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${gi(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState);if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!d&&!a)return void e.attachMedia(t);const c=d&&r?r:{media:t},u=this.schedule;if(u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t||!1===e.appendInPlace}}if(!d&&o){const t=e,s=t.assetItem.timelineStart;if(s){const e=t.hls,i=Math.max(this.timelinePos-s,Number.EPSILON);e.startPosition!==i&&(this.log(`Set ${t} startPosition: ${i}`),e.config.startPosition=i,e.loadingEnabled&&e.startLoad(i))}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){if(!s.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const i=s.startPosition;if(this.timelinePos=i,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Gu("checkStart (preroll)",i));const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(Gu("checkStart",i));const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}else 0===s.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Gu("checkStart (playing item)",r.start));const t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Bu(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=this.getNextItemIndex(e,!0),s=null==(n=this.schedule.items)?void 0:n[t];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,r)}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!Ss(e.resumeOffset)&&this.hls){const e=this.getLiveStartPos();if(t){const t=this.getBufferingPlayer();return e+(null!=t&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){const s=this.livePrerollResumption(e.event,t);if(void 0!==s)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){const i=Bu(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=s[t],r=i.event?this.getNextItemIndex(i):t+1;if(r>=s.length)return void this.setSchedulePosition(-1);const n=e.resumeTime;this.timelinePos<n&&(this.log(Gu("advanceAfterAssetEnded",n)),this.timelinePos=n,e.appendInPlace&&!s[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(e.appendInPlace){const t=e.assetList[i];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const t=s.findEventIndex(i),n=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?Nu(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==t&&c!==s.assetList[t].identifier)){var o;const t=s.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Uu(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(Is.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(c,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Nu(n)}`),s.hasPlayed=!0,this.hls.trigger(Is.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:e}),s.cue.once&&this.hls)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const o=this.findItemIndex(r),l=this.livePrerollResumption(s);if(void 0!==l){let t=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(i[r])){var h;const e=null==(h=this.primaryDetails)?void 0:h.fragments;if(s.snapOptions.in&&e){const s=$h(null,e,l);s&&(t=Math.min(Math.max(i[r].start,xu(t,s)),i[r].end))}}if(this.log(Gu("live join (preroll)",t)),this.timelinePos=t,r!==o&&(r||0===r))return void this.advanceSchedule(r,e,void 0,n,a)}this.advanceSchedule(o,e,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const s=t.interstitial,i=n.findEventIndex(s.identifier);(i<e||i>e+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const t=Bu(r,(s=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,s);s=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Nu(a)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(Is.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=r.assetList[s];if(!d)return void this.advanceAfterAssetEnded(r,e,s||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){const e=r.assetList.length;this.warn(`asset ${s+1}/${e} player destroyed ${r}`),h=this.createAssetPlayer(r,d,s),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,s,t,e,o),this.shouldPlay&&$u(h.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&$u(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var i,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Nu(e)}`);let n=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<e.start||n>=e.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(e,t),this.log(Gu("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,e)),!s)return;const a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Nu(e)}`),this.hls.trigger(Is.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,s){const i=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;const e=this.endedItem||this.playingItem,r=null!=e&&e.event?this.livePrerollResumption(e.event,s):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:e,edge:t}=n;if(i<e||i>t&&!s){const s=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${e}-${t}]) snapping to liveSync ${s}`),s||e}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;const t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||s&&s-t<i?s||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:_i.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Gu("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:n}=s,a=!t&&s.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} instructToSeek: ${a} startPosition: ${n} loadingEnabled: ${i} bufferingEnabled: ${r}`),a||!i||Math.abs(n-e)>.1){const i=this.primaryDetails;if(null!=i&&i.live&&e>=i.edge){const t=this.bufferingItem;return this.log(`Resume primary loading when live reaches ${e} buffering item: ${t?Nu(t):null}`),s.pauseBuffering(),void(this.bufferPastEdge=!0)}s.startLoad(e,t)}else r||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Is.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=Xo(Xo({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===r?0:r),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const e=this.primaryDetails,t=this.bufferedPos;if(null!=e&&e.live&&t<e.edge){this.bufferPastEdge=!1;const s=this.bufferingItem;if(this.log(`Live edge ${e.edge} reached buffer: ${t} buffering item: ${s?Nu(s):null}`),(null==s?void 0:s.end)===1/0)this.startLoadingPrimaryAt(Math.max(t,s.start));else{const e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(Is.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Xo(Xo({},this.altSelection),{},{audio:s}));const r=Xo(Xo({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Xo(Xo({},this.altSelection),{},{subtitles:s}));const r=Xo(Xo({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Mh(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Mh(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){const e=this.getEventItem(s.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;return e&&i&&i[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,s)=>{e.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(t.identifier,null)});const s=e.end+.25,i=_i.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${Nu(e)} (was ${Nu(t)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const s=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;const i=this.mediaSelection;if(!i)return;const r=(null==(t=this.hls)?void 0:t.liveSyncPosition)||0;null==(s=this.schedule)||s.updateSchedule(i,[],r,e)}checkBuffer(e){var t;const s=null==(t=this.schedule)?void 0:t.items;if(!s)return;const i=_i.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(r),i=Math.min(s+1,t.length-1),n=t[i];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=i),this.isInterstitial(r)){const e=r.event;if(i-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const s=this.getAssetPlayer(e.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Nu(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,s)=>{const i=this.getAssetPlayer(e.identifier);i&&(s===t&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(Is.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),s=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),i=this.detachedData;if(i)if(i.mediaSource){const t=!0;this.attachPrimary(s,e,t)}else this.startLoadingPrimaryAt(s);else this.startLoadingPrimaryAt(s)}}bufferedToEvent(e,t){const s=e.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=0===i&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;e.appendInPlace&&(this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25));let l,h=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!e.cue.pre&&!e.cue.post){const e=h-r;e>0&&(l=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${h?` live-start: ${h} start-offset: ${l} (timeline-start: ${r})`:""}`),s)return this.createAsset(e,0,0,r,e.duration,s);const d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!n&&i){for(let s=t;s<i;s++){const t=e.assetList[s],i=this.getAssetPlayerQueueIndex(t.identifier);-1!==i&&!this.playerQueue[i].destroyed||t.error||this.createAssetPlayer(e,t,s)}const s=e.assetList[t];if(s){const e=this.getAssetPlayer(s.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const s=this.primaryDetails;s&&e>=s.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,i,r,n){const a={parentIdentifier:e.identifier,identifier:Ou(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig,n=Nh(i.loadLevelObj||i.levels[i.currentLevel],r.videoPreference),a=i.audioTracks[i.audioTrack],o=i.subtitleTracks[i.subtitleTrack];let l=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>=0){const s=t.duration;s&&e<s&&(l=e)}}const h=t.identifier,d=Xo(Xo({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:a||r.audioPreference,subtitlePreference:o||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const c=d.cmcd;null!=c&&c.sessionId&&c.contentId&&(d.cmcd=zo({},c,{contentId:fu(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const u=new Qa(this.HlsPlayerClass,d,e,t);this.playerQueue.push(u),e.assetList[s]=t;let f=!0;const g=i=>{if(i.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),i={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=this.findEventIndex(e.identifier);return void this.handleAssetItemError(i,e,r,s,t.message)}const r=i.edge-i.fragmentStart,n=t.duration;(f||null===n||r>n)&&(f=!1,this.log(`Interstitial asset "${h}" duration change ${n} > ${r}`),t.duration=r,this.updateSchedule())};u.on(Is.LEVEL_UPDATED,(e,{details:t})=>g(t)),u.on(Is.LEVEL_PTS_UPDATED,(e,{details:t})=>g(t)),u.on(Is.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(e,t)=>{const s=this.getAssetPlayer(h);if(s&&t.tracks){s.off(Is.BUFFER_CODECS,m),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};u.on(Is.BUFFER_CODECS,m),u.on(Is.BUFFERED_TO_END,()=>{const t=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;const s=this.getEventItem(e.identifier);s&&this.advanceAssetBuffering(s,t.assetItem)});const p=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const s=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return u.once(Is.MEDIA_ENDED,p(s)),u.once(Is.PLAYOUT_LIMIT_REACHED,p(1/0)),u.on(Is.ERROR,(t,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(i.details===ws.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));i.details!==ws.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(i,e,this.findEventIndex(e.identifier),s,`Asset player error ${i.error} ${e}`)}),u.on(Is.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${h}`),i={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(i,e,this.findEventIndex(e.identifier),s,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Uu(t)}`),this.hls.trigger(Is.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:u}),u}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){const e=this.playerQueue[s];this.log(`clear ${e} toSegment: ${t?Nu(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(null==h?void 0:h.identifier)!==o&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Uu(a)}`),this.hls.trigger(Is.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=e,n=this.getEventItem(i.identifier);if(!n)return;if(e.loadSource(),this.setBufferingItem(n),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))return void this.advanceAssetBuffering(n,r);const a=this.getBufferingPlayer();if(a===e)return;const o=i.appendInPlace;if(o&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const l=(null==a?void 0:a.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(o&&r!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(l&&!cl(l,e.tracks)){const t=new Error(`Asset ${Uu(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),s={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=i.findAssetIndex(r);return void this.handleAssetItemError(s,i,this.findEventIndex(i.identifier),n,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s,a.currentTime))&&a.hls){const s=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,r)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,i,r){if(e.details===ws.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Uu(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,d=zo({},e,{fatal:!1,errorAction:Vh(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(Is.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let e=i;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==c?void 0:c.identifier)===a?this.advanceAfterAssetEnded(t,s,i):(null==u?void 0:u.identifier)===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${a} playing: ${Nu(s)} startPosition: ${n} seekableStart: ${r} error: ${e.error}`),-1===a&&(a=n),a=Math.max(a,r);const i=this.updateItem(s,a);this.itemsMatch(s,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(i))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(r,t,h,o+h,s,e.URI),h+=s}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){const e=this.findEventIndex(n),t=this.getEventItem(n);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r);this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ws.ASSET_LIST_PARSING_ERROR:case ws.ASSET_LIST_LOAD_ERROR:case ws.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ws.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);const t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==t?void 0:t.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},to=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ws.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}},so=class extends er{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",Ps.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Is.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Is.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Zi.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,part:i,success:r}=t;if(!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=(i||s).start;for(let e=0;e<n.length;e++)if(o>=n[e].start&&o<=n[e].end){a=n[e];break}const l=o+(i||s).duration;if(a?a.end=l:(a={start:o,end:l},n.push(a)),!i||l>=s.end){const e=this.fragmentTracker.fragBuffered(s);i&&e&&(e.range.subs={time:[{startPTS:s.start,endPTS:l}],partial:!0}),Wo(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(0===s&&i!==Number.POSITIVE_INFINITY){const e=i-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}}),this.fragmentTracker.removeFragmentsInRange(s,e,Ps.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===Ps.SUBTITLE&&(t.details===ws.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Zi.STOPPED&&(this.state=Zi.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Rc(this.levels,t)?this.levels=t.map(e=>new ui(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new ui(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ps.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Zi.STOPPED&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let h=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var d;o.details&&(h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)),n.alignedSliding||(qd(l,n,this),h=n.fragmentStart)}o.details=n,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,h),a===i&&(this.hls.trigger(Is.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:s,payload:i}=e;s&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,s)}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e;!this.fragContextChanged(t)&&null!=s&&s.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(s,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&ld(t.method))}decryptPayload(e,t,s){const i=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,hd(i.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(Is.FRAG_DECRYPTED,{frag:t,part:s,payload:e,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:s}),s||(this.warn(`${e.name}: ${e.message}`),this.state=Zi.IDLE)})}doTick(){if(this.state===Zi.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=_i.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:h,len:d}=l;if(d>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||d&&!this.buffering)return;let c=this.getNextFragment(h,n);if(!c)return;if(Wo(c)){var t;const e=c.sn-n.startSN,s=n.fragments[e-1];c.cc!==(null==s?void 0:s.cc)||null!=(t=n.partList)&&t.length||this.fragmentTracker.getState(s)!==Ei.NOT_LOADED||(c=s)}this.loadFragment(c,r,h)}}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i!==Ei.NOT_LOADED&&i!==Ei.PARTIAL||super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new io(this.tracksBuffered[this.currentTrackId]||[])}},io=class{constructor(e){this.buffered=void 0;const t=(t,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}},ro={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},no=e=>String.fromCharCode(ro[e]||e),ao=15,oo=42,lo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ho={17:2,18:4,21:6,22:8,23:10,19:13,20:15},co={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},uo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],go=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;Gs.log(`${this.time} [${e}] ${s}`)}}},mo=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},po=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),vo=class{constructor(){this.styles=po}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=po}setStyles(e){const t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},yo=class{constructor(){this.uchar=" ",this.penState=new vo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},So=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new vo,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<oo;e++)this.chars.push(new yo);this.logger=e}equals(e){const t=this.chars,s=e.chars;for(let e=0;e<oo;e++){const i=t[e],r=s[e];if(i.uchar!==r.uchar)return!1;const n=i.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(e){for(let t=0;t<oo;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<oo;t++){const s=e[t];if(" "!==s.uchar)return!1;const i=s.penState.styles;if(i!==po&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=oo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(e){const t=Math.min(this.pos+e,oo);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=no(e);this.pos>=oo?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<oo;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<oo;s++){const i=this.chars[s].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Eo=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ao;t++)this.rows.push(new So(e));this.logger=e}reset(){for(let e=0;e<ao;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<ao;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ao;t++){const s=this.rows[t].chars,i=e.rows[t].chars;for(let e=0;e<oo;e++){const t=s[e],r=i[e];t.uchar=r.uchar,t.penState.styles=r.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<ao;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 = "+gi(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<ao;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[e].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[t-this.nrRollUpRows+i+1].copy(s.rows[e+i])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,i=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[i].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+gi(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let s=0;s<ao;s++){const r=this.rows[s].getTextString();r&&(i=s+1,e?t.push("Row "+i+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}},bo=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Eo(s),this.nonDisplayedMemory=new Eo(s),this.lastOutputScreen=new Eo(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+gi(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},To=class{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new go,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,null==(s=this.channels[e])||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new bo(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const s=127&t[e],i=127&t[e+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,()=>"["+mo([t[e],t[e+1]])+"] -> ("+mo([s,i])+")");const a=this.cmdHistory;if(s>=16&&s<=31){if(Wu(s,i,a)){Hu(null,null,a),this.logger.log(3,()=>"Repeated command ("+mo([s,i])+") is dropped");continue}Hu(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else Hu(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+mo([s,i])+" orig: "+mo([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,i=this.getChannel(s);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+mo([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;const i=e<=23?1:2;return s=t>=64&&t<=95?1===i?lo[e]:co[e]:1===i?ho[e]:uo[e],this.getChannel(i).setPAC(this.interpretPAC(s,t)),this.currentChannel=i,!0}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+no(e)+"' in channel "+s),i=[e]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+mo(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let s;const i={};16===e||24===e?(s=Math.floor((t-32)/2),i.background=fo[s],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));const r=e<=23?1:2;return this.getChannel(r).setBkgData(i),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Hu(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}},wo=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Io=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this),e.on(Is.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Is.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this),e.off(Is.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Is.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new wo(this,"textTrack1"),t=new wo(this,"textTrack2"),s=new wo(this,"textTrack3"),i=new wo(this,"textTrack4");this.cea608Parser1=new To(1,e,t),this.cea608Parser2=new To(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let e=r.length;e--;){const i=r[e],a=qu(i[0],i[1],t,s);if(a>=0&&(i[0]=Math.min(i[0],t),i[1]=Math.max(i[1],s),n=!0,a/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const r=this.cueCache[e];if(r){const e=this.Cues.newCue(null,t,s,i);e.length&&r.push.apply(r,e)}else{const r=this.captionsTracks[e].track;this.Cues.newCue(r,t,s,i)}}else{var a;const r=this.Cues.newCue(null,t,s,i),n=null==(a=this.captionsProperties[e])?void 0:a.media;this.hls.trigger(Is.CUES_PARSED,{type:"captions",cues:r,track:e,closedCaptions:n})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){const{unparsedVttFrags:i}=this;t===Ps.MAIN&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Is.FRAG_LOADED,e):this.hls.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,cueCache:i,media:r}=this,{label:n,languageCode:a}=t[e];r&&(i[e]=[],s[e]=Tu(r,"captions",n,a,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Is.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:e,cueCache:t}=this;for(const s in e)e[s].remove(),delete t[s]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!Rc(this.tracks,s)){const e=s.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(Is.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,i=this.captionsProperties[s];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Ps.MAIN){var s,i;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(i=t.part)?void 0:i.index)?s:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.level<this.tracks.length&&s.type===Ps.SUBTITLE)if(i.byteLength){const e=s.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(null==e?void 0:e.textCodec)===Da?this._parseIMSC1(t):this._parseVTTs(t)}}else{const e="part"in t?t.part:null;this.hls.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:e,error:new Error("Empty subtitle payload")})}}_parseIMSC1(e){const{frag:t,payload:s}=e,i="part"in e?e.part:null,r=this.hls;mu(s,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),r.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:i})},e=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),r.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:i,error:e})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,r="part"in e?e.part:null,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&-1===o)return void a.push(e);const l=this.hls,h=null==(t=s.initSegment)?void 0:t.data;!function(e,t,s,i,r,n,a){const o=new ka,l=bl(new Uint8Array(e)).trim().replace(Ra,"\n").split("\n"),h=[],d=t?function(e,t=1){return yc(e,$r,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!1,p=!0;o.oncue=function(e){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(m){if(null!=n&&n.new&&(a=s.ccOffset=n.start),o){if(!t)return void(c=new Error(Ca+"MPEGTS"));a=o-s.presentationOffset}}else{if(!t)return void(c=new Error(Ca+"without X-TIMESTAMP-MAP"));a=-t.baseTime/t.timescale}const l=e.endTime-e.startTime,u=Tc(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?i&&(e.id=`hlsjscc${i}_${e.id}`):e.id=gu(e.startTime,e.endTime,p),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(h)},l.forEach(e=>{if(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,m=!0,e.slice(16).split(",").forEach(e=>{e.startsWith("LOCAL:")?u=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=Pa(u)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}(h?eh(h,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!h?r:s).start,e=>{this._appendCues(e,s.level),l.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},t=>{const i=t.message.startsWith("Missing initPTS");l.logger.log(`${i?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${t}`),i?a.push(e):(this.config.enableIMSC1&&this._fallbackToIMSC1(e),l.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:t}))})}_fallbackToIMSC1(e){const{frag:t,payload:s}=e,i=this.tracks[t.level];i.textCodec||mu(s,this.initPTS[t.cc],()=>{i.textCodec=Da,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const s=null==(i=this.tracks[t].trackNode)?void 0:i.track;if(!s||"disabled"===s.mode)return;e.forEach(e=>wu(s,e))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(Is.CUES_PARSED,{type:"subtitles",cues:e,track:r,subtitleTrack:i})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===Ps.SUBTITLE&&this.onFragLoaded(Is.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(s.type!==Ps.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(t);this.cea608Parser1.addData(i[e].pts,s[0]),this.cea608Parser2.addData(i[e].pts,s[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var s;const{type:e,timeRanges:i}=t;if("video"===e&&null!=(s=i[e])&&s.length){const{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(s=>{var i;const r=null==(i=e[s])?void 0:i.track;if(r){const e=t[s];for(let t=0;t<e.length;t++)wu(r,e[t])}delete t[s]})}}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:n}=t,{media:a}=this;if(a&&!(a.currentTime<i)){if(!n||"video"===n){const{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Iu(e[t].track,s,i)),Object.keys(t).forEach(e=>{const r=t[e];for(let e=r.length;e--;){const t=r[e];t.startTime>=s&&t.endTime<=i&&r.splice(e,1)}})}this.config.renderTextTracksNatively&&0===s&&void 0!==r&&this.tracks.forEach(e=>{var t;const i=null==(t=e.trackNode)?void 0:t.track;i&&Iu(i,s,r)})}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let i=2;for(let r=0;r<s;r++){const s=e[i++],r=127&e[i++],n=127&e[i++];if((0!==r||0!==n)&&4&s){const e=3&s;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},Lo=/\s/,Ao={newCue(e,t,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)Lo.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const i=uu(h.trim()),f=gu(t,s,i);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new d(t,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>wu(e,t))),r}},ko=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Rs}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(nl(e,this.stats.retry,!0))this.retry(e);else{var t;Gs.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=il(e,s.retry),s.retry++,Gs.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}},Ro=/(\d+)-(\d+)\/(\d+)/,Co=class extends ko{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||Ku}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(zo({},e.headers))};return e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),s}(t,this.controller.signal),r="arraybuffer"===t.responseType,n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:o}=e.loadPolicy;this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=a&&Ss(a)?a:o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(kc(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var n;this.response=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},o-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new Po(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Ro.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ss(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(i.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&Ss(e.highWaterMark)?this.loadProgressively(i,s,t,e.highWaterMark,l):r?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{var r,a;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[n];l&&(s.loaded=s.total=l);const h={url:o.url,data:i,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!Ss(e.highWaterMark)&&d(s,t,i,o),null==(a=this.callbacks)||a.onSuccess(h,s,t,o)}).catch(i=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=i&&i.code||0,n=i?i.message:null,a=e.loadPolicy.errorRetry;var o;nl(a,s.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(a):(Gs.error(`${r} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},t,i?i.details:null,s))})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new tr,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}},Po=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},Do=(e,t,s)=>Math.max(t,Math.min(e,s)),Mo=/^age:\s*[\d.]+\s*$/im,_o=class extends ko{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r.call(this,s,t.url,t)}).catch(e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&Ss(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&Gs.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;nl(h,s.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(h):(Gs.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s))}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Mo.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}},Oo={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},xo=Xo(Xo({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:_o,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:qi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:Oo},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:$a,abrController:mi,bufferController:on,capLevelController:ln,errorController:Si,fpsController:ba,id3TrackController:Ua,gapController:Fa,latencyController:to},{cueHandler:Ao,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:so,subtitleTrackController:xa,timelineController:Io,audioStreamController:Jr,audioTrackController:en,emeController:Ea,cmcdController:va,contentSteeringController:ya,iframeController:Ka,interstitialsController:eo}),Fo=class extends Zr{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1,h=!1;t.levels.forEach(e=>{const t=e.attrs,d=Qu(e,s),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:m}=e;if(!d)return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);a||(a=!(!g||!m)),o||(o=!!u),l||(l=!!c),h||(h=!!f);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":S,RESOLUTION:E,"VIDEO-RANGE":b}=t,T=`${S||"."}-${e.bitrate}-${E}-${v}-${p}-${b}-${y}`;if(r[T])if(r[T].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(r[T].addGroupId("audio",t.AUDIO),r[T].addGroupId("text",t.SUBTITLES));else{const t=n[T]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[T]=s,i.push(s)}else{const t=this.createLevel(e);r[T]=t,n[T]=1,i.push(t)}}),this.filterAndSortMediaOptions(i,t,a,o,l,h)}createLevel(e){const t=new ui(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!zu(s.videoCodec,this.hls.config.preferManagedMediaSource)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=Th(e,[])}return t}filterAndSortMediaOptions(e,t,s,i,r,n){var a;let o=[],l=[],h=e;const d=(null==(a=t.stats)?void 0:a.parsing)||{},c=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(h=h.filter(({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&!!(r=t)&&hi.indexOf(r)>-1;var r})),i&&n&&(h=h.filter(e=>!e.imageCodec)),0===h.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${gi(t.levels.map(e=>e.attrs.CODECS).filter((e,t,s)=>s.indexOf(e)===t))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}}),void(d.end=performance.now());t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Yu(e.audioCodec,c)),Xu(o)),t.subtitles&&(l=t.subtitles,Xu(l));const u=h.slice(0);h.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return hi.indexOf(e.videoRange)-hi.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=gh(e.videoCodec),i=gh(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=mh(e.codecSet),i=mh(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let f=u[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==u.length))for(let e=0;e<u.length;e++)if(u[e].pathwayId===h[0].pathwayId){f=u[e];break}this._levels=h;for(let e=0;e<h.length;e++)if(h[e]===f){var g;this._firstLevel=e;const t=f.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${t}`),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const m=t.iframeVariants.filter(e=>Qu(e,c));this._iframeVariants=m;const p=r&&!i,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),S={levels:h,audioTracks:o,subtitleTracks:l,iframeVariants:m,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!p&&o.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(Is.MANIFEST_PARSED,S)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Is.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===Ps.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(Is.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){const s=this.hls.config.abrSwitchInterval;if(s>0){const i=performance.now(),r=i-this.lastABRSwitchTime,n=1e3*s;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms < ${n}ms / ${s}s)`);this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms >= ${n}ms / ${s}s)`)}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Ud(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Is.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Is.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}},Bo=class extends Bs{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);const i=e.decryptdata;if(!i){const t=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,t))}const r=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){const t=function(e){const t=[];return Ql(e,e=>t.push(e.subarray(8,24))),t}(e.initSegment.data);if(t.length){let s=t[0];const i=e.decryptdata.uri;if(s.some(e=>0!==e))this.log(`Using keyId found in init segment ${Rl(s)} keyUri: ${i}`),Ki.setKeyIdForUri(i,s);else{const e=Ki.addKeyIdForUri(i);this.log(`Patching empty keyId with ${Rl(e)} keyUri: ${i}`),s=e}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return t.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(s=>(t.key=i.decryptdata.key,Xo(Xo({},s),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Rl(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const r=this.config,n=new(0,r.loader)(r);e.keyLoader=n;const a=this.keyLoaderInfo[s]={decryptdata:t,keyLoadPromise:null,loader:n};return a.keyLoadPromise=new Promise((t,i)=>{const o={type:Cs.KEY,keyInfo:a,frag:e,responseType:"arraybuffer",url:s},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,s,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyLoaderInfo[l])return i(Ju(a,ws.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=o.loader=o.keyLoadPromise=null,t({frag:a,keyInfo:o})},onError:(t,r,n,a)=>{this.resetLoader(r),i(Ju(e,ws.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),n,Xo({url:s,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),i(Ju(e,ws.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),i(Ju(e,ws.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};n.load(o,h,d)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}},Uo=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Is.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Is.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Cs.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Cs.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Cs.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Cs.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[Cs.LEVEL];if(s){const e=s.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(s.abort(),delete this.loaders[Cs.LEVEL])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if((null==s?void 0:s.levelOrTrack)===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===Cs.MANIFEST?s.manifestLoadPolicy.default:zo({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Ss(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===Cs.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Cs.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Cs.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=zo({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),Ji.isMediaPlaylist(n)||s.type!==Cs.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=ef(e,s),o=Ji.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,iframeVariants:d,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g,h.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];ch(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,ii.audio[i.substring(0,4)]=2,t.splice(n,1)):ch(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,ii.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Ji.parseMasterPlaylistMedia(n,a,o);m.length&&(m.some(e=>!e.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Bi({}),bitrate:0,url:""}))),r.trigger(Is.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,iframeVariants:d,captions:v,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=ef(e,s),d=Ss(o)?o:Ss(a)?a:0,c=Zu(s),u=Ji.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===Cs.MANIFEST){const e={attrs:new Bi({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+Od(u,0),n.trigger(Is.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.MANIFEST_PARSING_ERROR,fatal:t.type===Cs.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Cs.LEVEL?n+=`: ${e.level} id: ${e.id}`:e.type!==Cs.AUDIO_TRACK&&e.type!==Cs.SUBTITLE_TRACK||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ws.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Cs.MANIFEST:o=s?ws.MANIFEST_LOAD_TIMEOUT:ws.MANIFEST_LOAD_ERROR,l=!0;break;case Cs.LEVEL:o=s?ws.LEVEL_LOAD_TIMEOUT:ws.LEVEL_LOAD_ERROR,l=!1;break;case Cs.AUDIO_TRACK:o=s?ws.AUDIO_TRACK_LOAD_TIMEOUT:ws.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Cs.SUBTITLE_TRACK:o=s?ws.SUBTITLE_TRACK_LOAD_TIMEOUT:ws.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:Ts.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){let s=e.url;t&&"url"in t&&(s=t.url),d.response=Xo({url:s,data:void 0},i)}this.hls.trigger(Is.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=ef(t,i),g=Zu(i);let m="number"==typeof i.level&&g===Ps.MAIN?l:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Cs.MANIFEST:case Cs.LEVEL:if(m)if(h){if(h!==a.levels[m]){const e=a.levels.indexOf(h);e>-1&&(m=e)}}else m=0;a.trigger(Is.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:m||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===Cs.MANIFEST,context:i});break;case Cs.AUDIO_TRACK:a.trigger(Is.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i});break;case Cs.SUBTITLE_TRACK:a.trigger(Is.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i})}}},(No=class e{static get version(){return nr}static isMSESupported(){return Mu()}static isSupported(){return _u()}static getMediaSource(){return dl()}static get Events(){return Is}static get MetadataSchema(){return or}static get ErrorTypes(){return Ts}static get ErrorDetails(){return ws}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:xo}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new rr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const s=this.logger=function(e,t,s){const i=ll();if("object"==typeof console&&!0===e||"object"==typeof e){const t=["debug","log","info","warn","error"];t.forEach(t=>{i[t]=hl(t,e,s)});try{i.log('Debug logs enabled for "Hls instance" in hls.js version 1.7.0')}catch(e){return ll()}t.forEach(t=>{$s[t]=hl(t,e)})}else zo($s,i);return i}(t.debug||!1,0,t.loggerId||t.assetPlayerId),i=this.config=function(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){const e=t.liveMaxUnchangedPlaylistRefresh,i=Do(e,2,1/0);i!==e&&s.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${i}.`),t.liveMaxUnchangedPlaylistRefresh=i}const i=Vu(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${gi(t[n])}`)}),Xo(Xo({},i),t)}(e.DefaultConfig,t,s);this.userConfig=t,i.progressive&&function(e,t){const s=e.loader;s!==Co&&s!==_o?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):ju()&&(e.loader=Co,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,s);const{streamController:r,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),m=new bi(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,e):null,y=a?this.bufferController=new a(this,m):null,S=o?this.capLevelController=new o(this):null,E=h?new h(this):null,b=i.cmcdController,T=b?this.cmcdController=new b(this):null,w=new Uo(this),I=i.contentSteeringController,L=I?new I(this):null,A=this.levelController=new Fo(this,L),k=d?new d(this):void 0,R=new Bo(this.config,this.logger),C=this.streamController=new r(this,m,R),P=this.gapController=u?new u(this,m):void 0;S&&S.setStreamController(C);const D=[w,A,C];v&&D.splice(1,0,v),L&&D.splice(1,0,L),this.networkControllers=D;const M=[g];y&&M.push(y),P&&M.push(P),S&&M.push(S),E&&(E.setStreamController(C),M.push(E)),k&&M.push(k),M.push(m),this.audioTrackController=this.createController(i.audioTrackController,D);const _=i.audioStreamController;_&&D.push(this.audioStreamController=new _(this,m,R)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const O=i.subtitleStreamController;O&&D.push(this.subtititleStreamController=new O(this,m,R)),this.createController(i.timelineController,M),R.emeController=this.emeController=this.createController(i.emeController,M),T&&M.push(T),this.latencyController=this.createController(i.latencyController,M),this.coreComponents=M,this.iframeController=c?new c(this,e):void 0,D.push(f);const x=f.onErrorOut;"function"==typeof x&&this.on(Is.ERROR,x,f),this.on(Is.MANIFEST_LOADED,w.onManifestLoaded,w)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===Is.ERROR;this.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Is.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(Is.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(Is.MEDIA_DETACHING,e),this._media=null,this.trigger(Is.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(Is.MEDIA_DETACHING,s),this.trigger(Is.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();const s=this.media,i=this._url,r=this._url=ks.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(Is.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started&&this.streamController.state!==Zi.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Ps.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Ps.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Ps.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,s=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=gl()),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=this.capLevelController,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return li.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=i;t--;){const i=e[t].attrs["HDCP-LEVEL"];if(i&&i<=s)return t}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}get latency(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}get maxLatency(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}get targetLatency(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Ih(e,Dh(t),navigator.mediaCapabilities)}}).defaultConfig=void 0}});function sf(e,t){return t?`${e}|${t.start}-${t.end}`:e}function rf(e,t){if(void 0!==e&&void 0!==t&&e<=t)return{start:e,end:t}}var nf,af,of,lf,hf,df,cf,uf,ff,gf,mf,pf,vf,yf,Sf,Ef,bf,Tf,wf=o({"../../node_modules/p2p-media-loader-hlsjs/lib/utils.js"(){}}),If=o({"../../node_modules/p2p-media-loader-core/lib/types.js"(){nf=class extends Error{constructor(e,t,s){super(t),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=s}},af=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerError"})}},of=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerWarning"})}},lf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TrackerError"})}},hf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TrackerWarning"})}},df=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerConnectError"})}},cf=class extends nf{constructor(e,t,s){super(e,t,s),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RequestError"}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.timestamp=performance.now()}},uf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CoreRequestError"})}}}}),Lf=o({"../../node_modules/p2p-media-loader-core/lib/utils/abort-controller.js"(){ff=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},mf=class{constructor(){Object.defineProperty(this,"aborted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),gf.set(this,new Set)}addEventListener(e,t){ff(this,gf,"f").add(t)}removeEventListener(e,t){ff(this,gf,"f").delete(t)}dispatchEvent(e){this.aborted=!0;for(const e of ff(this,gf,"f"))try{e()}catch(e){}ff(this,gf,"f").clear()}},gf=new WeakMap,pf=class{constructor(){Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:new mf})}abort(){this.signal.dispatchEvent("abort")}},vf="undefined"!=typeof AbortController,yf=vf?AbortController:pf}}),Af=o({"../../node_modules/p2p-media-loader-core/lib/http-loader.js"(){If(),Lf(),Sf=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ef=class{isAborted(){return this.abortController.signal.aborted}constructor(e,t,s){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"httpConfig",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:new yf}),Object.defineProperty(this,"expectedBytesLength",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestByteRange",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onChunkDownloaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.onChunkDownloaded=s.getEventDispatcher("onChunkDownloaded");const{byteRange:i}=this.request.segment;i&&(this.requestByteRange=Object.assign({},i))}execute(){var e;const t={onAbort:()=>this.abortController.abort(),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs};if(this.request.tryCompleteByLoadedBytes({downloadSource:"http"},t,this.httpConfig.validateHTTPSegment,"http-segment-validation-failed"))return;0!==this.request.loadedBytes&&(this.requestByteRange=null!==(e=this.requestByteRange)&&void 0!==e?e:{start:0},this.requestByteRange.start=this.requestByteRange.start+this.request.loadedBytes),this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes);const s=this.request.start({downloadSource:"http"},t);this.fetch(s)}fetch(e){return Sf(this,void 0,void 0,function*(){var t,s,i;const{segment:r}=this.request;let n;if(this.isAborted())return;const a=()=>{try{null==n||n.cancel().catch(()=>{})}catch(e){}};this.abortController.signal.addEventListener("abort",a);const o=vf?this.abortController.signal:void 0;try{let a=yield null===(s=(t=this.httpConfig).httpRequestSetup)||void 0===s?void 0:s.call(t,r.url,r.byteRange,o,this.requestByteRange);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!a){const e=new Headers;this.requestByteRange&&e.set("Range",`bytes=${this.requestByteRange.start}-${null!==(i=this.requestByteRange.end)&&void 0!==i?i:""}`);const t={headers:e};o&&(t.signal=o),a=new Request(r.url,t)}if(this.isAborted())throw new DOMException("Request aborted before request fetch","AbortError");const l=yield window.fetch(a);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(this.handleResponseHeaders(l),e.firstBytesReceived(),l.body&&"function"==typeof l.body.getReader){const t=l.body.getReader();for(n=t;;){if(this.isAborted())throw new DOMException("Request aborted","AbortError");const{done:s,value:i}=yield t.read();if(s)break;if(this.isAborted())throw new DOMException("Request aborted","AbortError");e.addLoadedChunk(i),this.onChunkDownloaded(i.byteLength,"http",void 0,r.stream.type,this.request.infoHash)}}else{const t=yield l.arrayBuffer();if(this.isAborted())throw new DOMException("Request aborted","AbortError");const s=new Uint8Array(t);e.addLoadedChunk(s),this.onChunkDownloaded(s.byteLength,"http",void 0,r.stream.type,this.request.infoHash)}if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(void 0!==this.request.totalBytes&&this.request.loadedBytes!==this.request.totalBytes)throw new cf("http-bytes-mismatch",`HTTP response truncated: received ${this.request.loadedBytes} of ${this.request.totalBytes} bytes`);const h=yield this.request.validateData(this.httpConfig.validateHTTPSegment);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!h)throw this.request.clearLoadedBytes(),new cf("http-segment-validation-failed");e.completeOnSuccess()}catch(t){this.handleError(t,e)}finally{this.abortController.signal.removeEventListener("abort",a)}})}handleResponseHeaders(e){if(!e.ok)throw 406===e.status||416===e.status?(this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText)):new cf("http-error",e.statusText);const{requestByteRange:t}=this;if(t)if(200===e.status){if(this.request.segment.byteRange)throw new cf("http-unexpected-status-code");this.request.clearLoadedBytes()}else{if(206!==e.status)throw new cf("http-unexpected-status-code",e.statusText);const s=e.headers.get("Content-Length");if(s&&void 0!==this.expectedBytesLength&&this.expectedBytesLength!==+s)throw this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText);const i=e.headers.get("Content-Range"),r=i?function(e){const t=bf.exec(e.trim());if(!t)return;const[,s,i,r]=t;return{from:s?parseInt(s):void 0,to:i?parseInt(i):void 0,total:r?parseInt(r):void 0}}(i):void 0;if(r){const{from:s,to:i}=r,n=void 0!==i&&void 0!==s?i-s+1:void 0;if(void 0!==n&&this.expectedBytesLength!==n||void 0!==s&&t.start!==s||void 0!==i&&void 0!==t.end&&t.end!==i)throw this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText)}}if(200===e.status&&void 0===this.request.totalBytes){const t=e.headers.get("Content-Length");t&&this.request.setTotalBytes(+t)}}handleError(e,t){if(!this.isAborted()&&e instanceof Error){const s=e instanceof cf?e:new cf("http-error",e.message);t.failWithError(s)}}},bf=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/}}),kf=l({"../../node_modules/ms/index.js"(e,t){var s=1e3,i=60*s,r=60*i,n=24*r,a=7*n;function o(e,t,s,i){var r=t>=1.5*s;return Math.round(e/s)+" "+i+(r?"s":"")}t.exports=function(e,t){t=t||{};var l,h,d=typeof e;if("string"===d&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return o*a;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*i;case"seconds":case"second":case"secs":case"sec":case"s":return o*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===d&&isFinite(e))return t.long?(l=e,(h=Math.abs(l))>=n?o(l,h,n,"day"):h>=r?o(l,h,r,"hour"):h>=i?o(l,h,i,"minute"):h>=s?o(l,h,s,"second"):l+" ms"):function(e){var t=Math.abs(e);return t>=n?Math.round(e/n)+"d":t>=r?Math.round(e/r)+"h":t>=i?Math.round(e/i)+"m":t>=s?Math.round(e/s)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}}),Rf=l({"../../node_modules/debug/src/common.js"(e,t){t.exports=function(e){function t(e){let i,r,n,a=null;function o(...e){if(!o.enabled)return;const s=o,r=Number(new Date),n=r-(i||r);s.diff=n,s.prev=i,s.curr=r,i=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,r)=>{if("%%"===i)return"%";a++;const n=t.formatters[r];if("function"==typeof n){const t=e[a];i=n.call(s,t),e.splice(a,1),a--}return i}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=s,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==t.namespaces&&(r=t.namespaces,n=t.enabled(e)),n),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function s(e,s){const i=t(this.namespace+(void 0===s?":":s)+e);return i.log=this.log,i}function i(e,t){let s=0,i=0,r=-1,n=0;for(;s<e.length;)if(i<t.length&&(t[i]===e[s]||"*"===t[i]))"*"===t[i]?(r=i,n=s,i++):(s++,i++);else{if(-1===r)return!1;i=r+1,n++,s=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(i(e,s))return!1;for(const s of t.names)if(i(e,s))return!0;return!1},t.humanize=kf(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(s=>{t[s]=e[s]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}}}),Cf=l({"../../node_modules/debug/src/browser.js"(e,t){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;e.splice(1,0,s,"color: inherit");let i=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(r=i))}),e.splice(r,0,s)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=Rf()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}}),Pf=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/types.js"(){var e;(e=Tf||(Tf={}))[e.SegmentsAnnouncement=0]="SegmentsAnnouncement",e[e.SegmentRequest=1]="SegmentRequest",e[e.SegmentData=2]="SegmentData",e[e.SegmentDataSendingCompleted=3]="SegmentDataSendingCompleted",e[e.SegmentAbsent=4]="SegmentAbsent",e[e.CancelSegmentRequest=5]="CancelSegmentRequest"}});function Df(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}function Mf(e){Promise.resolve().then(e)}function _f(e,t){null!=t||(t=e.reduce((e,t)=>e+t.byteLength,0));const s=new Uint8Array(t);let i=0;for(const t of e)s.set(t,i),i+=t.byteLength;return s}function*Of(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function xf(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Ff(e){if(function(e){return Array.isArray(e)}(e))return e.map(e=>Ff(e));if(xf(e)){const t={};for(const s of Object.keys(e))t[s]=Ff(e[s]);return t}return e}function Bf(e,t,s={}){return"object"!=typeof e||null===e||"object"!=typeof t||null===t||Object.keys(t).forEach(i=>{const r="symbol"==typeof i?i.toString():String(i);if("__proto__"===i||"constructor"===i||"prototype"===i)throw new Error(`Attempt to modify restricted property '${r}'`);const n=t[i],a=s[i];i in e&&(e[i]=void 0===n?void 0===a?void 0:a:n)}),e}function Uf(e){const{defaultConfig:t,baseConfig:s={},specificStreamConfig:i={}}=e,r=Ff(Object.assign(Object.assign(Object.assign({},t),s),i)),n=Object.keys(t),a={};return n.forEach(e=>{e in r&&(a[e]=r[e])}),a}var Nf,$f,Gf,Hf,Wf,qf,jf,Kf,Vf,Yf,zf=o({"../../node_modules/p2p-media-loader-core/lib/utils/utils.js"(){}});function Qf(e){const t=e.length,s=(e,s)=>{const i=8*(t-1-s);return e*Math.pow(2,i)};let i=s(127&e[0],0);for(let r=1;r<t;r++)i+=s(e[r],r);return(128&e[0])>>7&&(i=-i),i}function Xf(e){const t=function(e){const t=e<0,s=function(e){if(0===e)return 1;const t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}(e),i=new Uint8Array(s);e=Math.abs(e);for(let t=0;t<s;t++){const r=8*(s-1-t),n=255&Math.floor(e/Math.pow(2,r));i[t]=n}return t&&(i[0]=128|i[0]),i}(e),s=Vf.Int<<4|t.length;return new Uint8Array([s,...t])}function Jf(e){if(0===e.length)throw new Error("Buffer is too short");const t=e[0];if(t>>4!==Vf.Int)throw new Error("Trying to deserialize integer with invalid serialized item code");const s=15&t;if(0===s)throw new Error("Invalid integer: zero byte length");if(s>7)throw new Error("Invalid integer: byte length exceeds safe integer limit");const i=1+s;if(e.length<i)throw new Error("Buffer is too short");return{number:Qf(e.subarray(1,i)),byteLength:s+1}}function Zf(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!==Vf.SimilarIntArray)throw new Error("Trying to deserialize similar int array with invalid serialized item code");let i=2;const r=[];for(let t=0;t<s;t++){const{number:t,byteLength:s}=Jf(e.subarray(i));i+=s;const n=255&t,a=0===n?256:n,o=t-n;if(i+a>e.length)throw new Error("Malformed similar int array: buffer too short");for(let t=0;t<a;t++){const t=e[i];r.push(o+t),i++}}return{numbers:r,byteLength:i}}function eg(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!==Vf.String)throw new Error("Trying to deserialize bytes (sting) with invalid serialized item code.");const i=(15&t)<<8|s;if(e.length<i+2)throw new Error("Malformed string: buffer too short");const r=e.subarray(2,i+2);return{string:Kf.decode(r),byteLength:i+2}}var tg,sg,ig,rg,ng,ag,og,lg,hg,dg,cg,ug,fg,gg,mg,pg,vg,yg,Sg,Eg,bg,Tg,wg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/binary-serialization.js"(){var e;zf(),Nf=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$f=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},jf=new TextEncoder,Kf=new TextDecoder("utf8"),(e=Vf||(Vf={}))[e.Min=-1]="Min",e[e.Int=0]="Int",e[e.SimilarIntArray=1]="SimilarIntArray",e[e.String=2]="String",e[e.Max=3]="Max",Yf=class{constructor(){Gf.add(this),Hf.set(this,[]),Wf.set(this,0)}push(e){Nf(this,Gf,"m",qf).call(this,e,"end")}unshift(e){Nf(this,Gf,"m",qf).call(this,e,"start")}getBytesChunks(){return Nf(this,Hf,"f")}getBuffer(){return _f(Nf(this,Hf,"f"),Nf(this,Wf,"f"))}get length(){return Nf(this,Wf,"f")}},Hf=new WeakMap,Wf=new WeakMap,Gf=new WeakSet,qf=function(e,t){let s;s=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),$f(this,Wf,Nf(this,Wf,"f")+s.length,"f"),Nf(this,Hf,"f")["start"===t?"unshift":"push"](s)}}});function Ig(e){if(e.length<Sg)return!1;const{length:t}=fg,s=e.subarray(-t);return vg.some(t=>Cg(e,t,ug))&&yg.some(e=>Cg(s,e,ug))}function Lg(e){const[t]=e,s={c:t};let i=1;for(;i<e.length;){if(i+1>=e.length)throw new Error("Malformed command buffer: truncated name/type header");const t=String.fromCharCode(e[i]);switch(i++,Ag(e[i])){case Vf.Int:{const{number:r,byteLength:n}=Jf(e.subarray(i));s[t]=r,i+=n}break;case Vf.SimilarIntArray:{const{numbers:r,byteLength:n}=Zf(e.subarray(i));s[t]=r,i+=n}break;case Vf.String:{const{string:r,byteLength:n}=eg(e.subarray(i));s[t]=r,i+=n}}}return function(e){switch(e.c){case Tf.SegmentsAnnouncement:return e;case Tf.SegmentRequest:return Pg(e,"i","r"),e;case Tf.SegmentData:return Pg(e,"i","r","s"),e;case Tf.SegmentAbsent:case Tf.CancelSegmentRequest:case Tf.SegmentDataSendingCompleted:return Pg(e,"i","r"),e;default:throw new Error(`Unknown peer command type: ${String(e.c)}`)}}(s)}function Ag(e){const t=e>>4;if(t<=Vf.Min||t>=Vf.Max)throw new Error("Not existing type");return t}function kg(e,t){if(t&&e.length!==t)throw new Error("Wrong string length");const s=new Uint8Array(null!=t?t:e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Rg(e,t,s){const i=new Uint8Array(e.length+t.length+s.length);return i.set(t),i.set(e,t.length),i.set(s,t.length+e.length),i}function Cg(e,t,s){for(let i=0;i<s;i++)if(e[i]!==t[i])return!1;return!0}function Pg(e,...t){for(const s of t)if("number"!=typeof e[s])throw new Error(`Expected number field "${s}", got ${typeof e[s]}`)}var Dg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/binary-command-creator.js"(){wg(),Pf(),tg=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},sg=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},fg=kg("cstr",ug=4),gg=kg("cend",ug),mg=kg("dstr",ug),pg=kg("dend",ug),vg=[fg,mg],yg=[gg,pg],Sg=fg.length+gg.length,Eg=class extends Error{constructor(e){super(),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:e})}},bg=class{constructor(e){ig.add(this),rg.set(this,new Yf),ng.set(this,"joining"),ag.set(this,void 0),tg(this,ag,e,"f")}addCommandChunk(e){if("completed"===sg(this,ng,"f"))return;const t=!((s=e).length<Sg)&&Cg(s,fg,ug);var s;if(!sg(this,rg,"f").length&&!t)throw new Eg("no-first-chunk");if(sg(this,rg,"f").length&&t)throw new Eg("incomplete-joining");sg(this,rg,"f").push(sg(this,ig,"m",og).call(this,e)),function(e){return!(e.length<Sg)&&Cg(e.subarray(-ug),gg,ug)}(e)&&(tg(this,ng,"completed","f"),sg(this,ag,"f").call(this,sg(this,rg,"f").getBuffer()))}},rg=new WeakMap,ng=new WeakMap,ag=new WeakMap,ig=new WeakSet,og=function(e){if(e.length<Sg)throw new Error("Command chunk is too short to unframe");return e.subarray(ug,e.length-ug)},Tg=class{constructor(e,t){lg.set(this,new Yf),hg.set(this,[]),dg.set(this,"creating"),cg.set(this,void 0),tg(this,cg,t,"f"),sg(this,lg,"f").push(e)}addInteger(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=Xf(t);sg(this,lg,"f").push(s)}addUniqueSimilarIntArr(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=function(e){var t;const s=new Map;for(const i of e){const e=255&i,r=i-e,n=null!==(t=s.get(r))&&void 0!==t?t:new Yf;n.length||s.set(r,n),n.push(e)}const i=new Yf;i.push([Vf.SimilarIntArray<<4,s.size]);for(const[e,t]of s){const{length:s}=t,r=e+(255&s);t.unshift(Xf(r)),i.push(t.getBuffer())}return i.getBuffer()}(t);sg(this,lg,"f").push(s)}addString(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=function(e){const t=jf.encode(e),{length:s}=t;if(s>4095)throw new Error("String exceeds maximum length of 4095 bytes");const i=new Yf;return i.push([Vf.String<<4|s>>8&15,255&s]),i.push(t),i.getBuffer()}(t);sg(this,lg,"f").push(s)}complete(){if(!sg(this,lg,"f").length)throw new Error("Buffer is empty");if("completed"===sg(this,dg,"f"))return;tg(this,dg,"completed","f");const e=sg(this,lg,"f").getBuffer();if(e.length+Sg<=sg(this,cg,"f"))return void sg(this,hg,"f").push(Rg(e,fg,gg));let t=Math.ceil(e.length/sg(this,cg,"f"));Math.ceil(e.length/t)+Sg>sg(this,cg,"f")&&t++;for(const[s,i]of function*(e,t){const s=Math.ceil(e.length/t);for(let i=0;i<t;i++)yield[i,e.subarray(i*s,(i+1)*s)]}(e,t))0===s?sg(this,hg,"f").push(Rg(i,fg,pg)):s===t-1?sg(this,hg,"f").push(Rg(i,mg,gg)):sg(this,hg,"f").push(Rg(i,mg,pg))}getResultBuffers(){if("creating"===sg(this,dg,"f")||!sg(this,hg,"f").length)throw new Error("Command is not complete.");return sg(this,hg,"f")}},lg=new WeakMap,hg=new WeakMap,dg=new WeakMap,cg=new WeakMap}});function Mg(e,t){switch(e.c){case Tf.CancelSegmentRequest:case Tf.SegmentAbsent:case Tf.SegmentDataSendingCompleted:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t);case Tf.SegmentRequest:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),e.b&&s.addInteger("b",e.b),s.complete(),s.getResultBuffers()}(e,t);case Tf.SegmentsAnnouncement:return function(e,t){const{c:s,p:i,l:r}=e,n=new Tg(s,t);return(null==r?void 0:r.length)&&n.addUniqueSimilarIntArr("l",r),(null==i?void 0:i.length)&&n.addUniqueSimilarIntArr("p",i),n.complete(),n.getResultBuffers()}(e,t);case Tf.SegmentData:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("s",e.s),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t)}}var _g=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/commands.js"(){Dg(),Pf()}}),Og={};h(Og,{BinaryCommandChunksJoiner:()=>bg,BinaryCommandJoiningError:()=>Eg,PeerCommandType:()=>Tf,deserializeCommand:()=>Lg,isCommandChunk:()=>Ig,serializePeerCommand:()=>Mg});var xg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/index.js"(){Pf(),_g(),Dg()}});function Fg(e,t="RTC error"){return function(e,t="RTC error"){var s,i;const r=e;if(r.error instanceof Error)return r.error;const n=null!==(i=null===(s=r.error)||void 0===s?void 0:s.message)&&void 0!==i?i:t;return new Error(n)}(e,t).message}function Bg(e){return"failed"===e||"closed"===e||"disconnected"===e}var Ug,Ng,$g,Gg,Hg,Wg,qg,jg,Kg,Vg,Yg,zg,Qg,Xg,Jg,Zg,em,tm,sm,im,rm,nm,am,om,lm,hm,dm,cm,um,fm,gm,mm,pm,vm,ym,Sm,Em,bm,Tm,wm,Im,Lm,Am,km,Rm,Cm,Pm,Dm,Mm,_m,Om,xm,Fm,Bm,Um,Nm,$m,Gm,Hm,Wm,qm,jm=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/utils.js"(){}}),Km=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/data-channel-sender.js"(){zf(),jm(),Ug=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ng=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$g=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Hg=class{constructor(e,t){Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"maxMessageSize",{enumerable:!0,configurable:!0,writable:!0,value:t}),Gg.set(this,void 0)}sendData(e,t){return Ug(this,void 0,void 0,function*(){if(Ng(this,Gg,"f"))throw new Error("Already sending data");if("open"!==this.channel.readyState)throw new Error("Data channel is not open");this.channel.bufferedAmountLowThreshold=8192;const{promise:s,resolve:i,reject:r}=Df();let n,a=0,o=!1;const l=()=>!o&&(o=!0,void 0!==n&&clearTimeout(n),$g(this,Gg,void 0,"f"),this.channel.removeEventListener("bufferedamountlow",g),this.channel.removeEventListener("closing",h),this.channel.removeEventListener("close",h),this.channel.removeEventListener("error",d),!0);$g(this,Gg,{cancel:()=>{l()&&r(new Error("Send cancelled"))}},"f");const h=()=>{l()&&r(new Error("Data channel closed"))},d=e=>{if(!l())return;const t=Fg(e,"Unknown error");r(new Error(`Data channel error: ${t}`))},c=ArrayBuffer.isView(e)?e.buffer:e,u=ArrayBuffer.isView(e)?e.byteOffset:0,f=()=>{void 0===n&&(n=setTimeout(()=>{n=void 0,g()},25))},g=()=>{if(!o)if("open"===this.channel.readyState){try{for(;a<e.byteLength;){if(this.channel.bufferedAmount>=16384)return void f();const s=Math.min(this.maxMessageSize,e.byteLength-a),i=new Uint8Array(c,u+a,s);if(this.channel.send(i),a+=s,null==t||t(s),!Ng(this,Gg,"f"))return}}catch(e){return void(l()&&r(e instanceof Error?e:new Error(String(e))))}l()&&i()}else l()&&r(new Error(`Data channel not open (state: ${this.channel.readyState})`))};return this.channel.addEventListener("bufferedamountlow",g),this.channel.addEventListener("closing",h),this.channel.addEventListener("close",h),this.channel.addEventListener("error",d),g(),s})}cancel(){var e;null===(e=Ng(this,Gg,"f"))||void 0===e||e.cancel()}},Gg=new WeakMap}}),Vm=o({"../../node_modules/p2p-media-loader-core/lib/p2p/peer-protocol.js"(){Wg=d(Cf(),1),xg(),Km(),qg=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},jg=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Kg=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},nm=(0,Wg.default)("p2pml-core:peer-protocol"),am=class{constructor(e,t,s,i,r){if(Vg.add(this),Yg.set(this,void 0),zg.set(this,void 0),Qg.set(this,void 0),Xg.set(this,void 0),Jg.set(this,void 0),Zg.set(this,void 0),em.set(this,void 0),tm.set(this,void 0),sm.set(this,void 0),im.set(this,e=>{try{const t=new Uint8Array(e.data);Ig(t)?Kg(this,Vg,"m",rm).call(this,t):(Kg(this,tm,"f").onSegmentChunkReceived(t),Kg(this,Xg,"f").call(this,t.byteLength,"p2p",Kg(this,sm,"f"),Kg(this,em,"f").streamType,Kg(this,em,"f").infoHash))}catch(e){nm("error handling data channel message: %O",e),Kg(this,tm,"f").onProtocolError(e)}}),jg(this,Zg,e,"f"),jg(this,em,t,"f"),jg(this,tm,s,"f"),jg(this,sm,r,"f"),jg(this,zg,new Hg(e,t.webRtcMaxMessageSize),"f"),jg(this,Xg,i.getEventDispatcher("onChunkDownloaded"),"f"),jg(this,Jg,i.getEventDispatcher("onChunkUploaded"),"f"),"arraybuffer"!==e.binaryType)throw new Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener("message",Kg(this,im,"f"))}sendCommand(e){if("open"!==Kg(this,Zg,"f").readyState)throw new Error(`cannot send command ${e.c} (channel state: ${Kg(this,Zg,"f").readyState})`);const t=Mg(e,Kg(this,em,"f").webRtcMaxMessageSize);for(const e of t)Kg(this,Zg,"f").send(e)}stopUploadingSegmentData(){Kg(this,zg,"f").cancel(),jg(this,Qg,void 0,"f")}getUploadingRequestId(){return Kg(this,Qg,"f")}splitSegmentDataToChunksAndUploadAsync(e,t){return qg(this,void 0,void 0,function*(){if(void 0!==Kg(this,Qg,"f"))throw new Error("Some segment data is already uploading.");jg(this,Qg,t,"f");try{yield Kg(this,zg,"f").sendData(e,e=>{Kg(this,Jg,"f").call(this,e,Kg(this,sm,"f"),Kg(this,em,"f").streamType,Kg(this,em,"f").infoHash)})}finally{Kg(this,Qg,"f")===t&&jg(this,Qg,void 0,"f")}})}destroy(){Kg(this,Zg,"f").removeEventListener("message",Kg(this,im,"f")),Kg(this,zg,"f").cancel(),jg(this,Yg,void 0,"f"),jg(this,Qg,void 0,"f")}},Yg=new WeakMap,zg=new WeakMap,Qg=new WeakMap,Xg=new WeakMap,Jg=new WeakMap,Zg=new WeakMap,em=new WeakMap,tm=new WeakMap,sm=new WeakMap,im=new WeakMap,Vg=new WeakSet,rm=function(e){var t;jg(this,Yg,null!==(t=Kg(this,Yg,"f"))&&void 0!==t?t:new bg(e=>{let t;jg(this,Yg,void 0,"f");try{t=Lg(e)}catch(e){return nm("error deserializing command: %O",e),void Kg(this,tm,"f").onProtocolError(e)}Kg(this,tm,"f").onCommandReceived(t)}),"f");try{Kg(this,Yg,"f").addCommandChunk(e)}catch(e){nm("error receiving command chunks: %O",e),jg(this,Yg,void 0,"f"),Kg(this,tm,"f").onProtocolError(e)}}}}),Ym=o({"../../node_modules/p2p-media-loader-core/lib/bandwidth-calculator.js"(){om=class{constructor(e=2e4){Object.defineProperty(this,"clearThresholdMs",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loadingsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"bytes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"loadingOnlyTimestamps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"timestamps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"noLoadingsTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"loadingsStoppedAt",{enumerable:!0,configurable:!0,writable:!0,value:0})}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),0===this.loadingsCount&&0!==this.loadingsStoppedAt&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,0===this.loadingsCount&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=Number.NEGATIVE_INFINITY){if(!this.loadingOnlyTimestamps.length)return 0;const s=1e3*e,i=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1];let r=i;const n=i-s;let a=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.loadingOnlyTimestamps[e];if(s<n||this.timestamps[e]<t)break;r=s,a+=this.bytes[e]}return 8e3*a/Math.max(i-r,1)}getBandwidth(e,t=Number.NEGATIVE_INFINITY,s=performance.now()){if(!this.timestamps.length)return 0;const i=s-1e3*e;let r=s,n=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.timestamps[e];if(s<i||s<t)break;r=s,n+=this.bytes[e]}return 8e3*n/Math.max(s-r,1)}clearStale(){if(!this.loadingOnlyTimestamps.length)return;const e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs;let t=0;for(const s of this.loadingOnlyTimestamps){if(s>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}clear(){this.bytes.length=0,this.loadingOnlyTimestamps.length=0,this.timestamps.length=0,this.loadingsCount=0,this.noLoadingsTime=0,this.loadingsStoppedAt=0}}}}),zm=o({"../../node_modules/p2p-media-loader-core/lib/p2p/peer.js"(){lm=d(Cf(),1),If(),xg(),Vm(),Ym(),hm=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},dm=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},cm=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},({PeerCommandType:Om}=Og),xm=class{get isDestroyed(){return dm(this,wm,"f")}constructor(e,t,s,i,r,n){um.add(this),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:n}),fm.set(this,void 0),gm.set(this,void 0),mm.set(this,new Set),pm.set(this,new Set),vm.set(this,0),ym.set(this,new om),Sm.set(this,{value:0,timestamp:0}),Em.set(this,(0,lm.default)("p2pml-core:peer")),bm.set(this,0),Tm.set(this,void 0),wm.set(this,!1),Object.defineProperty(this,"connectedAt",{enumerable:!0,configurable:!0,writable:!0,value:performance.now()}),Im.set(this,void 0),Lm.set(this,void 0),Am.set(this,void 0),km.set(this,e=>hm(this,void 0,void 0,function*(){var t;switch(e.c){case Om.SegmentsAnnouncement:cm(this,mm,new Set(e.l),"f"),cm(this,pm,new Set(e.p),"f"),dm(this,Lm,"f").onSegmentsAnnouncement(dm(this,mm,"f").size,dm(this,pm,"f").size);break;case Om.SegmentRequest:cm(this,Tm,e.r,"f"),dm(this,fm,"f").stopUploadingSegmentData(),dm(this,Lm,"f").onSegmentRequested(this,e.i,e.r,e.b);break;case Om.SegmentData:{if(!dm(this,gm,"f"))break;if(dm(this,gm,"f").isSegmentDataCommandReceived)break;const{request:t,controls:s,requestId:i}=dm(this,gm,"f");if(t.segment.externalId!==e.i||i!==e.r)break;dm(this,gm,"f").isSegmentDataCommandReceived=!0,s.firstBytesReceived(),void 0===t.totalBytes?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch")}break;case Om.SegmentDataSendingCompleted:{const t=dm(this,gm,"f");if(!(null==t?void 0:t.isSegmentDataCommandReceived))return;const{request:s,controls:i,requestId:r}=t;if(s.segment.externalId!==e.i||r!==e.r)return void dm(this,um,"m",Cm).call(this,"protocol-violation","Peer protocol violation");if(s.loadedBytes!==s.totalBytes)return void dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch");const n=yield s.validateData(dm(this,Am,"f").validateP2PSegment);if(dm(this,wm,"f"))return;if(dm(this,gm,"f")!==t)return;if(!n)return void dm(this,um,"m",Cm).call(this,"validation-failed","P2P segment validation failed");cm(this,vm,0,"f"),i.completeOnSuccess(),dm(this,ym,"f").stopLoading(),cm(this,gm,void 0,"f");break}case Om.SegmentAbsent:dm(this,mm,"f").delete(e.i),(null===(t=dm(this,gm,"f"))||void 0===t?void 0:t.request.segment.externalId)===e.i&&dm(this,gm,"f").requestId===e.r&&dm(this,um,"m",Pm).call(this,"peer-segment-absent");break;case Om.CancelSegmentRequest:if(dm(this,Tm,"f")===e.r&&cm(this,Tm,void 0,"f"),dm(this,fm,"f").getUploadingRequestId()!==e.r)break;dm(this,fm,"f").stopUploadingSegmentData()}})),Rm.set(this,e=>{var t;if(!(null===(t=dm(this,gm,"f"))||void 0===t?void 0:t.isSegmentDataCommandReceived))return;const{request:s,controls:i}=dm(this,gm,"f");void 0!==s.totalBytes&&s.loadedBytes+e.byteLength>s.totalBytes?dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch"):(dm(this,ym,"f").addBytes(e.byteLength),dm(this,Sm,"f").timestamp=0,i.addLoadedChunk(e))}),cm(this,Im,s,"f"),cm(this,Lm,i,"f"),cm(this,Am,r,"f"),cm(this,fm,new am(t,r,{onSegmentChunkReceived:dm(this,Rm,"f"),onCommandReceived:e=>{dm(this,km,"f").call(this,e).catch(t=>{dm(this,Em,"f").call(this,"error processing command %O: %O",e,t),this.destroy(!1,new af("protocol-violation",t instanceof Error?t.message:"Error processing command",t))})},onProtocolError:e=>{this.destroy(!1,new af("protocol-violation",e instanceof Error?e.message:"Protocol error",e))}},n,e),"f")}get downloadingSegment(){var e;return null===(e=dm(this,gm,"f"))||void 0===e?void 0:e.request.segment}get isUploadingSegment(){return void 0!==dm(this,fm,"f").getUploadingRequestId()}getDownloadBandwidth(){const e=performance.now();return e-dm(this,Sm,"f").timestamp>1e3&&(dm(this,Sm,"f").value=dm(this,ym,"f").getBandwidthLoadingOnly(15),dm(this,Sm,"f").timestamp=e),dm(this,Sm,"f").value}getSegmentStatus(e){const{externalId:t}=e;return dm(this,mm,"f").has(t)?"loaded":dm(this,pm,"f").has(t)?"http-loading":void 0}downloadSegment(e){if(dm(this,wm,"f"))return;if(dm(this,gm,"f"))throw new Error("Some segment already is downloading");if(e.tryCompleteByLoadedBytes({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:dm(this,Am,"f").p2pNotReceivingBytesTimeoutMs,onAbort:()=>{}},dm(this,Am,"f").validateP2PSegment,"p2p-segment-validation-failed"))return;dm(this,ym,"f").startLoading(),cm(this,bm,(dm(this,bm,"f")+1)%1e9,"f"),cm(this,gm,{request:e,requestId:dm(this,bm,"f"),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:dm(this,Am,"f").p2pNotReceivingBytesTimeoutMs,onAbort:t=>{var s;if(!dm(this,gm,"f")||dm(this,gm,"f").request!==e)return;const{request:i,requestId:r}=dm(this,gm,"f");dm(this,um,"m",Dm).call(this,i.segment,r),dm(this,ym,"f").stopLoading(),"abort"!==t.type&&(dm(this,ym,"f").clear(),dm(this,Sm,"f").timestamp=0,dm(this,Em,"f").call(this,`cleared bandwidth history due to ${t.type}`)),cm(this,gm,void 0,"f"),"bytes-receiving-timeout"===t.type&&cm(this,vm,(s=dm(this,vm,"f"),++s),"f"),dm(this,vm,"f")>=dm(this,Am,"f").p2pErrorRetries?this.destroy(!1,new af("timeout","Too many timeout errors")):"bytes-receiving-timeout"===t.type&&dm(this,Lm,"f").onWarning(new of("timeout-strike",`Timeout strike ${dm(this,vm,"f")}/${dm(this,Am,"f").p2pErrorRetries}`))}})},"f");const t={c:Om.SegmentRequest,r:dm(this,gm,"f").requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),dm(this,um,"m",_m).call(this,t)||dm(this,um,"m",Pm).call(this,"peer-closed")}uploadSegmentData(e,t,s){return hm(this,void 0,void 0,function*(){if(dm(this,wm,"f"))return;if(t!==dm(this,Tm,"f"))return void dm(this,Em,"f").call(this,`discarding obsolete upload request ${t} for segment ${e.externalId}`);const{externalId:i}=e;dm(this,Em,"f").call(this,`send segment ${e.externalId} to ${this.id} (byteLength: ${s.byteLength})`);const r={c:Om.SegmentData,i:i,r:t,s:s.byteLength};if(dm(this,um,"m",_m).call(this,r))try{if(yield dm(this,fm,"f").splitSegmentDataToChunksAndUploadAsync(s,t),this.isDestroyed||t!==dm(this,Tm,"f"))return;dm(this,um,"m",Mm).call(this,e,t),dm(this,Em,"f").call(this,`segment ${i} has been sent to ${this.id}`)}catch(e){dm(this,Em,"f").call(this,`cancel segment uploading ${i}: %O`,e)}})}sendSegmentsAnnouncementCommand(e,t){const s={c:Om.SegmentsAnnouncement,p:t,l:e};dm(this,um,"m",_m).call(this,s)}sendSegmentAbsentCommand(e,t){dm(this,um,"m",_m).call(this,{c:Om.SegmentAbsent,i:e,r:t})}destroy(e=!1,t){dm(this,wm,"f")||(cm(this,wm,!0,"f"),dm(this,um,"m",Pm).call(this,"peer-closed",t),dm(this,fm,"f").destroy(),e||dm(this,Im,"f").call(this,t),dm(this,Em,"f").call(this,`peer closed ${this.id}`))}},fm=new WeakMap,gm=new WeakMap,mm=new WeakMap,pm=new WeakMap,vm=new WeakMap,ym=new WeakMap,Sm=new WeakMap,Em=new WeakMap,bm=new WeakMap,Tm=new WeakMap,wm=new WeakMap,Im=new WeakMap,Lm=new WeakMap,Am=new WeakMap,km=new WeakMap,Rm=new WeakMap,um=new WeakSet,Cm=function(e,t){var s;null===(s=dm(this,gm,"f"))||void 0===s||s.request.clearLoadedBytes();const i=new af(e,t);dm(this,um,"m",Pm).call(this,"peer-closed",i),this.destroy(!1,i)},Pm=function(e,t){if(!dm(this,gm,"f"))return;const{request:s,controls:i}=dm(this,gm,"f"),{segment:r}=s;dm(this,Em,"f").call(this,`cancel segment request ${r.externalId} (${e})`);const n=new cf(e,void 0,t);i.failWithError(n),dm(this,ym,"f").stopLoading(),"peer-segment-absent"!==e&&(dm(this,ym,"f").clear(),dm(this,Sm,"f").timestamp=0,dm(this,Em,"f").call(this,`cleared bandwidth history due to ${n.type}`)),cm(this,gm,void 0,"f")},Dm=function(e,t){dm(this,um,"m",_m).call(this,{c:Om.CancelSegmentRequest,i:e.externalId,r:t})},Mm=function(e,t){dm(this,um,"m",_m).call(this,{c:Om.SegmentDataSendingCompleted,r:t,i:e.externalId})},_m=function(e){if(dm(this,wm,"f"))return!1;try{return dm(this,fm,"f").sendCommand(e),!0}catch(t){return dm(this,Em,"f").call(this,"error sending command %d: %O",e.c,t),!1}}}}),Qm=o({"../../node_modules/p2p-media-loader-core/lib/utils/event-target.js"(){Fm=class{constructor(){Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}dispatchEvent(e,t,s,i,r,n){const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch(e){}}getEventDispatcher(e){return(t,s,i,r,n)=>{const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch(e){}}}addEventListener(e,t){const s=this.events.get(e);s?this.events.set(e,[...s,t]):this.events.set(e,[t])}removeEventListener(e,t){const s=this.events.get(e);if(!s)return;const i=s.indexOf(t);if(-1===i)return;if(1===s.length)return void this.events.delete(e);const r=s.slice();r.splice(i,1),this.events.set(e,r)}clear(){this.events.clear()}}}});function Xm(e,t){return qm?e.setLocalDescription(t):new Promise((s,i)=>{try{e.setLocalDescription(t,s,i)}catch(e){i(e)}})}function Jm(e,t){return qm?e.setRemoteDescription(t):new Promise((s,i)=>{try{e.setRemoteDescription(t,s,i)}catch(e){i(e)}})}var Zm,ep,tp,sp,ip,rp,np,ap,op,lp,hp,dp,cp,up,fp,gp,mp,pp,vp,yp,Sp,Ep,bp,Tp,wp,Ip,Lp,Ap,kp,Rp,Cp,Pp,Dp,Mp,_p,Op,xp,Fp,Bp,Up,Np=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-client/webrtc-utils.js"(){Gm="undefined"!=typeof window?window:{},Hm=null!==(Um=null!==(Bm=Gm.RTCPeerConnection)&&void 0!==Bm?Bm:Gm.webkitRTCPeerConnection)&&void 0!==Um?Um:Gm.mozRTCPeerConnection,Wm=null!==($m=null!==(Nm=Gm.RTCSessionDescription)&&void 0!==Nm?Nm:Gm.webkitRTCSessionDescription)&&void 0!==$m?$m:Gm.mozRTCSessionDescription,qm=(()=>{if(!Gm.RTCPeerConnection&&!Gm.webkitRTCPeerConnection&&!Gm.mozRTCPeerConnection)return!1;let e;try{e=new Hm;const t=e.createOffer();if("function"==typeof(null==t?void 0:t.then))return t.catch(()=>{}),!0}catch(e){}finally{try{null==e||e.close()}catch(e){}}return!1})()}});function $p(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&Bp.has(t.type)&&"string"==typeof t.sdp}var Gp,Hp,Wp,qp,jp,Kp,Vp,Yp,zp,Qp,Xp,Jp,Zp,ev,tv=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-client/index.js"(){Qm(),zf(),jm(),If(),Lf(),Np(),Zm=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},ep=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},tp=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Bp=new Set(["offer","answer","pranswer","rollback"]),ip=Up=class{constructor(e){var t,s,i,r,n,a;sp.add(this),ap.set(this,void 0),op.set(this,void 0),lp.set(this,new Fm),hp.set(this,new Map),dp.set(this,new Set),cp.set(this,new yf),up.set(this,null),fp.set(this,null),gp.set(this,0),mp.set(this,null),pp.set(this,void 0),vp.set(this,null),yp.set(this,!1),bp.set(this,()=>{ep(this,sp,"m",Ip).call(this,ep(ip,ip,"f",rp)),ep(this,sp,"m",Ap).call(this,"started").catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("announce-failed",`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})}),Tp.set(this,()=>{ep(this,sp,"m",Lp).call(this),tp(this,fp,null,"f")}),wp.set(this,e=>{if(ep(this,sp,"m",Sp).call(this))return;let t;try{const s="string"==typeof e?e:(new TextDecoder).decode(e);t=JSON.parse(s)}catch(e){return void ep(this,lp,"f").dispatchEvent("error",new lf("parse-error",`Failed to parse tracker message: ${e instanceof Error?e.message:String(e)}`,e))}if("object"!=typeof t||null===t||Array.isArray(t))return;const s=t,i=s.info_hash;if("string"==typeof i&&i!==ep(this,ap,"f").infoHash)return;const r=s["warning message"];"string"==typeof r&&ep(this,lp,"f").dispatchEvent("warning",new hf("tracker-response",r));const n=s["failure reason"];if("string"==typeof n)return void ep(this,lp,"f").dispatchEvent("error",new lf("tracker-response",n));const{interval:a}=s;if("number"==typeof a&&a>0){const e=Math.max(ep(ip,ip,"f",np),a);ep(this,fp,"f")!==e&&ep(this,sp,"m",Ip).call(this,e)}const o=s["tracker id"];"string"==typeof o&&tp(this,vp,o,"f");const l=s.peer_id;if("string"==typeof l&&l===ep(this,ap,"f").peerId)return;const h=s.offer_id;"string"==typeof l&&"string"==typeof h&&($p(s.offer)?ep(this,sp,"m",Pp).call(this,{sdp:s.offer,peerId:l,offerId:h}).catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("signaling-failed",`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):$p(s.answer)&&ep(this,sp,"m",Dp).call(this,{sdp:s.answer,peerId:l,offerId:h}).catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("signaling-failed",`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))}),tp(this,ap,{infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:null!==(t=e.offerTimeout)&&void 0!==t?t:()=>5e4,offersCount:null!==(s=e.offersCount)&&void 0!==s?s:()=>5,iceGatheringTimeout:null!==(i=e.iceGatheringTimeout)&&void 0!==i?i:()=>5e3,connectionTimeout:null!==(r=e.connectionTimeout)&&void 0!==r?r:()=>15e3,claimPeer:null!==(n=e.claimPeer)&&void 0!==n?n:()=>!0,shouldGenerateOffers:null!==(a=e.shouldGenerateOffers)&&void 0!==a?a:()=>!0},"f"),tp(this,op,e.wsClient,"f")}addEventListener(e,t){ep(this,lp,"f").addEventListener(e,t)}removeEventListener(e,t){ep(this,lp,"f").removeEventListener(e,t)}start(){ep(this,sp,"m",Sp).call(this)||ep(this,yp,"f")||(tp(this,yp,!0,"f"),ep(this,op,"f").addEventListener("connected",ep(this,bp,"f")),ep(this,op,"f").addEventListener("disconnected",ep(this,Tp,"f")),ep(this,op,"f").addEventListener("message",ep(this,wp,"f")),"connected"===ep(this,op,"f").state&&ep(this,bp,"f").call(this))}destroy(){ep(this,sp,"m",Sp).call(this)||(ep(this,cp,"f").abort(),ep(this,sp,"m",Lp).call(this),ep(this,sp,"m",Rp).call(this),ep(this,sp,"m",xp).call(this),ep(this,sp,"m",Fp).call(this),ep(this,yp,"f")&&(ep(this,op,"f").removeEventListener("connected",ep(this,bp,"f")),ep(this,op,"f").removeEventListener("disconnected",ep(this,Tp,"f")),ep(this,op,"f").removeEventListener("message",ep(this,wp,"f"))),ep(this,lp,"f").clear())}},ap=new WeakMap,op=new WeakMap,lp=new WeakMap,hp=new WeakMap,dp=new WeakMap,cp=new WeakMap,up=new WeakMap,fp=new WeakMap,gp=new WeakMap,mp=new WeakMap,pp=new WeakMap,vp=new WeakMap,yp=new WeakMap,bp=new WeakMap,Tp=new WeakMap,wp=new WeakMap,sp=new WeakSet,Sp=function(){return ep(this,cp,"f").signal.aborted},Ep=function(){if(ep(this,cp,"f").signal.aborted)throw new Error("Client destroyed")},Ip=function(e){var t;ep(this,sp,"m",Lp).call(this),tp(this,fp,e,"f");const s=tp(this,gp,(t=ep(this,gp,"f"),++t),"f"),i=()=>Zm(this,void 0,void 0,function*(){try{yield ep(this,sp,"m",Ap).call(this)}catch(e){if(ep(this,sp,"m",Sp).call(this))return;ep(this,lp,"f").dispatchEvent("error",new lf("announce-failed",`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}ep(this,sp,"m",Sp).call(this)||null===ep(this,fp,"f")||ep(this,gp,"f")!==s||tp(this,up,setTimeout(i,1e3*ep(this,fp,"f")),"f")});tp(this,up,setTimeout(i,1e3*e),"f")},Lp=function(){null!==ep(this,up,"f")&&(clearTimeout(ep(this,up,"f")),tp(this,up,null,"f"))},Ap=function(e){return Zm(this,void 0,void 0,function*(){if(ep(this,sp,"m",Sp).call(this)||"connected"!==ep(this,op,"f").state)return;if(e&&tp(this,pp,e,"f"),ep(this,mp,"f"))return ep(this,mp,"f");const t=(()=>Zm(this,void 0,void 0,function*(){const e=ep(this,ap,"f").shouldGenerateOffers()?ep(this,ap,"f").offersCount():0,t=yield Promise.all(Array.from({length:e},()=>ep(this,sp,"m",kp).call(this)));if(ep(this,sp,"m",Sp).call(this)){for(const e of t)e&&ep(this,sp,"m",Op).call(this,e.offer_id);return}const s=[];for(const e of t)e&&s.push(e);const i=ep(this,pp,"f");tp(this,pp,void 0,"f");const r=ep(this,sp,"m",Cp).call(this,{numwant:s.length,offers:s,event:i});if("connected"===ep(this,op,"f").state)try{ep(this,op,"f").send(JSON.stringify(r))}catch(e){for(const e of s)ep(this,sp,"m",Op).call(this,e.offer_id);throw e}else for(const e of s)ep(this,sp,"m",Op).call(this,e.offer_id)}))();tp(this,mp,t,"f");try{yield t}finally{ep(this,mp,"f")===t&&tp(this,mp,null,"f")}})},kp=function(){return Zm(this,void 0,void 0,function*(){var e,t;if(ep(this,sp,"m",Sp).call(this))return;let s;try{s=new Hm(null===(t=(e=ep(this,ap,"f")).rtcConfig)||void 0===t?void 0:t.call(e)),ep(this,dp,"f").add(s);const i=s.createDataChannel("webtorrent",ep(this,ap,"f").channelConfig),r=yield function(e,t){return qm?e.createOffer(t):new Promise((s,i)=>{try{e.createOffer(s,i,t)}catch(e){i(e)}})}(s);ep(this,sp,"m",Ep).call(this),yield Xm(s,r),ep(this,sp,"m",Ep).call(this),yield ep(this,sp,"m",Mp).call(this,s),ep(this,sp,"m",Ep).call(this);const n=s.localDescription;if(!(null==n?void 0:n.sdp))return void s.close();const a=function(){let e="";for(let t=0;t<20;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e}();return ep(this,hp,"f").set(a,{connection:s,channel:i,timeoutId:setTimeout(()=>{ep(this,sp,"m",Op).call(this,a)},ep(this,ap,"f").offerTimeout())}),{offer:{type:n.type,sdp:n.sdp},offer_id:a}}catch(e){null==s||s.close(),ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("warning",new hf("offer-failed",`Failed to create offer: ${e instanceof Error?e.message:String(e)}`,e))}finally{s&&ep(this,dp,"f").delete(s)}})},Rp=function(){if("connected"!==ep(this,op,"f").state)return;const e=ep(this,sp,"m",Cp).call(this,{numwant:0,offers:[],event:"stopped"});try{ep(this,op,"f").send(JSON.stringify(e))}catch(e){}},Cp=function({numwant:e,offers:t,event:s}){const i={action:"announce",info_hash:ep(this,ap,"f").infoHash,peer_id:ep(this,ap,"f").peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return s&&(i.event=s),ep(this,vp,"f")&&(i.trackerid=ep(this,vp,"f")),i},Pp=function(e){return Zm(this,arguments,void 0,function*({sdp:e,peerId:t,offerId:s}){var i,r;if(ep(this,sp,"m",Sp).call(this))return;if(!ep(this,ap,"f").claimPeer(t))return;let n;try{n=new Hm(null===(r=(i=ep(this,ap,"f")).rtcConfig)||void 0===r?void 0:r.call(i)),ep(this,dp,"f").add(n),yield Jm(n,new Wm(e)),ep(this,sp,"m",Ep).call(this);const a=yield function(e,t){return qm?e.createAnswer(t):new Promise((s,i)=>{try{e.createAnswer(s,i,t)}catch(e){i(e)}})}(n);ep(this,sp,"m",Ep).call(this),yield Xm(n,a),ep(this,sp,"m",Ep).call(this),yield ep(this,sp,"m",Mp).call(this,n),ep(this,sp,"m",Ep).call(this);const o=n.localDescription;if(!o)throw new Error("Failed to get local description after ICE gathering");const l={action:"announce",info_hash:ep(this,ap,"f").infoHash,peer_id:ep(this,ap,"f").peerId,to_peer_id:t,offer_id:s,answer:{type:o.type,sdp:o.sdp}};ep(this,op,"f").send(JSON.stringify(l));const h=yield ep(this,sp,"m",_p).call(this,n);ep(this,sp,"m",Ep).call(this),ep(this,lp,"f").dispatchEvent("peerConnected",{peerId:t,connection:n,channel:h})}catch(e){null==n||n.close(),ep(this,lp,"f").dispatchEvent("peerConnectFailed",{peerId:t,error:new df("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{n&&ep(this,dp,"f").delete(n)}})},Dp=function(e){return Zm(this,arguments,void 0,function*({sdp:e,peerId:t,offerId:s}){if(ep(this,sp,"m",Sp).call(this))return;const i=ep(this,hp,"f").get(s);if(i)if(ep(this,hp,"f").delete(s),clearTimeout(i.timeoutId),ep(this,ap,"f").claimPeer(t)){ep(this,dp,"f").add(i.connection);try{yield Jm(i.connection,new Wm(e)),ep(this,sp,"m",Ep).call(this);const s=yield ep(this,sp,"m",_p).call(this,i.connection,i.channel);ep(this,sp,"m",Ep).call(this),ep(this,lp,"f").dispatchEvent("peerConnected",{peerId:t,connection:i.connection,channel:s})}catch(e){i.connection.close(),ep(this,lp,"f").dispatchEvent("peerConnectFailed",{peerId:t,error:new df("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{ep(this,dp,"f").delete(i.connection)}}else i.connection.close()})},Mp=function(e){return new Promise((t,s)=>{if("complete"===e.iceGatheringState)return void t();if("closed"===e.signalingState)return void s(new Error("RTCPeerConnection closed"));let i;const r=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",n),e.removeEventListener("icecandidate",a),e.removeEventListener("signalingstatechange",o),ep(this,cp,"f").signal.removeEventListener("abort",l)},n=()=>{"complete"===e.iceGatheringState&&(r(),t())},a=e=>{null===e.candidate&&(r(),t())},o=()=>{"closed"===e.signalingState&&(r(),s(new Error("RTCPeerConnection closed")))},l=()=>{r(),s(new Error("ICE gathering aborted due to teardown"))};ep(this,cp,"f").signal.aborted?l():(i=setTimeout(()=>{r(),t()},ep(this,ap,"f").iceGatheringTimeout()),e.addEventListener("icegatheringstatechange",n),e.addEventListener("icecandidate",a),e.addEventListener("signalingstatechange",o),ep(this,cp,"f").signal.addEventListener("abort",l))})},_p=function(e,t){const{promise:s,resolve:i,reject:r}=Df();let n,a=t;const o=()=>!!Bg(e.iceConnectionState)&&(g(),r(new Error(`ICE connection ${e.iceConnectionState}`)),!0),l=()=>{g(),a?i(a):r(new Error("Data channel missing on open"))},h=()=>{g(),r(new Error("Data channel error"))},d=()=>{g(),r(new Error("Data channel closed prematurely"))},c=e=>{a=e,"open"===e.readyState?l():"closed"===e.readyState||"closing"===e.readyState?d():(e.addEventListener("open",l),e.addEventListener("error",h),e.addEventListener("close",d),e.addEventListener("closing",d))},u=e=>{a||c(e.channel)},f=()=>{g(),r(new Error("Connection aborted due to teardown"))},g=()=>{clearTimeout(n),e.removeEventListener("iceconnectionstatechange",o),e.removeEventListener("datachannel",u),a&&(a.removeEventListener("open",l),a.removeEventListener("error",h),a.removeEventListener("close",d),a.removeEventListener("closing",d)),ep(this,cp,"f").signal.removeEventListener("abort",f)};return ep(this,cp,"f").signal.aborted?(f(),s):(o()||(n=setTimeout(()=>{g(),r(new Error("Data channel open timeout"))},ep(this,ap,"f").connectionTimeout()),e.addEventListener("iceconnectionstatechange",o),ep(this,cp,"f").signal.addEventListener("abort",f),a?c(a):e.addEventListener("datachannel",u)),s)},Op=function(e,t){const s=null!=t?t:ep(this,hp,"f").get(e);s&&(clearTimeout(s.timeoutId),s.connection.close(),ep(this,hp,"f").delete(e))},xp=function(){for(const[e,t]of ep(this,hp,"f"))ep(this,sp,"m",Op).call(this,e,t)},Fp=function(){for(const e of ep(this,dp,"f"))e.close();ep(this,dp,"f").clear()},rp={value:120},np={value:20}}}),sv=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-manager/index.js"(){If(),Qm(),jm(),tv(),Gp=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Hp=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},ev=class{constructor(e){var t,s;Wp.add(this),qp.set(this,void 0),jp.set(this,new Fm),Kp.set(this,new Set),Vp.set(this,new Map),Yp.set(this,new Set),zp.set(this,!1),Qp.set(this,!1),Xp.set(this,e=>{if(Hp(this,zp,"f"))return!1;if(Hp(this,Kp,"f").has(e)||Hp(this,Vp,"f").has(e))return!1;const t=Math.floor(Hp(this,qp,"f").maxPeers()*Math.max(1,Hp(this,qp,"f").maxPeersMultiplier()));return!(Hp(this,Kp,"f").size+Hp(this,Vp,"f").size>=t||(Hp(this,Kp,"f").add(e),0))}),Gp(this,qp,Object.assign(Object.assign({},e),{maxPeers:null!==(t=e.maxPeers)&&void 0!==t?t:()=>50,maxPeersMultiplier:null!==(s=e.maxPeersMultiplier)&&void 0!==s?s:()=>1.5}),"f")}addEventListener(e,t){Hp(this,jp,"f").addEventListener(e,t)}removeEventListener(e,t){Hp(this,jp,"f").removeEventListener(e,t)}start(){if(!Hp(this,zp,"f")&&!Hp(this,Qp,"f")){Gp(this,Qp,!0,"f");try{for(const e of Hp(this,qp,"f").trackerUrls){const{client:t,release:s}=Hp(this,qp,"f").socketPool.acquire(e);let i=!1;try{const r=new Up({infoHash:Hp(this,qp,"f").infoHash,peerId:Hp(this,qp,"f").peerId,wsClient:t,rtcConfig:Hp(this,qp,"f").rtcConfig,channelConfig:Hp(this,qp,"f").channelConfig,claimPeer:Hp(this,Xp,"f"),offersCount:Hp(this,qp,"f").offersCount,offerTimeout:Hp(this,qp,"f").offerTimeout,iceGatheringTimeout:Hp(this,qp,"f").iceGatheringTimeout,connectionTimeout:Hp(this,qp,"f").connectionTimeout,shouldGenerateOffers:()=>Hp(this,Kp,"f").size+Hp(this,Vp,"f").size<Hp(this,qp,"f").maxPeers()}),n=t=>{Hp(this,Kp,"f").delete(t.peerId),Hp(this,Wp,"m",Zp).call(this,t.peerId,t.connection,t.channel,e)},a=t=>{Hp(this,Kp,"f").has(t.peerId)&&(Hp(this,Kp,"f").delete(t.peerId),Hp(this,jp,"f").dispatchEvent("peerConnectFailed",{peerId:t.peerId,trackerUrl:e,error:t.error}))},o=t=>{Hp(this,jp,"f").dispatchEvent("warning",{trackerUrl:e,warning:t})},l=t=>{Hp(this,jp,"f").dispatchEvent("error",{trackerUrl:e,error:t})};r.addEventListener("peerConnected",n),r.addEventListener("peerConnectFailed",a),r.addEventListener("warning",o),r.addEventListener("error",l);const h=()=>{r.removeEventListener("peerConnected",n),r.removeEventListener("peerConnectFailed",a),r.removeEventListener("warning",o),r.removeEventListener("error",l)};Hp(this,Yp,"f").add({client:r,releaseSocket:s,cleanupListeners:h}),i=!0,r.start()}catch(e){throw i||s(),e}}}catch(e){throw this.destroy(),e}}}destroy(){if(Hp(this,zp,"f"))return;Gp(this,zp,!0,"f");for(const{client:e,releaseSocket:t,cleanupListeners:s}of Hp(this,Yp,"f"))s(),e.destroy(),t();Hp(this,Yp,"f").clear(),Hp(this,Kp,"f").clear();const e=[...Hp(this,Vp,"f").entries()];Hp(this,Vp,"f").clear();for(const[t,s]of e){s.cleanup();try{s.channel.close()}catch(e){}try{s.connection.close()}catch(e){}Hp(this,jp,"f").dispatchEvent("peerDisconnected",{peerId:t,trackerUrl:s.trackerUrl,disconnectReason:"Manager destroyed"})}Hp(this,jp,"f").clear()}},qp=new WeakMap,jp=new WeakMap,Kp=new WeakMap,Vp=new WeakMap,Yp=new WeakMap,zp=new WeakMap,Qp=new WeakMap,Xp=new WeakMap,Wp=new WeakSet,Jp=function(e,t){if(Hp(this,zp,"f"))return;const s=Hp(this,Vp,"f").get(e);if(s){Hp(this,Vp,"f").delete(e),s.cleanup();try{s.channel.close()}catch(e){}try{s.connection.close()}catch(e){}Hp(this,jp,"f").dispatchEvent("peerDisconnected",Object.assign({peerId:e,trackerUrl:s.trackerUrl},t))}},Zp=function(e,t,s,i){if(Bg(t.iceConnectionState)){try{t.close()}catch(e){}return void Hp(this,jp,"f").dispatchEvent("peerConnectFailed",{peerId:e,trackerUrl:i,error:new df("connection-failed","Connection failed during promotion")})}const r=t=>Hp(this,Wp,"m",Jp).call(this,e,t),n=()=>{Bg(t.iceConnectionState)&&r({error:new af("connection-lost",`ICE connection state became ${t.iceConnectionState}`)})},a=()=>r({disconnectReason:"Data channel closed"}),o=()=>r({disconnectReason:"Data channel closing"}),l=e=>{const t=Fg(e,"Data channel error");r({error:new af("transport-error",`Data channel error: ${t}`)})};let h=t=>Hp(this,Wp,"m",Jp).call(this,e,t?{error:t}:{disconnectReason:"Closed by consumer"});Hp(this,Vp,"f").set(e,{connection:t,channel:s,trackerUrl:i,cleanup:()=>{h=null,t.removeEventListener("iceconnectionstatechange",n),s.removeEventListener("close",a),s.removeEventListener("closing",o),s.removeEventListener("error",l)}}),t.addEventListener("iceconnectionstatechange",n),s.addEventListener("close",a),s.addEventListener("closing",o),s.addEventListener("error",l),Hp(this,jp,"f").dispatchEvent("peerConnected",{peerId:e,connection:t,channel:s,trackerUrl:i,close:e=>null==h?void 0:h(e)})}}});function iv(e){const t=(s=e,(new TextEncoder).encode(s));var s;const i=[],r=8*t.length;for(let e=0;e<t.length;e++)i[e>>2]|=(255&t[e])<<24-e%4*8;i[r>>5]|=128<<24-r%32,i[15+(r+64>>9<<4)]=r;let n=1732584193,a=4023233417,o=2562383102,l=271733878,h=3285377520;const d=[];for(let e=0;e<i.length;e+=16){const t=n,s=a,r=o,c=l,u=h;for(let t=0;t<80;t++){if(t<16)d[t]=0|i[e+t];else{const e=d[t-3]^d[t-8]^d[t-14]^d[t-16];d[t]=e<<1|e>>>31}let s;s=t<20?1518500249+(a&o|~a&l):t<40?1859775393+(a^o^l):t<60?(a&o|a&l|o&l)-1894007588:(a^o^l)-899497514;const r=(n<<5|n>>>27)+h+(d[t]>>>0)+s|0;h=l,l=o,o=a<<30|a>>>2,a=n,n=r}n=n+t|0,a=a+s|0,o=o+r|0,l=l+c|0,h=h+u|0}let c="";const u=[n,a,o,l,h];for(let e=0;e<20;e++){const t=24-e%4*8,s=u[e>>2];c+=String.fromCharCode(s>>>t&255)}return c}var rv,nv=o({"../../node_modules/p2p-media-loader-core/lib/utils/hash.js"(){zf()}});function av({bitrate:e,codecs:t,width:s,height:i,language:r,channels:n,name:a,frameRate:o,videoRange:l}){const h=t?t.split(",").map(e=>{const t=(e=e.trim().toLowerCase()).split(".");if(3===t.length&&("avc1"===t[0]||"avc"===t[0])){const s=parseInt(t[1],10),i=parseInt(t[2],10);if(!isNaN(s)&&!isNaN(i)&&t[1]===s.toString()&&t[2]===i.toString()){const r=`00${s.toString(16)}`.slice(-2),n=`00${i.toString(16)}`.slice(-2);e=`${t[0]}.${r}00${n}`}}return e}).sort().join(","):"",d=r&&"und"!==r?r.slice(0,2).toLowerCase():"",c=n?n.toString().split("/")[0]:"",u=a?a.toLowerCase().trim():"",f=o&&!isNaN(Number(o))?Number(o).toString():"",g=l?l.toUpperCase().trim():"";return btoa(iv(`${null!=e?e:0}-${h}-${null!=s?s:""}-${null!=i?i:""}-${d}-${c}-${u}-${f}-${g}`))}function ov(e,t){return`${rv}-${e}-${function(e){return`${e.type}-${e.index}`}(t)}`}function lv(e,t){for(const s of e.values()){const e=s.segments.get(t);if(e)return e}}function hv(e,t,s,i,r){const{highDemandTimeWindow:n,httpDownloadTimeWindow:a,p2pDownloadTimeWindow:o}=function(e,t){const{highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r}=e,n={highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r};return t<=5?(n.httpDownloadTimeWindow=0,n.p2pDownloadTimeWindow=0):t<=10&&(n.p2pDownloadTimeWindow=n.httpDownloadTimeWindow),n}(s,r);return{isHighDemand:dv(e,t,n),isHttpDownloadable:dv(e,t,a),isP2PDownloadable:dv(e,t,o)&&i.isSegmentLoadingOrLoadedBySomeone(e)}}function dv(e,t,s){const{startTime:i,endTime:r}=e,{position:n,rate:a}=t;return!(n+s*a<i||n>r)}var cv,uv,fv,gv,mv=o({"../../node_modules/p2p-media-loader-core/lib/utils/stream.js"(){nv(),rv="v2"}}),pv=o({"../../node_modules/p2p-media-loader-core/lib/utils/version.js"(){cv="3.0.1"}});function vv(e){return btoa(iv(e).slice(0,15))}var yv,Sv,Ev,bv,Tv,wv,Iv,Lv,Av,kv,Rv,Cv,Pv,Dv,Mv,_v,Ov,xv,Fv,Bv,Uv,Nv,$v,Gv,Hv,Wv,qv,jv,Kv,Vv,Yv,zv,Qv,Xv,Jv,Zv,ey,ty=o({"../../node_modules/p2p-media-loader-core/lib/utils/peer.js"(){nv(),pv(),uv=`-PM${function(){const e=cv.split(".");return`${`00${e[0]}`.slice(-2)}${`00${e[1]}`.slice(-2)}`}()}-`,fv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",gv=20}});function sy(e){if(1===e.length)return e[0];let t=0;for(const s of e){const e=s.getDownloadBandwidth();e>t&&(t=e)}if(t>0){const s=Math.max(1,.1*t);let i=0,r=0;for(const t of e)t.getDownloadBandwidth()<=s?i++:r+=t.getDownloadBandwidth();let n=s;return i>0&&r>0&&i*s>r&&(n=r/i),function(e){if(0===e.length)throw new Error("Cannot get item from empty array");if(1===e.length)return e[0];let t=0;const s=e.map(e=>{const s=(i=e,Math.max(i.getDownloadBandwidth(),n));var i;return t+=s,s});let i=Math.random()*t;for(let t=0;t<e.length;t++)if(i-=s[t],i<=0)return e[t];return e[e.length-1]}(e)}return(s=e)[Math.floor(Math.random()*s.length)];var s}var iy=o({"../../node_modules/p2p-media-loader-core/lib/p2p/loader.js"(){zm(),sv(),mv(),zf(),ty(),yv=d(Cf(),1),Sv=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ev=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},bv=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},ey=class{constructor(e,t,s,i,r,n,a,o,l){var h;Tv.add(this),wv.set(this,void 0),Iv.set(this,new Map),Lv.set(this,void 0),Av.set(this,void 0),kv.set(this,!1),Rv.set(this,(0,yv.default)("p2pml-core:webtorrent-manager")),Cv.set(this,(0,yv.default)("p2pml-core:churn-cleanup")),Pv.set(this,void 0),Dv.set(this,void 0),Mv.set(this,void 0),_v.set(this,void 0),Ov.set(this,void 0),xv.set(this,void 0),Fv.set(this,void 0),Bv.set(this,void 0),Uv.set(this,void 0),Nv.set(this,void 0),$v.set(this,void 0),Gv.set(this,void 0),Hv.set(this,void 0),Wv.set(this,void 0),qv.set(this,void 0),jv.set(this,void 0),Kv.set(this,void 0),Vv.set(this,void 0),Yv.set(this,()=>{Ev(this,Nv,setTimeout(bv(this,Yv,"f"),Math.max(1e3,bv(this,xv,"f").p2pChurnCleanupIntervalMs)),"f");const e=bv(this,Iv,"f").size-bv(this,xv,"f").p2pMaxPeers;if(e<=0)return;const t=[],s=performance.now();for(const e of bv(this,Iv,"f").values())e.downloadingSegment||e.isUploadingSegment||s-e.connectedAt<bv(this,xv,"f").p2pChurnGracePeriodMs||t.push(e);if(0===t.length)return;t.sort((e,t)=>e.getDownloadBandwidth()-t.getDownloadBandwidth()||e.connectedAt-t.connectedAt);const i=t.slice(0,e);bv(this,Cv,"f").call(this,`Background churn cleanup: dropping ${i.length} excess peers (total: ${bv(this,Iv,"f").size}, target: ${bv(this,xv,"f").p2pMaxPeers}, eligible: ${t.length})`);for(const e of i)bv(this,Cv,"f").call(this,`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()}),Qv.set(this,e=>{if(bv(this,Rv,"f").call(this,`peerConnected: peerId=${e.peerId}`),bv(this,Iv,"f").has(e.peerId))return void e.close();const t=new xm(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,s,i)=>{bv(this,Zv,"f").call(this,e,t,s,i).catch(s=>{bv(this,Rv,"f").call(this,`Error in onSegmentRequested ${t} for peer ${e.id}:`,s)})},onSegmentsAnnouncement:(t,s)=>{bv(this,Vv,"f").call(this,e.peerId,bv(this,Pv,"f"),bv(this,Mv,"f").type,t,s),bv(this,Uv,"f").call(this)},onWarning:e=>{bv(this,qv,"f").call(this,{peerId:t.id,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:bv(this,xv,"f").p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:bv(this,xv,"f").webRtcMaxMessageSize,p2pErrorRetries:bv(this,xv,"f").p2pErrorRetries,validateP2PSegment:bv(this,xv,"f").validateP2PSegment,streamType:bv(this,Mv,"f").type,infoHash:bv(this,Pv,"f")},bv(this,Bv,"f"));if(bv(this,Iv,"f").set(e.peerId,t),bv(this,$v,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type}),bv(this,xv,"f").isP2PUploadDisabled)return;const{httpLoading:s,loaded:i}=bv(this,Tv,"m",zv).call(this);t.sendSegmentsAnnouncementCommand(i,s)}),Xv.set(this,e=>{var t;bv(this,Rv,"f").call(this,"peerDisconnected: peerId=%s error=%s reason=%s",e.peerId,null===(t=e.error)||void 0===t?void 0:t.message,e.disconnectReason);const s=bv(this,Iv,"f").get(e.peerId);s&&(bv(this,Iv,"f").delete(e.peerId),s.destroy(!0),e.error&&bv(this,Wv,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,error:e.error}),bv(this,Hv,"f").call(this,{peerId:s.id,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type}))}),Object.defineProperty(this,"broadcastAnnouncement",{enumerable:!0,configurable:!0,writable:!0,value:(e=!1)=>{e?bv(this,Jv,"f").call(this,e):bv(this,kv,"f")||bv(this,xv,"f").isP2PUploadDisabled||bv(this,Jv,"f").call(this)}}),Jv.set(this,(e=!1)=>{Ev(this,kv,!0,"f"),Mf(()=>{const{loaded:t=[],httpLoading:s=[]}=e?{}:bv(this,Tv,"m",zv).call(this);for(const e of bv(this,Iv,"f").values())e.sendSegmentsAnnouncementCommand(t,s);Ev(this,kv,!1,"f")})}),Zv.set(this,(e,t,s,i)=>Sv(this,void 0,void 0,function*(){const r=function(e,t){for(const s of e.segments.values())if(s.externalId===t)return s}(bv(this,Mv,"f"),t);if(!r)return;if(bv(this,xv,"f").isP2PUploadDisabled)return void e.sendSegmentAbsentCommand(t,s);let n;try{n=yield bv(this,Ov,"f").getSegmentData(bv(this,Lv,"f"),bv(this,Av,"f"),r.externalId)}catch(s){bv(this,Rv,"f").call(this,`Storage error for segment ${t} requested by peer ${e.id}:`,s)}!bv(this,Iv,"f").has(e.id)||(n?yield e.uploadSegmentData(r,s,void 0!==i?new Uint8Array(n).subarray(i):n):e.sendSegmentAbsentCommand(t,s))})),Ev(this,Dv,e,"f"),Ev(this,Mv,t,"f"),Ev(this,_v,s,"f"),Ev(this,Ov,i,"f"),Ev(this,xv,r,"f"),Ev(this,Fv,n,"f"),Ev(this,Bv,a,"f"),Ev(this,Uv,l,"f"),Ev(this,$v,a.getEventDispatcher("onPeerConnect"),"f"),Ev(this,Gv,a.getEventDispatcher("onPeerConnectError"),"f"),Ev(this,Hv,a.getEventDispatcher("onPeerClose"),"f"),Ev(this,Wv,a.getEventDispatcher("onPeerError"),"f"),Ev(this,qv,a.getEventDispatcher("onPeerWarning"),"f"),Ev(this,jv,a.getEventDispatcher("onTrackerWarning"),"f"),Ev(this,Kv,a.getEventDispatcher("onTrackerError"),"f"),Ev(this,Vv,a.getEventDispatcher("onPeerSegmentsAnnouncement"),"f"),Ev(this,Lv,null!==(h=bv(this,xv,"f").swarmId)&&void 0!==h?h:bv(this,Dv,"f"),"f"),Ev(this,Av,ov(bv(this,Lv,"f"),bv(this,Mv,"f")),"f");const d=vv(bv(this,Av,"f"));Ev(this,Pv,d,"f"),Ev(this,wv,new ev({infoHash:d,peerId:o,trackerUrls:bv(this,xv,"f").announceTrackers,rtcConfig:()=>bv(this,xv,"f").rtcConfig,socketPool:bv(this,Fv,"f"),maxPeers:()=>bv(this,xv,"f").p2pMaxPeers,maxPeersMultiplier:()=>bv(this,xv,"f").p2pChurnMaxPeersMultiplier,offersCount:()=>bv(this,xv,"f").webRtcOffersCount,offerTimeout:()=>bv(this,xv,"f").webRtcOfferTimeoutMs,iceGatheringTimeout:()=>bv(this,xv,"f").webRtcIceGatheringTimeoutMs,connectionTimeout:()=>bv(this,xv,"f").webRtcConnectionTimeoutMs}),"f"),bv(this,wv,"f").addEventListener("peerConnected",bv(this,Qv,"f")),bv(this,wv,"f").addEventListener("peerDisconnected",bv(this,Xv,"f")),bv(this,wv,"f").addEventListener("peerConnectFailed",e=>{bv(this,Rv,"f").call(this,`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),bv(this,Gv,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,trackerUrl:e.trackerUrl,error:e.error})}),bv(this,wv,"f").addEventListener("warning",e=>{bv(this,Rv,"f").call(this,`Tracker warning (${e.trackerUrl}):`,e.warning),bv(this,jv,"f").call(this,{trackerUrl:e.trackerUrl,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,warning:e.warning})}),bv(this,wv,"f").addEventListener("error",e=>{bv(this,Rv,"f").call(this,`Tracker error (${e.trackerUrl}):`,e.error),bv(this,Kv,"f").call(this,{trackerUrl:e.trackerUrl,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,error:e.error})}),bv(this,Bv,"f").addEventListener(`onStorageUpdated-${bv(this,Av,"f")}`,this.broadcastAnnouncement),bv(this,wv,"f").start(),Ev(this,Nv,setTimeout(bv(this,Yv,"f"),Math.max(1e3,bv(this,xv,"f").p2pChurnCleanupIntervalMs)),"f")}downloadSegment(e){const t=[];for(const s of bv(this,Iv,"f").values())s.downloadingSegment||"loaded"!==s.getSegmentStatus(e)||t.push(s);if(0===t.length)return;const s=sy(t),i=bv(this,_v,"f").getOrCreateRequest(e);s.downloadSegment(i)}isSegmentLoadingOrLoadedBySomeone(e){for(const t of bv(this,Iv,"f").values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(const t of bv(this,Iv,"f").values())if("loaded"===t.getSegmentStatus(e))return!0;return!1}get connectedPeerCount(){return bv(this,Iv,"f").size}*peers(){for(const e of bv(this,Iv,"f").values())yield e}destroy(){clearTimeout(bv(this,Nv,"f")),Ev(this,Nv,void 0,"f"),bv(this,Bv,"f").removeEventListener(`onStorageUpdated-${bv(this,Av,"f")}`,this.broadcastAnnouncement),bv(this,wv,"f").destroy();for(const e of bv(this,Iv,"f").values())e.destroy();bv(this,Iv,"f").clear()}},wv=new WeakMap,Iv=new WeakMap,Lv=new WeakMap,Av=new WeakMap,kv=new WeakMap,Rv=new WeakMap,Cv=new WeakMap,Pv=new WeakMap,Dv=new WeakMap,Mv=new WeakMap,_v=new WeakMap,Ov=new WeakMap,xv=new WeakMap,Fv=new WeakMap,Bv=new WeakMap,Uv=new WeakMap,Nv=new WeakMap,$v=new WeakMap,Gv=new WeakMap,Hv=new WeakMap,Wv=new WeakMap,qv=new WeakMap,jv=new WeakMap,Kv=new WeakMap,Vv=new WeakMap,Yv=new WeakMap,Qv=new WeakMap,Xv=new WeakMap,Jv=new WeakMap,Zv=new WeakMap,Tv=new WeakSet,zv=function(){const e=bv(this,Ov,"f").getStoredSegmentIds(bv(this,Lv,"f"),bv(this,Av,"f")),t=[];for(const e of bv(this,_v,"f").httpRequests()){const s=bv(this,Mv,"f").segments.get(e.segment.runtimeId);s&&t.push(s.externalId)}return{loaded:e,httpLoading:t}}}});function ry(e){return`${e.type}-${e.index}`}function ny(e){const{externalId:t}=e;return`(${ry(e.stream)} | ${t})`}var ay,oy,ly,hy,dy,cy,uy,fy,gy,my,py,vy,yy,Sy,Ey,by,Ty,wy,Iy,Ly,Ay,ky,Ry,Cy,Py,Dy=o({"../../node_modules/p2p-media-loader-core/lib/utils/logger.js"(){}}),My=o({"../../node_modules/p2p-media-loader-core/lib/p2p/loaders-container.js"(){iy(),ay=d(Cf(),1),Dy(),mv(),oy=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},ly=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},Ly=class{constructor(e,t,s,i,r,n,a,o,l){hy.add(this),dy.set(this,new Map),cy.set(this,void 0),uy.set(this,(0,ay.default)("p2pml-core:p2p-loaders-container")),fy.set(this,void 0),gy.set(this,void 0),my.set(this,void 0),py.set(this,void 0),vy.set(this,void 0),yy.set(this,void 0),Sy.set(this,void 0),Ey.set(this,void 0),oy(this,fy,e,"f"),oy(this,gy,s,"f"),oy(this,my,i,"f"),oy(this,py,r,"f"),oy(this,vy,n,"f"),oy(this,yy,a,"f"),oy(this,Sy,o,"f"),oy(this,Ey,l,"f"),oy(this,cy,ly(this,hy,"m",Ty).call(this,t),"f"),ly(this,uy,"f").call(this,`set current p2p loader: ${ry(t)}`)}changeCurrentLoader(e){var t;const s=null!==(t=ly(this,py,"f").swarmId)&&void 0!==t?t:ly(this,fy,"f"),i=ov(s,ly(this,cy,"f").stream);ly(this,my,"f").getStoredSegmentIds(s,i).length?ly(this,hy,"m",wy).call(this,ly(this,cy,"f")):ly(this,hy,"m",Iy).call(this,ly(this,cy,"f")),oy(this,cy,ly(this,hy,"m",Ty).call(this,e),"f"),ly(this,uy,"f").call(this,`change current p2p loader: ${ry(e)}`)}get currentLoader(){return ly(this,cy,"f").loader}destroy(){for(const{loader:e,destroyTimeoutId:t}of ly(this,dy,"f").values())e.destroy(),clearTimeout(t);ly(this,dy,"f").clear()}},dy=new WeakMap,cy=new WeakMap,uy=new WeakMap,fy=new WeakMap,gy=new WeakMap,my=new WeakMap,py=new WeakMap,vy=new WeakMap,yy=new WeakMap,Sy=new WeakMap,Ey=new WeakMap,hy=new WeakSet,by=function(e){if(ly(this,dy,"f").has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new ey(ly(this,fy,"f"),e,ly(this,gy,"f"),ly(this,my,"f"),ly(this,py,"f"),ly(this,vy,"f"),ly(this,yy,"f"),ly(this,Sy,"f"),()=>{ly(this,cy,"f").loader===t&&ly(this,Ey,"f").call(this)}),s=ry(e);return ly(this,uy,"f").call(this,`created new loader: ${s}`),{loader:t,stream:e,loggerInfo:s}},Ty=function(e){const t=ly(this,dy,"f").get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{const t=ly(this,hy,"m",by).call(this,e);return ly(this,dy,"f").set(e.runtimeId,t),t}},wy=function(e){e.destroyTimeoutId=window.setTimeout(()=>ly(this,hy,"m",Iy).call(this,e),ly(this,py,"f").p2pInactiveLoaderDestroyTimeoutMs)},Iy=function(e){e.loader.destroy(),ly(this,dy,"f").delete(e.stream.runtimeId),ly(this,uy,"f").call(this,"destroy p2p loader: ",e.loggerInfo)}}});function _y(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}var Oy,xy,Fy=o({"../../node_modules/p2p-media-loader-core/lib/requests/request.js"(){Ay=d(Cf(),1),If(),zf(),ky=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ry=class{constructor(e,t,s,i,r,n,a){Object.defineProperty(this,"segment",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"requestProcessQueueCallback",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"playbackConfig",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"infoHash",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"currentAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_failedAttempts",{enumerable:!0,configurable:!0,writable:!0,value:new Cy}),Object.defineProperty(this,"finalData",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"bytes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_loadedBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_totalBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_status",{enumerable:!0,configurable:!0,writable:!0,value:"not-started"}),Object.defineProperty(this,"progress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"notReceivingBytesTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onAbortCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"notReceivingBytesTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isHandledByProcessQueue",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"onSegmentError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentAbort",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentLoaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:()=>{var e,t;if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress||void 0===this.notReceivingBytesTimeoutMs)return;const s=performance.now()-(null!==(e=this.progress.lastLoadedChunkTimestamp)&&void 0!==e?e:this.progress.startTimestamp);if(s<this.notReceivingBytesTimeoutMs)return void this.notReceivingBytesTimeout.restart(this.notReceivingBytesTimeoutMs-s);const i=new cf("bytes-receiving-timeout");null===(t=this._onAbortCallback)||void 0===t||t.call(this,i),this.handleFailure(i)}}),Object.defineProperty(this,"failWithError",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)}}),Object.defineProperty(this,"handleFailure",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.currentAttempt&&(this.setStatus("failed"),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add(Object.assign(Object.assign({},this.currentAttempt),{error:e})),this.onSegmentError({segment:_y(this.segment),error:e,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback())}}),Object.defineProperty(this,"completeOnSuccess",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear(),this.setStatus("succeed"),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,segment:_y(this.segment),bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())}}),Object.defineProperty(this,"addLoadedChunk",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;const{byteLength:t}=e,{all:s,http:i}=this.bandwidthCalculators;s.addBytes(t),"http"===this.currentAttempt.downloadSource&&i.addBytes(t),this.bytes.push(e),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=t,this._loadedBytes+=t}}),Object.defineProperty(this,"firstBytesReceived",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.throwErrorIfNotLoadingStatus()}}),this.onSegmentError=n.getEventDispatcher("onSegmentError"),this.onSegmentAbort=n.getEventDispatcher("onSegmentAbort"),this.onSegmentStart=n.getEventDispatcher("onSegmentStart"),this.onSegmentLoaded=n.getEventDispatcher("onSegmentLoaded");const{byteRange:o}=this.segment;if(o){const{end:e,start:t}=o;this._totalBytes=e-t+1}this.notReceivingBytesTimeout=new Py(this.abortOnTimeout);const{type:l}=this.segment.stream;this._logger=(0,Ay.default)(`p2pml-core:request-${l}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){var e;return null===(e=this.currentAttempt)||void 0===e?void 0:e.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){var e;return null!==(e=this.finalData)&&void 0!==e||(this.finalData=_f(this.bytes).buffer),this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(void 0!==this._totalBytes)throw new Error("Request total bytes value is already set");this._totalBytes=e}tryCompleteByLoadedBytes(e,t,s,i){if(!this._totalBytes)return!1;if(this._loadedBytes>this._totalBytes)return this.logger(`${e.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`),this.clearLoadedBytes(),!1;if(this._loadedBytes!==this._totalBytes)return!1;const r=this.start(e,t);return this.notReceivingBytesTimeout.clear(),s?this.validateAndComplete(e.downloadSource,r,s,i):r.completeOnSuccess(),!0}validateData(e){return ky(this,void 0,void 0,function*(){if(!e)return!0;try{return yield e(this.segment.url,this.segment.byteRange,this.data)}catch(e){return this.logger(`validation threw an error: ${String(e)}`),!1}})}validateAndComplete(e,t,s,i){return ky(this,void 0,void 0,function*(){const r=yield this.validateData(s);if("loading"===this._status){if(!r)return this.logger(`${e} ${this.segment.externalId} validation failed for already-loaded bytes, clearing`),this.clearLoadedBytes(),void t.failWithError(new cf(i));this.logger(`${e} ${this.segment.externalId} validation passed for already-loaded bytes`),t.completeOnSuccess()}})}start(e,t){if("succeed"===this._status)throw new Error(`Request ${this.segment.externalId} has been already succeed.`);if("loading"===this._status)throw new Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus("loading"),this.currentAttempt=Object.assign({},e),this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState("start");const{notReceivingBytesTimeoutMs:s}=t;return this._onAbortCallback=t.onAbort,this.notReceivingBytesTimeoutMs=s,void 0!==s&&this.notReceivingBytesTimeout.start(s),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:_y(this.segment),downloadSource:e.downloadSource,peerId:"p2p"===e.downloadSource?e.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,failWithError:this.failWithError}}cancel(){var e,t,s,i;this.throwErrorIfNotLoadingStatus(),this.setStatus("aborted"),this.logger(`${null===(e=this.currentAttempt)||void 0===e?void 0:e.downloadSource} ${this.segment.externalId} aborted`),null===(t=this._onAbortCallback)||void 0===t||t.call(this,new cf("abort")),this.onSegmentAbort({segment:_y(this.segment),downloadSource:null===(s=this.currentAttempt)||void 0===s?void 0:s.downloadSource,peerId:"p2p"===(null===(i=this.currentAttempt)||void 0===i?void 0:i.downloadSource)?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this._onAbortCallback=void 0,this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear()}throwErrorIfNotLoadingStatus(){if("loading"!==this._status)throw new Error(`Request has been already ${this.status}.`)}logger(e){var t;this._logger.color="http"===(null===(t=this.currentAttempt)||void 0===t?void 0:t.downloadSource)?"green":"red",this._logger(e),this._logger.color=""}manageBandwidthCalculatorsState(e){var t;const{all:s,http:i}=this.bandwidthCalculators,r="start"===e?"startLoading":"stopLoading";"http"===(null===(t=this.currentAttempt)||void 0===t?void 0:t.downloadSource)&&i[r](),s[r]()}},Cy=class{constructor(){Object.defineProperty(this,"attempts",{enumerable:!0,configurable:!0,writable:!0,value:[]})}add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>"http"===t.downloadSource?e+1:e,0)}get p2pAttemptsCount(){return this.attempts.reduce((e,t)=>"p2p"===t.downloadSource?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}},Py=class{constructor(e){Object.defineProperty(this,"action",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}start(e){if(this.timeoutId)throw new Error("Timeout is already started.");this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.clear(),void 0!==e&&(this.ms=e),void 0!==this.ms&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}}}}),By=o({"../../node_modules/p2p-media-loader-core/lib/requests/request-container.js"(){Fy(),mv(),ty(),Oy=class{constructor(e,t,s,i,r,n){Object.defineProperty(this,"requestProcessQueueCallback",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"swarmId",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"requests",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}get executingHttpCount(){let e=0;for(const t of this.httpRequests())"loading"===t.status&&e++;return e}get executingP2PCount(){let e=0;for(const t of this.p2pRequests())"loading"===t.status&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);if(!t){const s=vv(ov(this.swarmId,e.stream));t=new Ry(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,s),this.requests.set(e,t)}return t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(const e of this.requests.values())"http"===e.downloadSource&&(yield e)}*p2pRequests(){for(const e of this.requests.values())"p2p"===e.downloadSource&&(yield e)}destroy(){for(const e of this.requests.values())"loading"===e.status&&e.cancel();this.requests.clear()}}}}),Uy=o({"../../node_modules/p2p-media-loader-core/lib/requests/engine-request.js"(){If(),xy=class{constructor(e,t){Object.defineProperty(this,"segment",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"engineCallbacks",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"_status",{enumerable:!0,configurable:!0,writable:!0,value:"pending"}),Object.defineProperty(this,"_shouldBeStartedImmediately",{enumerable:!0,configurable:!0,writable:!0,value:!1})}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){"pending"===this._status&&(this._status="succeed",this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){"pending"===this._status&&(this._status="failed",this.engineCallbacks.onError(new uf("failed")))}abort(){"pending"===this._status&&(this._status="aborted",this.engineCallbacks.onError(new uf("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}}}});function*Ny(e,t,s,i,r){const{runtimeId:n,stream:a}=e,o=a.segments.get(n);if(!o)return;const l=a.segments.values();let h;do{const e=l.next();if(e.done)return;h=e.value}while(h!==o);const d=hv(h,t,s,i,r);if($y(d)){const e=l.next();if(e.done)return;const n=e.value,a=hv(n,t,s,i,r);if($y(a))return;d.isHighDemand=!0,yield{segment:h,statuses:d},yield{segment:n,statuses:a}}else yield{segment:h,statuses:d};for(const e of l){const n=hv(e,t,s,i,r);if($y(n))break;yield{segment:e,statuses:n}}}function $y(e){const{isHighDemand:t,isHttpDownloadable:s,isP2PDownloadable:i}=e;return!t&&!s&&!i}var Gy,Hy,Wy,qy,jy,Ky,Vy,Yy,zy,Qy,Xy,Jy,Zy,eS,tS,sS,iS,rS,nS,aS,oS,lS,hS,dS,cS,uS,fS,gS,mS,pS,vS,yS,SS,ES,bS,TS,wS,IS,LS,AS,kS,RS,CS,PS,DS,MS,_S,OS,xS,FS,BS,US,NS,$S,GS,HS,WS,qS,jS,KS,VS,YS,zS,QS=o({"../../node_modules/p2p-media-loader-core/lib/utils/queue.js"(){mv()}}),XS=o({"../../node_modules/p2p-media-loader-core/lib/hybrid-loader.js"(){Af(),My(),By(),Uy(),QS(),Dy(),mv(),zf(),Gy=d(Cf(),1),Hy=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Wy=class{constructor(e,t,s,i,r,n,a,o,l){var h;Object.defineProperty(this,"streamManifestUrl",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lastRequestedSegment",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"streamDetails",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"segmentStorage",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"webTorrentSocketPool",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"peerId",{enumerable:!0,configurable:!0,writable:!0,value:l}),Object.defineProperty(this,"requests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"engineRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"p2pLoaders",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentAvgDuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"levelChangedTimestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastQueueProcessingTimeStamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"randomHttpDownloadTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialHttpDelayTimeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isProcessQueueMicrotaskCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"swarmId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"createdAt",{enumerable:!0,configurable:!0,writable:!0,value:performance.now()}),Object.defineProperty(this,"requestProcessQueueMicrotask",{enumerable:!0,configurable:!0,writable:!0,value:(e=!0)=>{const t=performance.now();!e&&void 0!==this.lastQueueProcessingTimeStamp&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,Mf(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))}});const d=this.lastRequestedSegment.stream;this.swarmId=null!==(h=this.config.swarmId)&&void 0!==h?h:this.streamManifestUrl,this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=function(e){const{segments:t}=e;let s=0;const{size:i}=t;if(0===i)return 0;for(const e of t.values())s+=e.endTime-e.startTime;return s/i}(d),this.requests=new Oy(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new Ly(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,Gy.default)(`p2pml-core:hybrid-loader-${d.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=1e3*Math.random()*e+1e3;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}loadSegment(e,t){return Hy(this,void 0,void 0,function*(){var s;this.logger(`requests: ${ny(e)}`);const{stream:i}=e;i!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${ry(i)}`),this.p2pLoaders.changeCurrentLoader(i)),this.lastRequestedSegment=e;const r=ov(this.swarmId,i);this.segmentStorage.onSegmentRequested(this.swarmId,r,e.externalId,e.startTime,e.endTime,i.type,this.streamDetails.isLive);const n=new xy(e,t);try{if(this.segmentStorage.hasSegment(this.swarmId,r,e.externalId)){const t=yield this.segmentStorage.getSegmentData(this.swarmId,r,e.externalId);if(t){const{queueDownloadRatio:e}=this.generateQueue();return void n.resolve(t,this.getBandwidth(e))}}null===(s=this.engineRequest)||void 0===s||s.abort(),this.engineRequest=n;const t=this.requests.get(e);"failed"===(null==t?void 0:t.status)&&t.failedAttempts.clear()}catch(t){this.logger(`request failed for ${ny(e)} in ${ry(i)}`,t),n.reject()}finally{this.requestProcessQueueMicrotask()}})}processRequests(e,t){var s;const{stream:i}=this.lastRequestedSegment,{httpErrorRetries:r}=this.config,n=performance.now();for(const a of this.requests.items()){const{downloadSource:o,status:l,segment:h,isHandledByProcessQueue:d}=a,c=(null===(s=this.engineRequest)||void 0===s?void 0:s.segment)===h?this.engineRequest:void 0;switch(l){case"loading":e.has(h.runtimeId)||c||(a.cancel(),this.requests.remove(a));break;case"succeed":{if(!o)break;"http"===o&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),c&&(c.resolve(a.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(a),this.logger(`succeed: ${ny(h)} (byteLength: ${a.data.byteLength})`);const e=ov(this.swarmId,i);this.segmentStorage.storeSegment(this.swarmId,e,h.externalId,a.data,h.startTime,h.endTime,h.stream.type,this.streamDetails.isLive);break}case"failed":"http"!==o||d||this.p2pLoaders.currentLoader.broadcastAnnouncement(),c||i.segments.has(a.segment.runtimeId)||this.requests.remove(a),a.failedAttempts.httpAttemptsCount>=r&&c&&(this.engineRequest=void 0,c.reject());break;case"not-started":case"aborted":this.requests.remove(a)}a.markHandledByProcessQueue();const{lastAttempt:u}=a.failedAttempts;u&&n-u.error.timestamp>6e4&&a.failedAttempts.clear()}}processQueue(){var e,t,s;const{queue:i,queueSegmentIds:r,queueDownloadRatio:n}=this.generateQueue();this.processRequests(r,n);const{simultaneousHttpDownloads:a,simultaneousP2PDownloads:o,httpErrorRetries:l,httpDownloadInitialTimeoutMs:h}=this.config,d=performance.now()-this.createdAt,c=h>0&&d<h;c&&(null!==(e=this.initialHttpDelayTimeoutId)&&void 0!==e||(this.initialHttpDelayTimeoutId=window.setTimeout(()=>{this.initialHttpDelayTimeoutId=void 0,this.requestProcessQueueMicrotask()},h-d)));const{engineRequest:u}=this;if(u){const{segment:e}=u,s=this.requests.get(e);if(u.shouldBeStartedImmediately&&"pending"===u.status&&(!s||"not-started"===s.status||"failed"===s.status||"aborted"===s.status)){const i=!c&&(null!==(t=null==s?void 0:s.failedAttempts.httpAttemptsCount)&&void 0!==t?t:0)<l&&this.requests.executingHttpCount<a,r=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(e)&&this.requests.executingP2PCount<o;this.config.preferP2PForEngineRequest&&r?this.loadThroughP2P(e):i?this.loadThroughHttp(e):r&&this.loadThroughP2P(e)}}for(const e of i){const{statuses:t,segment:r}=e,n=this.requests.get(r);if("succeed"!==(null==n?void 0:n.status))if(t.isHighDemand){const e=!c&&(null!==(s=null==n?void 0:n.failedAttempts.httpAttemptsCount)&&void 0!==s?s:0)<l;if("loading"===(null==n?void 0:n.status)){!this.config.preferP2PForEngineRequest&&e&&"p2p"===n.downloadSource&&(this.requests.executingHttpCount<a||this.abortLastHttpLoadingInQueueAfterItem(i,r))&&(n.cancel(),this.loadThroughHttp(r));continue}if(e&&(this.requests.executingHttpCount<a||this.abortLastHttpLoadingInQueueAfterItem(i,r))){this.loadThroughHttp(r);continue}this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(r)&&(this.requests.executingP2PCount<o||this.abortLastP2PLoadingInQueueAfterItem(i,r))&&this.loadThroughP2P(r)}else t.isP2PDownloadable&&"loading"!==(null==n?void 0:n.status)&&this.requests.executingP2PCount<o&&this.loadThroughP2P(r)}}abortSegmentRequest(e){var t;(null===(t=this.engineRequest)||void 0===t?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger("abort: ",ny(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){const t=this.requests.getOrCreateRequest(e);new Ef(t,this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){const{httpDownloadInitialTimeoutMs:e}=this.config;if(e>0&&performance.now()-this.createdAt<e)return;const t=this.getAvailableStorageCapacityPercent();if(t<=10)return;const{simultaneousHttpDownloads:s,httpErrorRetries:i}=this.config,r=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=s||!r.connectedPeerCount)return;const n=[];for(const{segment:e,statuses:s}of Ny(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){const t=ov(this.swarmId,e.stream);if(!s.isHttpDownloadable||s.isP2PDownloadable||this.segmentStorage.hasSegment(this.swarmId,t,e.externalId))continue;const r=this.requests.get(e);r&&("loading"===r.status||"succeed"===r.status||r.failedAttempts.httpAttemptsCount>=i)||n.push(e)}if(!n.length)return;if(0===s-this.requests.executingHttpCount)return;const a=r.connectedPeerCount+1,o=Math.min(n.length,s*a),l=function(e){for(let t=e.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]]}return e}(Array.from({length:o},(e,t)=>t));let h=o/a;for(const e of l){if(this.requests.executingHttpCount>=s)break;if(h>=1||Math.random()<=h){const t=n[e];this.loadThroughHttp(t)}if(h--,h<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:s}of Of(e)){if(s===t)break;const e=this.requests.get(s);if("http"===(null==e?void 0:e.downloadSource)&&"loading"===e.status)return e.cancel(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(const{segment:s}of Of(e)){if(s===t)break;const e=this.requests.get(s);if("p2p"===(null==e?void 0:e.downloadSource)&&"loading"===e.status)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){const{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){var e;const t=[],s=new Set;let i=0,r=0;const n=this.getAvailableStorageCapacityPercent();for(const a of Ny(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,n)){i++;const{segment:n}=a,o=ov(this.swarmId,n.stream);this.segmentStorage.hasSegment(this.swarmId,o,n.externalId)||"succeed"===(null===(e=this.requests.get(n))||void 0===e?void 0:e.status)?r++:(t.push(a),s.add(n.runtimeId))}return{queue:t,queueSegmentIds:s,maxPossibleLength:i,alreadyLoadedCount:r,queueDownloadRatio:0!==i?r/i:0}}getBandwidth(e){const{http:t,all:s}=this.bandwidthCalculators,{activeLevelBitrate:i}=this.streamDetails;if(0===i)return s.getBandwidthLoadingOnly(3);const r=Math.max(s.getBandwidth(30,this.levelChangedTimestamp),s.getBandwidth(60,this.levelChangedTimestamp),s.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||r>=.9*i)return Math.max(s.getBandwidthLoadingOnly(1),s.getBandwidthLoadingOnly(3),s.getBandwidthLoadingOnly(5));const n=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(r,n)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){var s;const i=this.playback.rate!==t,r=this.playback.position!==e;if(!i&&!r)return;const n=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;r&&(this.playback.position=e),i&&0!==t&&(this.playback.rate=t),n&&(this.logger("position significantly changed"),null===(s=this.engineRequest)||void 0===s||s.markAsShouldBeStartedImmediately()),this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(n)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${ry(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),null===(e=this.engineRequest)||void 0===e||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}}}}),JS=o({"../../node_modules/p2p-media-loader-core/lib/segment-storage/utils.js"(){qy=(e,t)=>`${e}|${t}`,jy=e=>/Android/i.test(e),Ky=e=>/iPad|iPhone/i.test(e),Vy=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e))}}),ZS=o({"../../node_modules/p2p-media-loader-core/lib/segment-storage/segment-memory-storage.js"(){Yy=d(Cf(),1),JS(),zy=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Qy=1048576,Xy=class{constructor(){Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:navigator.userAgent}),Object.defineProperty(this,"segmentMemoryStorageLimit",{enumerable:!0,configurable:!0,writable:!0,value:4096}),Object.defineProperty(this,"currentStorageUsage",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"coreConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentPlayback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRequestedSegment",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentChangeCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=(0,Yy.default)("p2pml-core:segment-memory-storage"),this.logger.color="RebeccaPurple"}initialize(e,t,s){return zy(this,void 0,void 0,function*(){this.coreConfig=e,this.mainStreamConfig=t,this.secondaryStreamConfig=s,this.setMemoryStorageLimit(),this.logger("initialized")})}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,s,i,r,n,a){this.lastRequestedSegment={streamId:t,segmentId:s,startTime:i,endTime:r,swarmId:e,streamType:n,isLiveStream:a}}storeSegment(e,t,s,i,r,n,a,o){return zy(this,void 0,void 0,function*(){this.clear(o,i.byteLength);const e=qy(t,s);if(this.cache.set(e,{data:i,segmentId:s,streamId:t,startTime:r,endTime:n,streamType:a}),this.increaseStorageUsage(i.byteLength),this.logger(`add segment: ${s} to ${t}`),!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)})}getSegmentData(e,t,s){return zy(this,void 0,void 0,function*(){const e=qy(t,s),i=this.cache.get(e);if(void 0!==i)return i.data})}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};const e=this.currentPlayback.position;let t=0;for(const{endTime:s,data:i}of this.cache.values())e>s||(t+=i.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/Qy}}hasSegment(e,t,s){const i=qy(t,s);return void 0!==this.cache.get(i)}getStoredSegmentIds(e,t){const s=[];for(const{segmentId:e,streamId:i}of this.cache.values())i===t&&s.push(e);return s}clear(e,t){if(!(this.currentPlayback&&this.mainStreamConfig&&this.secondaryStreamConfig&&this.coreConfig))return;if(!this.isMemoryLimitReached(t)&&!e)return;const s=new Set,i=Array.from(this.cache.values()).sort((e,t)=>e.startTime-t.startTime);for(const r of i){const{streamId:i,segmentId:n,data:a}=r,o=qy(i,n);if(this.shouldRemoveSegment(r,e,this.currentPlayback.position)&&(this.cache.delete(o),s.add(i),this.decreaseStorageUsage(a.byteLength),this.logger(`Removed segment ${n} from stream ${i}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(s)}isMemoryLimitReached(e){return this.currentStorageUsage+e/Qy>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){0!==e.size&&e.forEach(e=>{if(!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(e)})}shouldRemoveSegment(e,t,s){const{endTime:i,streamType:r}=e,n=this.getStreamTimeWindow(r,"highDemandTimeWindow");return!(s<=i)&&(!t||s>n+i)}increaseStorageUsage(e){this.currentStorageUsage+=e/Qy}decreaseStorageUsage(e){this.currentStorageUsage-=e/Qy}setMemoryStorageLimit(){var e;(null===(e=this.coreConfig)||void 0===e?void 0:e.segmentMemoryStorageLimit)?this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit:Vy(this.userAgent)||Ky(this.userAgent)?this.segmentMemoryStorageLimit=1024:jy(this.userAgent)&&(this.segmentMemoryStorageLimit=2048)}getStreamTimeWindow(e,t){var s;const i="main"===e?this.mainStreamConfig:this.secondaryStreamConfig;return null!==(s=null==i?void 0:i[t])&&void 0!==s?s:0}destroy(){this.cache.clear(),this.segmentChangeCallback=void 0}}}}),eE=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/websocket-client/index.js"(){Qm(),Jy=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Zy=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},fS=class{constructor(e){var t,s,i;eS.add(this),tS.set(this,void 0),sS.set(this,"disconnected"),iS.set(this,null),rS.set(this,0),nS.set(this,null),aS.set(this,new Fm),oS.set(this,()=>{"disposed"!==Zy(this,sS,"f")&&(Jy(this,sS,"connected","f"),Jy(this,rS,0,"f"),Zy(this,aS,"f").dispatchEvent("connected"))}),lS.set(this,()=>{"disposed"!==Zy(this,sS,"f")&&(Zy(this,iS,"f")&&(Zy(this,iS,"f").onopen=null,Zy(this,iS,"f").onclose=null,Zy(this,iS,"f").onerror=null,Zy(this,iS,"f").onmessage=null,Jy(this,iS,null,"f")),Zy(this,eS,"m",cS).call(this),Zy(this,aS,"f").dispatchEvent("disconnected"))}),hS.set(this,e=>{"disposed"!==Zy(this,sS,"f")&&Zy(this,aS,"f").dispatchEvent("error",e)}),dS.set(this,e=>{"disposed"!==Zy(this,sS,"f")&&Zy(this,aS,"f").dispatchEvent("message",e.data)});const r=Math.max(100,null!==(t=e.initialDelay)&&void 0!==t?t:1e3);Jy(this,tS,{url:e.url,initialDelay:r,maxDelay:Math.max(r,null!==(s=e.maxDelay)&&void 0!==s?s:3e4),jitterMultiplier:Math.max(0,null!==(i=e.jitterMultiplier)&&void 0!==i?i:.2)},"f")}get state(){return Zy(this,sS,"f")}addEventListener(e,t){Zy(this,aS,"f").addEventListener(e,t)}removeEventListener(e,t){Zy(this,aS,"f").removeEventListener(e,t)}connect(){if("connected"!==Zy(this,sS,"f")&&"connecting"!==Zy(this,sS,"f")&&"disposed"!==Zy(this,sS,"f")){Jy(this,sS,"connecting","f"),Zy(this,eS,"m",uS).call(this);try{Jy(this,iS,new WebSocket(Zy(this,tS,"f").url),"f"),Zy(this,iS,"f").binaryType="arraybuffer",Zy(this,iS,"f").onopen=Zy(this,oS,"f"),Zy(this,iS,"f").onclose=Zy(this,lS,"f"),Zy(this,iS,"f").onerror=Zy(this,hS,"f"),Zy(this,iS,"f").onmessage=Zy(this,dS,"f")}catch(e){Jy(this,sS,"disconnected","f");const t=new ErrorEvent("error",{message:e instanceof Error?e.message:"Unknown WebSocket creation error",error:e});Zy(this,aS,"f").dispatchEvent("error",t)}}}send(e){if("connected"!==Zy(this,sS,"f")||!Zy(this,iS,"f"))throw new Error("WebSocketClient: Cannot send data when not connected");Zy(this,iS,"f").send(e)}dispose(){Jy(this,sS,"disposed","f"),Zy(this,eS,"m",uS).call(this),Zy(this,iS,"f")&&(Zy(this,iS,"f").onopen=null,Zy(this,iS,"f").onclose=null,Zy(this,iS,"f").onerror=null,Zy(this,iS,"f").onmessage=null,Zy(this,iS,"f").close(),Jy(this,iS,null,"f")),Zy(this,aS,"f").clear()}},tS=new WeakMap,sS=new WeakMap,iS=new WeakMap,rS=new WeakMap,nS=new WeakMap,aS=new WeakMap,oS=new WeakMap,lS=new WeakMap,hS=new WeakMap,dS=new WeakMap,eS=new WeakSet,cS=function(){var e;if("disposed"===Zy(this,sS,"f"))return;Jy(this,sS,"reconnecting","f");const t=Math.min(Zy(this,tS,"f").initialDelay*Math.pow(2,Zy(this,rS,"f")),Zy(this,tS,"f").maxDelay),s=t*Zy(this,tS,"f").jitterMultiplier,i=2*Math.random()*s-s,r=Math.max(0,t+i);t<Zy(this,tS,"f").maxDelay&&Jy(this,rS,(e=Zy(this,rS,"f"),++e),"f"),Jy(this,nS,setTimeout(()=>{"disposed"!==Zy(this,sS,"f")&&this.connect()},r),"f"),Zy(this,aS,"f").dispatchEvent("reconnecting")},uS=function(){null!==Zy(this,nS,"f")&&(clearTimeout(Zy(this,nS,"f")),Jy(this,nS,null,"f"))}}}),tE=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-socket-pool/index.js"(){eE(),Qm(),gS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},vS=class{constructor(){mS.set(this,new Map),pS.set(this,new Fm)}addEventListener(e,t){gS(this,pS,"f").addEventListener(e,t)}removeEventListener(e,t){gS(this,pS,"f").removeEventListener(e,t)}acquire(e){let t=gS(this,mS,"f").get(e);if(!t){const s=new fS({url:e});s.addEventListener("error",t=>{gS(this,pS,"f").dispatchEvent("error",t,e)}),s.connect(),t={client:s,refCount:0},gS(this,mS,"f").set(e,t)}t.refCount++;let s=!1;return{client:t.client,release:()=>{!s&&(s=!0,t.refCount--,t.refCount<=0)&&(t.refCount<0&&console.error(`[WebTorrentSocketPool] Negative refCount detected for ${e}`),gS(this,mS,"f").get(e)===t&&gS(this,mS,"f").delete(e),t.client.dispose())}}}destroy(){gS(this,pS,"f").clear();const e=Array.from(gS(this,mS,"f").values());gS(this,mS,"f").clear();for(const t of e)try{t.client.dispose()}catch(e){console.error("[WebTorrentSocketPool] Failed to dispose WebSocketClient:",e)}}},mS=new WeakMap,pS=new WeakMap}}),sE=o({"../../node_modules/p2p-media-loader-core/lib/core.js"(){XS(),yS=d(Cf(),1),mv(),Ym(),ZS(),Qm(),zf(),ty(),tE(),SS=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},ES=class e{constructor(t){Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:new Fm}),Object.defineProperty(this,"manifestResponseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streams",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"mainStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonCoreConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:{all:new om,http:new om}}),Object.defineProperty(this,"segmentStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webTorrentSocketPool",{enumerable:!0,configurable:!0,writable:!0,value:new vS}),Object.defineProperty(this,"socketPoolLogger",{enumerable:!0,configurable:!0,writable:!0,value:(0,yS.default)("p2pml-core:webtorrent-socket-pool")}),Object.defineProperty(this,"peerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainStreamLoader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamLoader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamDetails",{enumerable:!0,configurable:!0,writable:!0,value:{isLive:!1,activeLevelBitrate:0}}),Object.defineProperty(this,"storageInitPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const s=function e(t){if(xf(t)){const s={};return Object.keys(t).forEach(i=>{if(void 0!==t[i]){const r=e(t[i]);void 0!==r&&(s[i]=r)}}),s}return t}(null!=t?t:{});this.commonCoreConfig=Uf({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:s}),this.mainStreamConfig=Uf({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.mainStream}),this.secondaryStreamConfig=Uf({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.secondaryStream}),this.peerId=function(e){const t=[e],s=gv-e.length;for(let e=0;e<s;e++)t.push(fv[Math.floor(Math.random()*fv.length)]);return t.join("")}(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener("error",(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return Object.assign(Object.assign({},Ff(this.commonCoreConfig)),{mainStream:Ff(this.mainStreamConfig),secondaryStream:Ff(this.secondaryStreamConfig)})}applyDynamicConfig(e){const{mainStream:t,secondaryStream:s}=e,i=Ff(this.mainStreamConfig),r=Ff(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,s),this.processSpecificDynamicConfigParams(i,e,"main"),this.processSpecificDynamicConfigParams(r,e,"secondary")}processSpecificDynamicConfigParams(e,t,s){const i=this.getUpdatedStreamProperty("isP2PDisabled",t,s);i&&e.isP2PDisabled!==i&&this.destroyStreamLoader(s);const r=this.getUpdatedStreamProperty("isP2PUploadDisabled",t,s);if(void 0!==r&&e.isP2PUploadDisabled!==r){const e="main"===s?this.mainStreamLoader:this.secondaryStreamLoader;null==e||e.sendBroadcastAnnouncement(r)}}getUpdatedStreamProperty(e,t,s){var i;const r="main"===s?t.mainStream:t.secondaryStream;return null!==(i=null==r?void 0:r[e])&&void 0!==i?i:t[e]}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split("?")[0]}hasSegment(e){return!!lv(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,Object.assign(Object.assign({},e),{segments:new Map}))}updateStream(e,t,s){var i,r;const n=this.streams.get(e);if(n){if(t)for(const e of t)n.segments.has(e.runtimeId)||n.segments.set(e.runtimeId,Object.assign(Object.assign({},e),{stream:n}));if(s)for(const e of s)n.segments.delete(e);null===(i=this.mainStreamLoader)||void 0===i||i.updateStream(n),null===(r=this.secondaryStreamLoader)||void 0===r||r.updateStream(n)}}loadSegment(e,t){return SS(this,void 0,void 0,function*(){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");yield this.initializeSegmentStorage();const s=this.identifySegment(e);this.getStreamHybridLoader(s).loadSegment(s,t)})}abortSegmentLoading(e){var t,s;null===(t=this.mainStreamLoader)||void 0===t||t.abortSegmentRequest(e),null===(s=this.secondaryStreamLoader)||void 0===s||s.abortSegmentRequest(e)}updatePlayback(e,t){var s,i;null===(s=this.mainStreamLoader)||void 0===s||s.updatePlayback(e,t),null===(i=this.secondaryStreamLoader)||void 0===i||i.updatePlayback(e,t)}setActiveLevelBitrate(e){var t,s;e!==this.streamDetails.activeLevelBitrate&&(this.streamDetails.activeLevelBitrate=e,null===(t=this.mainStreamLoader)||void 0===t||t.notifyLevelChanged(),null===(s=this.secondaryStreamLoader)||void 0===s||s.notifyLevelChanged())}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{const t=this.identifySegment(e);return!("main"===t.stream.type&&this.mainStreamConfig.isP2PDisabled||"secondary"===t.stream.type&&this.secondaryStreamConfig.isP2PDisabled)}catch(e){return!1}}destroy(){var e,t,s,i;this.streams.clear(),null===(e=this.mainStreamLoader)||void 0===e||e.destroy(),null===(t=this.secondaryStreamLoader)||void 0===t||t.destroy(),null===(s=this.segmentStorage)||void 0===s||s.setSegmentChangeCallback(void 0),null===(i=this.segmentStorage)||void 0===i||i.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}initializeSegmentStorage(){return SS(this,void 0,void 0,function*(){if(!this.segmentStorage){if(this.storageInitPromise)return this.storageInitPromise;this.storageInitPromise=(()=>SS(this,void 0,void 0,function*(){const{isLive:e}=this.streamDetails,t=this.commonCoreConfig.customSegmentStorageFactory;if(t&&"function"!=typeof t)throw new Error("Storage configuration is invalid");const s=t?t(e):new Xy;try{yield s.initialize(this.commonCoreConfig,this.mainStreamConfig,this.secondaryStreamConfig)}catch(e){throw s.destroy(),e}if(!this.storageInitPromise)return s.setSegmentChangeCallback(void 0),void s.destroy();s.setSegmentChangeCallback(e=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${e}`)}),this.segmentStorage=s}))();try{yield this.storageInitPromise}finally{this.storageInitPromise=void 0}}})}identifySegment(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is undefined");const t=lv(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,s){Bf(this.commonCoreConfig,e),Bf(this.mainStreamConfig,e),Bf(this.secondaryStreamConfig,e),t&&Bf(this.mainStreamConfig,t),s&&Bf(this.secondaryStreamConfig,s)}destroyStreamLoader(e){var t,s;"main"===e?(null===(t=this.mainStreamLoader)||void 0===t||t.destroy(),this.mainStreamLoader=void 0):(null===(s=this.secondaryStreamLoader)||void 0===s||s.destroy(),this.secondaryStreamLoader=void 0)}getStreamHybridLoader(e){var t,s;return"main"===e.stream.type?(null!==(t=this.mainStreamLoader)&&void 0!==t||(this.mainStreamLoader=this.createNewHybridLoader(e)),this.mainStreamLoader):(null!==(s=this.secondaryStreamLoader)&&void 0!==s||(this.secondaryStreamLoader=this.createNewHybridLoader(e)),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");if(!this.segmentStorage)throw new Error("Segment storage is not initialized");const t="main"===e.stream.type?this.mainStreamConfig:this.secondaryStreamConfig;return new Wy(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}},Object.defineProperty(ES,"DEFAULT_COMMON_CORE_CONFIG",{enumerable:!0,configurable:!0,writable:!0,value:{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:uv}}),Object.defineProperty(ES,"DEFAULT_STREAM_CONFIG",{enumerable:!0,configurable:!0,writable:!0,value:{isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,preferP2PForEngineRequest:!1,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:65535,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:3e4,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:["wss://tracker.novage.com.ua","wss://tracker.openwebtorrent.com"],rtcConfig:{iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478"}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3}})}}),iE=o({"../../node_modules/p2p-media-loader-core/lib/index.js"(){sE(),If(),mv(),bS=d(Cf(),1)}}),rE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/fragment-loader.js"(){wf(),iE(),TS=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},wS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},_S=class{constructor(e,t){IS.add(this),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),LS.set(this,void 0),AS.set(this,void 0),kS.set(this,void 0),RS.set(this,void 0),CS.set(this,void 0),PS.set(this,void 0),TS(this,RS,t,"f"),TS(this,AS,()=>new e.loader(e),"f"),this.stats={aborted:!1,chunkCount:0,loading:{start:0,first:0,end:0},buffering:{start:0,first:0,end:0},parsing:{start:0,end:0},total:1,loaded:1,bwEstimate:0,retry:0}}load(e,t,s){this.context=e,this.config=t,TS(this,LS,s,"f");const{stats:i}=this,{rangeStart:r,rangeEnd:n}=e,a=rf(r,void 0!==n?n-1:void 0);TS(this,PS,sf(e.url,a),"f");const o=wS(this,RS,"f").isSegmentLoadable(wS(this,PS,"f"));if(!wS(this,RS,"f").hasSegment(wS(this,PS,"f"))||!o)return TS(this,kS,wS(this,AS,"f").call(this),"f"),wS(this,kS,"f").stats=this.stats,void wS(this,kS,"f").load(e,t,s);wS(this,RS,"f").loadSegment(wS(this,PS,"f"),{onSuccess:t=>{if(!wS(this,LS,"f"))return;TS(this,CS,t,"f");const s=wS(this,CS,"f").data.byteLength;i.loading=function(e,t,s){const i=e>0?8e3*t/e:0,r=Math.max(0,s-i);return{start:Math.max(0,r-10),first:r,end:s}}(wS(this,CS,"f").bandwidth,s,performance.now()),i.total=s,i.loaded=s;const r=wS(this,CS,"f").data.slice(0);wS(this,LS,"f").onProgress&&wS(this,LS,"f").onProgress(this.stats,e,r,void 0),wS(this,LS,"f").onSuccess({data:r,url:e.url},this.stats,e,void 0)},onError:e=>{e instanceof uf&&"aborted"===e.type&&this.stats.aborted||wS(this,IS,"m",DS).call(this,e)}})}abort(){var e,t;wS(this,kS,"f")?wS(this,kS,"f").abort():(wS(this,IS,"m",MS).call(this),null===(t=null===(e=wS(this,LS,"f"))||void 0===e?void 0:e.onAbort)||void 0===t||t.call(e,this.stats,this.context,{}))}destroy(){wS(this,kS,"f")?wS(this,kS,"f").destroy():(this.stats.aborted||wS(this,IS,"m",MS).call(this),TS(this,LS,null,"f"),this.config=null)}},LS=new WeakMap,AS=new WeakMap,kS=new WeakMap,RS=new WeakMap,CS=new WeakMap,PS=new WeakMap,IS=new WeakSet,DS=function(e){var t;const s={code:0,text:""};(e instanceof uf&&"failed"===e.type||e instanceof Error)&&(s.text=e.message),null===(t=wS(this,LS,"f"))||void 0===t||t.onError(s,this.context,null,this.stats)},MS=function(){!wS(this,CS,"f")&&wS(this,PS,"f")&&(this.stats.aborted=!0,wS(this,RS,"f").abortSegmentLoading(wS(this,PS,"f")))}}}),nE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/playlist-loader.js"(){OS=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},xS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},BS=class{constructor(e){FS.set(this,void 0),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),OS(this,FS,new e.loader(e),"f"),this.stats=xS(this,FS,"f").stats,this.context=xS(this,FS,"f").context}load(e,t,s){xS(this,FS,"f").load(e,t,s)}abort(){xS(this,FS,"f").abort()}destroy(){xS(this,FS,"f").destroy()}},FS=new WeakMap}}),aE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/segment-manager.js"(){wf(),iE(),US=class{constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.core=e}processMainManifest(e){const{levels:t,audioTracks:s}=e;for(const e of t){const{url:t,bitrate:s,maxBitrate:i,videoCodec:r,width:n,height:a}=e,o=null!=i?i:s,l=0===o,h=e.attrs["FRAME-RATE"],d=e.attrs["VIDEO-RANGE"],c=av({bitrate:o,codecs:l?void 0:r,width:l?void 0:n,height:l?void 0:a,frameRate:l?void 0:h,videoRange:l?void 0:d});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:"main",index:c})}for(const e of s){const{url:t,audioCodec:s,lang:i,channels:r,name:n}=e,a=av({bitrate:0,codecs:s,language:i,channels:r,name:n});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:"secondary",index:a})}}updatePlaylist(e){const{details:{url:t,fragments:s,live:i}}=e,r=this.core.getStream(t);if(!r)return;const n=new Set(r.segments.keys()),a=[];s.forEach((e,t)=>{const{url:s,byteRange:o,sn:l,start:h,end:d}=e,[c,u]=o,f=rf(c,void 0!==u?u-1:void 0),g=sf(s,f);n.delete(g),r.segments.has(g)||a.push({runtimeId:g,url:s,externalId:i?l:t,byteRange:f,startTime:h,endTime:d})}),(a.length||n.size)&&this.core.updateStream(t,a,n.values())}}}}),oE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/engine-static.js"(){lE(),NS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$S=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},GS=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]])}return s}}}),lE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/engine.js"(){rE(),nE(),aE(),iE(),oE(),HS=class{static injectMixin(e){return t=e,i=class extends t{get p2pEngine(){return NS(this,s,"f")}constructor(...e){var t;const i=e[0],r=null!=i?i:{},{p2p:n}=r,a=GS(r,["p2p"]),o=new HS(n);super(Object.assign(Object.assign({},a),o.getConfigForHlsJs())),s.set(this,void 0),o.bindHls(this),$S(this,s,o,"f"),null===(t=null==n?void 0:n.onHlsJsCreated)||void 0===t||t.call(n,this)}},s=new WeakMap,i;var t,s,i}constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hlsInstanceGetter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentHlsInstance",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:(0,bS.default)("p2pml-hlsjs:engine")}),Object.defineProperty(this,"updateMediaElementEventHandlers",{enumerable:!0,configurable:!0,writable:!0,value:e=>{var t;const s=null===(t=this.currentHlsInstance)||void 0===t?void 0:t.media;if(!s)return;const i="register"===e?"addEventListener":"removeEventListener";s[i]("timeupdate",this.handlePlaybackUpdate),s[i]("seeking",this.handlePlaybackUpdate),s[i]("ratechange",this.handlePlaybackUpdate)}}),Object.defineProperty(this,"handleManifestLoaded",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{const s=t.networkDetails;s instanceof XMLHttpRequest?this.core.setManifestResponseUrl(s.responseURL):s instanceof Response&&this.core.setManifestResponseUrl(s.url),this.segmentManager.processMainManifest(t)}}),Object.defineProperty(this,"handleLevelSwitching",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{t.bitrate&&this.core.setActiveLevelBitrate(t.bitrate)}}),Object.defineProperty(this,"handleLevelUpdated",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{this.currentHlsInstance&&"main"===t.details.fragments[0].type&&t.details.fragments.length>4&&(!t.details.live||this.currentHlsInstance.userConfig.liveSyncDuration||this.currentHlsInstance.userConfig.liveSyncDurationCount||this.updateLiveSyncDurationCount(t),this.currentHlsInstance.userConfig.maxBufferLength||this.currentHlsInstance.userConfig.maxMaxBufferLength||this.updateMaxBufferLength(t.details.targetduration)),this.core.setIsLive(t.details.live),this.segmentManager.updatePlaylist(t)}}),Object.defineProperty(this,"handleMediaAttached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("register")}}),Object.defineProperty(this,"handleMediaDetached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("unregister")}}),Object.defineProperty(this,"handlePlaybackUpdate",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=e.target;this.core.updatePlayback(t.currentTime,t.playbackRate)}}),Object.defineProperty(this,"destroyCore",{enumerable:!0,configurable:!0,writable:!0,value:()=>this.core.destroy()}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyCore(),this.updateHlsEventsHandlers("unregister"),this.updateMediaElementEventHandlers("unregister"),this.currentHlsInstance=void 0}}),this.core=new ES(null==e?void 0:e.core),this.segmentManager=new US(this.core)}addEventListener(e,t){this.core.addEventListener(e,t)}removeEventListener(e,t){this.core.removeEventListener(e,t)}getConfigForHlsJs(){return{fLoader:this.createFragmentLoaderClass(),pLoader:this.createPlaylistLoaderClass()}}getConfig(){return{core:this.core.getConfig()}}applyDynamicConfig(e){e.core&&this.core.applyDynamicConfig(e.core)}bindHls(e){this.hlsInstanceGetter="function"==typeof e?e:()=>e}initHlsEvents(){var e;const t=null===(e=this.hlsInstanceGetter)||void 0===e?void 0:e.call(this);this.currentHlsInstance!==t&&(this.currentHlsInstance&&this.destroy(),this.currentHlsInstance=t,this.updateHlsEventsHandlers("register"),this.updateMediaElementEventHandlers("register"))}updateHlsEventsHandlers(e){const t=this.currentHlsInstance;if(!t)return;const s="register"===e?"on":"off";t[s]("hlsManifestLoaded",this.handleManifestLoaded),t[s]("hlsLevelSwitching",this.handleLevelSwitching),t[s]("hlsLevelUpdated",this.handleLevelUpdated),t[s]("hlsAudioTrackLoaded",this.handleLevelUpdated),t[s]("hlsDestroying",this.destroy),t[s]("hlsMediaAttaching",this.destroyCore),t[s]("hlsManifestLoading",this.destroyCore),t[s]("hlsMediaDetached",this.handleMediaDetached),t[s]("hlsMediaAttached",this.handleMediaAttached)}updateLiveSyncDurationCount(e){const t=e.details.targetduration,s=Math.floor(120/t),i=Math.min(e.details.fragments.length-1,s);this.currentHlsInstance&&this.currentHlsInstance.config.liveSyncDurationCount!==i&&(this.debug(`Setting liveSyncDurationCount to ${i}`),this.currentHlsInstance.config.liveSyncDurationCount=i)}updateMaxBufferLength(e){if(!this.currentHlsInstance)return;const t=this.core.getConfig(),s=Math.max(t.mainStream.highDemandTimeWindow,t.secondaryStream.highDemandTimeWindow),i=Math.max(2*e,s);this.currentHlsInstance.config.maxBufferLength>i&&(this.debug(`Setting maxBufferLength to ${i}`),this.currentHlsInstance.config.maxBufferLength=i),this.currentHlsInstance.config.maxMaxBufferLength>i&&(this.debug(`Setting maxMaxBufferLength to ${i}`),this.currentHlsInstance.config.maxMaxBufferLength=i)}createFragmentLoaderClass(){const{core:e}=this,t=this;return class extends _S{constructor(t){super(t,e)}static getEngine(){return t}}}createPlaylistLoaderClass(){const e=this;return class extends BS{constructor(t){super(t),e.initHlsEvents()}}}}}}),hE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/index.js"(){lE()}}),dE=o({"src/logging.ts"(){WS={none:0,error:1,warn:2,info:3,debug:4},qS=0,jS=class{constructor(e="none"){this.level=e}level;clientId=++qS;repeats=new Map;log(e,t,s){if(!((WS[this.level]??0)<WS[e]))try{let i=0;if("error"===e||"warn"===e){const e=performance.now(),s=this.repeats.get(t);if(s&&e-s.at<5e3)return void s.suppressed++;i=s?.suppressed??0,this.repeats.size>=32&&!s&&this.repeats.delete(this.repeats.keys().next().value),this.repeats.set(t,{at:e,suppressed:0})}const r=function(e){return e.replace(/(?:https?|wss?):\/\/[^\s"'<>]+/gi,e=>{try{const t=new URL(e);return t.username="",t.password="",t.search="",t.hash="",["localhost","127.0.0.1","[::1]"].includes(t.hostname)&&(t.pathname="/[proxy]"),t.toString()}catch{return"[redacted-url]"}}).replace(/\/[^\s/?]+\/fetch\/[^\s]*/g,"/[proxy]").replace(/\b(authorization|proxy-authorization|sdk[_-]?key|session[_-]?token|access[_-]?token|refresh[_-]?token|token|key)["']?\s*[:=]\s*(?:(?:Bearer|Basic)\s+)?(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)/gi,"$1=[redacted]").replace(/\b(?:Bearer|Basic)\s+[^\s,"';}]+/gi,"[redacted-authorization]").replace(/\bkey_[A-Za-z0-9_-]+/g,"[redacted-key]").replace(/[\x00-\x1f\x7f]/g," ").slice(0,4096)}(s());console[e](`[MeshStream web-${this.clientId}] ${r}${i?` suppressed=${i}`:""}`)}catch{}}}}}),cE={};function uE(e,t){var s;t&&(s=e.userConfig,!Boolean(void 0!==s?.liveSyncDuration||void 0!==s?.liveSyncDurationCount||void 0!==s?.liveMaxLatencyDuration||void 0!==s?.liveMaxLatencyDurationCount))&&(e.config.liveSyncDurationCount=VS,e.config.liveMaxLatencyDurationCount=YS)}function fE(e,t,s=KS.liveSeedCohortCount){const i=Number.isFinite(s)?Math.max(1,Math.floor(s)):KS.liveSeedCohortCount;return function(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}(`${t}${e}`)%i===0}function gE({livePeerSchedulingActive:e,peerHasSegment:t,p2pSlotsAvailable:s,previousP2pFailures:i}){return e&&t&&s&&Number.isFinite(i)&&0===i}function mE(e,t){return void 0!==e&&Number.isFinite(e)?Math.max(0,Math.floor(e)):t}function pE(e){if(null!=e&&Number.isFinite(e)&&!(e<0))return Math.round(1e3*e)}function vE(e){if(e instanceof Error)return e.message.slice(0,200);if("string"==typeof e)return e.slice(0,200);try{return JSON.stringify(e).slice(0,200)}catch{return String(e).slice(0,200)}}function yE(e){try{e()}catch{}}h(cE,{DEFAULT_P2P_STRATEGY:()=>KS,HlsP2pClient:()=>zS,applyDefaultHlsLiveLatencyPolicy:()=>uE,isLiveSeedCohort:()=>fE,shouldUsePeerForLiveHttpRequest:()=>gE});var SE=o({"src/hls.ts"(){hE(),re(),w(),J(),Mt(),Z(),dE(),E(),W(),KS=Object.freeze({uploadSlots:4,downloadSlots:5,simultaneousP2PDownloads:3,httpDownloadInitialTimeoutMs:0,highDemandTimeWindow:15,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,peerHighDemandTimeWindow:6,peerHttpDownloadTimeWindow:3e3,peerP2pDownloadTimeWindow:12e3,livePeerHighDemandTimeWindow:2,livePeerHttpDownloadTimeWindow:4,liveSeedCohortCount:4,liveSeedHttpDownloadTimeWindow:6,maxMessageSizeBytes:16384,p2pNotReceivingBytesTimeoutMs:2e3,webRtcConnectionTimeoutMs:15e3}),VS=4,YS=8,zS=class{logger;engine;hlsjsInstance;engineConfig;trackerCandidates;activeTrackerIndex=0;failoverInFlight=!1;disposed=!1;engineGeneration=0;swarmId;streamUrl;contentId;appId;keyId;uploadSlots;downloadSlots;reportIntervalMs;capability;reportUrl;sessionId;sessionTokenManager;startedAtMs=performance.now();listeners=new Map;eventListeners=new Set;activePeers=new Set;pagehideHandler=()=>{this.reportStats()};reportTimer;reportInFlight=!1;pendingFinalReport;hasReportedContext=!1;eventTimer;p2pEnabled;p2pReady=!1;peerWindowProfile="baseline";playbackIsLive;liveSeedCohort;hlsLivePlaylistHandler=(e,t)=>{"boolean"==typeof t.details?.live&&(this.playbackIsLive=t.details.live,uE(this.hlsjsInstance,t.details.live),this.applyPeerOptimizedWindows(this.activePeers.size>0))};stats={httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0};diagnosticState={fallbackCount:0,coldStart:{p2pDownloaded:0,httpDownloaded:0},ice:{attempts:0,successes:0,failures:0,durationMs:0}};static isSupported(){return"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof WebSocket}constructor(e){this.logger=new jS(e.logLevel),this.hlsjsInstance=e.hlsjsInstance,this.streamUrl=e.streamUrl,this.contentId=e.contentId?.trim()||void 0,this.appId=e.sdkConfig?.applicationId?.trim()||e.appId?.trim()||void 0,this.keyId=e.sdkConfig?.keyId?.trim()||void 0,this.sessionId=e.sessionId?.trim()||`web-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`,this.p2pEnabled=!1!==e.p2pEnabled,this.uploadSlots=mE(e.uploadSlots,KS.uploadSlots),this.downloadSlots=mE(e.downloadSlots,KS.downloadSlots),this.reportIntervalMs=j(e.sdkConfig?.defaults?.reportIntervalMs),this.capability=e.capability,this.sessionTokenManager=e.sessionTokenManager;const t=e.contentId?.trim()?D(e.contentId):P(e.streamUrl),s=e.sdkConfig?.defaults?.swarmBucketCount??1,i=e.sdkConfig?.defaults?.swarmBucketId??O(this.sessionId,s);this.swarmId=x(t,s,i),this.liveSeedCohort=fE(this.sessionId,this.swarmId),this.diagnosticState.playbackAuth=b(e.streamUrl,e.sdkConfig?.playbackAuth);const r=e.sdkConfig?.trackerUrls?.length?e.sdkConfig.trackerUrls:e.trackerUrls,n=I(e.trackerUrl,r,this.appId,this.swarmId,this.keyId,e.sdkConfig?.primaryTrackerUrl,{liveWindowBucket:e.liveWindowBucket?.trim()||"auto"});this.trackerCandidates=n;const a=n[0],o=u(e.originHeaders,e.originHeadersProvider,e.streamUrl);this.reportUrl=k(C(e.sdkConfig?.reportUrl,{appId:this.appId,keyId:this.keyId}))||k(R(a))||C(e.sdkConfig?.reportUrl,{appId:this.appId,keyId:this.keyId})||R(a),this.engineConfig={core:{httpRequestSetup:o,...a?{announceTrackers:[a]}:{},rtcConfig:{iceServers:e.iceServers??(e.sdkConfig?.iceServers?.length?[{urls:e.sdkConfig.iceServers}]:ee())},swarmId:this.swarmId,isP2PDisabled:!1===e.p2pEnabled,simultaneousP2PDownloads:KS.simultaneousP2PDownloads,httpDownloadInitialTimeoutMs:mE(e.httpDownloadInitialTimeoutMs,KS.httpDownloadInitialTimeoutMs),highDemandTimeWindow:KS.highDemandTimeWindow,httpDownloadTimeWindow:KS.httpDownloadTimeWindow,p2pDownloadTimeWindow:KS.p2pDownloadTimeWindow,preferP2PForEngineRequest:!0,webRtcMaxMessageSize:KS.maxMessageSizeBytes,p2pNotReceivingBytesTimeoutMs:KS.p2pNotReceivingBytesTimeoutMs,webRtcConnectionTimeoutMs:KS.webRtcConnectionTimeoutMs,customSegmentStorageFactory:ne}},this.engine=this.createEngine(a),this.engine.bindHls(this.hlsjsInstance),Object.assign(this.hlsjsInstance.config,this.engine.getConfigForHlsJs()),this.hlsjsInstance.on?.("hlsLevelLoaded",this.hlsLivePlaylistHandler);const l=this.hlsjsInstance.latestLevelDetails;l&&(this.playbackIsLive=l.live,uE(this.hlsjsInstance,l.live)),this.bindEvents(),this.logger.log("info","initialized",()=>"HLS P2P client initialized"),window.addEventListener("pagehide",this.pagehideHandler),this.startStatsReporting()}on(e,t){const s=this.listeners.get(e)??new Set;s.add(t),this.listeners.set(e,s)}off(e,t){this.listeners.get(e)?.delete(t)}addEventListener(e){this.eventListeners.add(e),yE(()=>e.onPlaybackStateChanged?.(this.p2pEnabled&&this.p2pReady?"p2p-ready":this.p2pEnabled?"connecting":"cdn-fallback")),void 0===this.eventTimer&&(this.eventTimer=window.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)yE(()=>t.onStatistics?.(e))},1e3))}removeEventListener(e){this.eventListeners.delete(e),0===this.eventListeners.size&&void 0!==this.eventTimer&&(window.clearInterval(this.eventTimer),this.eventTimer=void 0)}setP2pEnabled(e){this.p2pEnabled=e,this.engine.applyDynamicConfig({core:{isP2PDisabled:!e}}),!e&&this.p2pReady&&(this.p2pReady=!1,this.notify(e=>e.onP2pUnavailable?.("DISABLED")),this.notifyPlaybackState("cdn-fallback"))}statistics(){return{...this.stats}}diagnostics(){const e=this.currentLiveLatency(),t=this.diagnosticState.liveLatency;return{...this.diagnosticState,...this.diagnosticState.coldStart?{coldStart:{...this.diagnosticState.coldStart}}:{},...t?{liveLatency:{...t,...e||{}}}:{}}}dispose(){this.disposed=!0,void 0!==this.reportTimer&&window.clearInterval(this.reportTimer),void 0!==this.eventTimer&&window.clearInterval(this.eventTimer),window.removeEventListener("pagehide",this.pagehideHandler),this.hlsjsInstance.off?.("hlsLevelLoaded",this.hlsLivePlaylistHandler),this.reportTimer=void 0,this.eventTimer=void 0,this.reportStats(this.statistics(),!0).catch(()=>{}),this.engine.destroy(),this.listeners.clear(),this.eventListeners.clear()}getHlsConfig(){return this.engine.getConfigForHlsJs()}emit(e,t){for(const s of this.listeners.get(e)??[])s(t)}bindEvents(){const e=this.engine,t=this.engineGeneration;e.addEventListener("onPeerConnect",e=>{t===this.engineGeneration&&(this.activePeers.add(e.peerId),this.logger.log("info","peer-connected",()=>`peer connected peers=${this.activePeers.size}`),this.diagnosticState.ice&&(this.diagnosticState.ice.attempts+=1,this.diagnosticState.ice.successes+=1),this.stats.connectedPeers=this.activePeers.size,this.applyPeerOptimizedWindows(!0),void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.firstPeerConnectMs=Math.round(performance.now()-this.startedAtMs)),this.emit("peer-connect",e),this.notify(e=>e.onPeerCountChanged?.(this.stats.connectedPeers)),!this.p2pReady&&this.p2pEnabled&&(this.p2pReady=!0,this.notify(e=>e.onP2pReady?.()),this.notifyPlaybackState("p2p-ready")))}),e.addEventListener("onPeerClose",e=>{t===this.engineGeneration&&(this.activePeers.delete(e.peerId),this.logger.log("info","peer-closed",()=>`peer closed peers=${this.activePeers.size}`),this.stats.connectedPeers=this.activePeers.size,0===this.activePeers.size&&this.applyPeerOptimizedWindows(!1),this.emit("peer-close",e),this.notify(e=>e.onPeerCountChanged?.(this.stats.connectedPeers)),this.p2pReady&&0===this.stats.connectedPeers&&(this.p2pReady=!1,this.notify(e=>e.onP2pUnavailable?.(this.p2pEnabled?"NO_PEERS":"DISABLED")),this.notifyPlaybackState("cdn-fallback")))}),e.addEventListener("onPeerConnectError",e=>{t===this.engineGeneration&&(this.stats.peerConnectErrors+=1,this.logger.log("error","peer-connect-error",()=>`peer connection failed total=${this.stats.peerConnectErrors}`),this.diagnosticState.ice&&(this.diagnosticState.ice.attempts+=1,this.diagnosticState.ice.failures+=1),this.diagnosticState.lastPeerError=vE(e),this.diagnosticState.lastErrorAtMs=Date.now(),this.emit("segment-error",e),this.notify(e=>e.onPeerConnectError?.(this.stats.peerConnectErrors)))}),e.addEventListener("onTrackerError",e=>{t===this.engineGeneration&&(this.stats.trackerErrors+=1,this.logger.log("error","tracker-error",()=>`tracker connection failed total=${this.stats.trackerErrors}`),this.diagnosticState.lastTrackerError=vE(e),this.diagnosticState.lastErrorAtMs=Date.now(),this.emit("tracker-error",e),this.notify(e=>e.onTrackerError?.(this.stats.trackerErrors)),this.failoverTracker(e.trackerUrl))}),e.addEventListener("onSegmentError",e=>{t===this.engineGeneration&&(this.logger.log("error","segment-error",()=>"segment request failed"),this.emit("segment-error",e))}),e.addEventListener("onChunkDownloaded",(e,s,i)=>{t===this.engineGeneration&&("p2p"===s?(this.stats.p2pDownloaded+=e,void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.coldStart.p2pDownloaded+=e),this.emit("p2p-download",{bytes:e,peerId:i})):(this.stats.httpDownloaded+=e,void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.coldStart.httpDownloaded+=e),0===this.activePeers.size&&(this.diagnosticState.fallbackCount+=1),this.emit("http-download",{bytes:e}),0!==this.activePeers.size&&0!==this.stats.p2pDownloaded||this.notify(t=>t.onCdnFallback?.(e))))}),e.addEventListener("onChunkUploaded",(e,s)=>{t===this.engineGeneration&&(this.stats.p2pUploaded+=e,this.emit("p2p-upload",{bytes:e,peerId:s}))})}createEngine(e){const t=this.engineConfig.core??{},s=new HS({...this.engineConfig,core:{...t,...e?{announceTrackers:[e]}:{}}});return function(e,t){const s=e.core,i=s?.createNewHybridLoader;s&&"function"==typeof i&&(s.createNewHybridLoader=function(e){const s=i.call(this,e),r=s.loadThroughHttp,n=s.loadThroughP2P;return"function"!=typeof r||"function"!=typeof n||(s.loadThroughHttp=e=>{const i=s.p2pLoaders?.currentLoader,a=s.requests?.get?.(e),o=a?.failedAttempts?.p2pAttemptsCount??0,l=s.requests?.executingP2PCount,h=s.config?.simultaneousP2PDownloads,d="number"==typeof l&&"number"==typeof h&&l<h,c=!0===i?.isSegmentLoadedBySomeone?.(e);gE({livePeerSchedulingActive:t(),peerHasSegment:c,p2pSlotsAvailable:d,previousP2pFailures:o})?n.call(s,e):r.call(s,e)}),s})}(s,()=>!0===this.playbackIsLive&&this.p2pEnabled&&this.activePeers.size>0),s}async failoverTracker(e){if(this.disposed||this.failoverInFlight||this.trackerCandidates.length<2)return;const t=this.trackerCandidates.indexOf(e),s=(t>=0?t:this.activeTrackerIndex)+1;if(!(s>=this.trackerCandidates.length)){this.failoverInFlight=!0;try{const e=this.trackerCandidates[s];this.engineGeneration+=1,this.engine.destroy(),this.activeTrackerIndex=s,this.activePeers.clear(),this.stats.connectedPeers=0,this.p2pReady=!1,this.engine=this.createEngine(e),this.engine.bindHls(this.hlsjsInstance),Object.assign(this.hlsjsInstance.config,this.engine.getConfigForHlsJs()),this.bindEvents()}finally{this.failoverInFlight=!1}}}notify(e){for(const t of this.eventListeners)yE(()=>e(t))}notifyPlaybackState(e){this.notify(t=>t.onPlaybackStateChanged?.(e))}startStatsReporting(){this.reportUrl&&(this.reportTimer=window.setTimeout(()=>{this.reportStats().catch(()=>{}),this.reportTimer=window.setInterval(()=>{this.reportStats().catch(()=>{})},this.reportIntervalMs)},K(this.reportIntervalMs)))}applyPeerOptimizedWindows(e){const t=e?this.playbackIsLive?this.liveSeedCohort?"live-seed":"live":"generic":"baseline";this.playbackIsLive?this.diagnosticState.liveSeed={cohort:this.liveSeedCohort,active:e&&this.liveSeedCohort}:delete this.diagnosticState.liveSeed,this.peerWindowProfile!==t&&(this.peerWindowProfile=t,this.engine.applyDynamicConfig({core:"live"===t||"live-seed"===t?{highDemandTimeWindow:KS.livePeerHighDemandTimeWindow,httpDownloadTimeWindow:"live-seed"===t?KS.liveSeedHttpDownloadTimeWindow:KS.livePeerHttpDownloadTimeWindow,p2pDownloadTimeWindow:KS.peerP2pDownloadTimeWindow}:"generic"===t?{highDemandTimeWindow:KS.peerHighDemandTimeWindow,httpDownloadTimeWindow:KS.peerHttpDownloadTimeWindow,p2pDownloadTimeWindow:KS.peerP2pDownloadTimeWindow}:{highDemandTimeWindow:KS.highDemandTimeWindow,httpDownloadTimeWindow:KS.httpDownloadTimeWindow,p2pDownloadTimeWindow:KS.p2pDownloadTimeWindow}}))}async reportStats(e,t=!1){if(!this.reportUrl||void 0===this.playbackIsLive)return;const s={...e??this.stats};if(this.reportInFlight)t&&(this.pendingFinalReport=s);else{this.reportInFlight=!0;try{this.recordLiveLatency();const e=function(e,t){return{...e,...e.coldStart?{coldStart:{...e.coldStart}}:{},...e.liveLatency?{liveLatency:{...e.liveLatency}}:{},...e.liveSeed?{liveSeed:{...e.liveSeed}}:{},...e.playbackAuth?{playbackAuth:{...e.playbackAuth}}:{},...e.ice?{ice:{...e.ice}}:{},...t?{auth:{...t}}:e.auth?{auth:{...e.auth}}:{},...e.websocket?{websocket:{...e.websocket}}:{}}}(this.diagnosticState,this.sessionTokenManager?.diagnostics?.()),t=!this.hasReportedContext,i=await(this.sessionTokenManager?.getAuthorizationHeader()),r=await z(this.reportUrl,V({platform:"web",playbackMode:this.playbackIsLive?"live":"vod",runtimeMode:"mse",protocol:"hls",playerType:"hlsjs",appId:this.appId,keyId:this.keyId,sdkVersion:Q,sessionId:this.sessionId,contentId:M(this.contentId,this.streamUrl),swarmId:this.swarmId,playbackUrl:this.streamUrl,stats:s,capability:this.capability,load:{uploadSlots:this.uploadSlots,activeUploadPeers:Math.min(s.connectedPeers,this.uploadSlots),downloadSlots:this.downloadSlots,activeDownloadPeers:Math.min(s.connectedPeers,this.downloadSlots)},diagnostics:e},t),{authorizationHeader:i});r?.ok&&(this.hasReportedContext=!0)}finally{this.reportInFlight=!1;const e=this.pendingFinalReport;this.pendingFinalReport=void 0,e&&this.reportStats(e,!0)}}}currentLiveLatency(){if(!this.playbackIsLive)return;const e=pE(this.hlsjsInstance.latency),t=pE(this.hlsjsInstance.targetLatency),s=pE(this.hlsjsInstance.maxLatency);return void 0!==e&&void 0!==t&&void 0!==s?{lastLatencyMs:e,lastTargetLatencyMs:t,lastMaxLatencyMs:s}:void 0}recordLiveLatency(){const e=this.currentLiveLatency();if(!e)return;const t=this.diagnosticState.liveLatency??{samples:0,latencyDurationMs:0,targetLatencyDurationMs:0,maxLatencyDurationMs:0,overMaxLatencySamples:0};t.samples+=1,t.latencyDurationMs+=e.lastLatencyMs,t.targetLatencyDurationMs+=e.lastTargetLatencyMs,t.maxLatencyDurationMs+=e.lastMaxLatencyMs,e.lastLatencyMs>e.lastMaxLatencyMs&&(t.overMaxLatencySamples+=1),this.diagnosticState.liveLatency=t}}}});function EE(e){return e in globalThis}function bE(e,t){return e??t}var TE="https://api.meshstream.net/config-api/v1/sdk/bootstrap",wE=[1e3,2e3,5e3,1e4,3e4],IE=new Map,LE=new Map,AE=new Map;async function kE(e,t={}){const s=function(e){const t=new URL(e);t.pathname&&"/"!==t.pathname||(t.pathname="/v1/sdk/bootstrap");for(const e of["key","app_id","appId","platform","package_name","packageName","signing_cert_sha256","signingCertSha256","network_type","networkType"])t.searchParams.delete(e);return t.toString()}(e.bootstrapUrl?.trim()||TE),i=e.key?.trim(),r=e.platform?.trim()||"web";if(!i)return;const n=t.now??Date.now,a=function(e){return JSON.stringify({bootstrapUrl:e.bootstrapUrl?.trim()||TE,key:e.key?.trim(),platform:e.platform?.trim()||"web",contentId:e.contentId?.trim()||"",expectedPeers:e.expectedPeers??0})}({...e,bootstrapUrl:s,key:i,platform:r}),o=IE.get(a);if(!t.forceRefresh&&o){if(n()<o.expiresAtMs)return IE.delete(a),IE.set(a,o),o.config;n()>=o.staleUntilMs&&IE.delete(a)}const l=LE.get(a);if(l)return l;const h=async function({request:e,options:t,bootstrapUrl:s,key:i,platform:r,cacheKey:n,now:a}){try{const d=t.fetcher??fetch,c=function(e){const t={},s=e.key?.trim();s&&(t.key=s),t.platform=e.platform?.trim()||"web";const i=e.contentId?.trim();return i&&(t.contentId=i),Number.isFinite(e.expectedPeers)&&(e.expectedPeers??0)>0&&(t.expectedPeers=String(Math.floor(e.expectedPeers))),t}({key:i,platform:r,contentId:e.contentId,expectedPeers:e.expectedPeers}),u=await async function(e,t,s,i){const r=new AbortController;let n;const a=new Promise((e,t)=>{n=setTimeout(()=>{r.abort(),t(new Error(`SDK bootstrap timed out after ${i} ms`))},i)});try{return await Promise.race([e(t,{...s,signal:r.signal}),a])}finally{void 0!==n&&clearTimeout(n)}}(d,s,{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(c)},(h=t.timeoutMs,Number.isFinite(h)?Math.max(1,Math.min(3e4,Math.floor(h))):8e3));if(!u.ok)return 408===(l=u.status)||429===l||l>=500?(RE(t,"TRANSIENT_HTTP"),CE(e,t,n),PE(n,a())):(RE(t,"REJECTED"),function(e){IE.delete(e)}(n));const f={configVersion:(o=await u.json()).configVersion,appId:o.appId,applicationId:o.applicationId,homeRegion:o.homeRegion,edgeRegion:o.edgeRegion,keyId:o.keyId,keyName:o.keyName,keyEnabled:o.keyEnabled,keyPlatform:o.keyPlatform,p2pEnabled:o.p2pEnabled,ttlSeconds:o.ttlSeconds,refreshAfterSeconds:o.refreshAfterSeconds,applyMode:o.applyMode,status:o.status,quota:o.quota,accessUrl:o.accessUrl,trackerUrls:Array.isArray(o.trackerUrls)?o.trackerUrls.filter(e=>Boolean(e?.trim())):[],primaryTrackerUrl:DE(o.primaryTrackerUrl,o.trackerUrls),iceServers:_E(o.iceServers),trackerNodes:Array.isArray(o.trackerNodes)?o.trackerNodes:void 0,trackerPool:o.trackerPool,reportUrl:o.reportUrl,scheduling:o.scheduling,playbackAuth:o.playbackAuth,defaults:o.defaults},g=a()+1e3*function(e){const t=e.refreshAfterSeconds??e.ttlSeconds??60;return Number.isFinite(t)?Math.max(5,Math.min(3600,Math.floor(t))):60}(f);return function(e,t){for(IE.delete(e),IE.set(e,t);IE.size>32;){const e=IE.keys().next().value;if(void 0===e)return;IE.delete(e)}}(n,{config:f,expiresAtMs:g,staleUntilMs:g+3e5}),f}catch{return RE(t,"NETWORK"),CE(e,t,n),PE(n,a())}var o,l,h}({request:e,options:t,bootstrapUrl:s,key:i,platform:r,cacheKey:a,now:n});LE.set(a,h);try{return await h}finally{LE.get(a)===h&&LE.delete(a)}}function RE(e,t){try{e.onFailure?.(t)}catch{}}function CE(e,t,s){if(t.suppressBackgroundRetry||AE.has(s))return;const i=(async()=>{for(const s of wE){await new Promise(e=>{const t=globalThis.setTimeout(e,s);t.unref?.()});let i=!1,r=!1;if(await kE(e,{...t,forceRefresh:!0,suppressBackgroundRetry:!0,onFailure:e=>{i="NETWORK"===e||"TRANSIENT_HTTP"===e,r="REJECTED"===e,RE(t,e)}})&&!i)return;if(r||!i)return}})();AE.set(s,i),i.finally(()=>{AE.get(s)===i&&AE.delete(s)})}function PE(e,t){const s=IE.get(e);if(s&&!(t>=s.staleUntilMs))return s.config;s&&IE.delete(e)}function DE(e,t){const s=e?.trim();if(s&&Array.isArray(t))return t.some(e=>e?.trim()===s)?s:void 0}function ME(e){return!0===e?.p2pEnabled&&!1!==e.status?.effectiveP2pEnabled&&"exhausted"!==e.quota?.status&&"disabled"!==e.quota?.status&&e.trackerUrls.length>0}function _E(e){if(Array.isArray(e))return[...new Set(e.map(e=>e?.trim()).filter(e=>Boolean(e)))].filter(e=>e.startsWith("stun:")||e.startsWith("stuns:")).slice(0,3)}async function OE(e,t={}){const s=e.sdkConfig?.reportUrl?.trim();if(!s)return;const i=await async function(e,t={}){const s=e.protocol??function(e){const t=e.split("?",1)[0]?.toLowerCase()??"";return t.endsWith(".m3u8")?"hls":t.endsWith(".mpd")?"dash":t.endsWith(".mp4")?"mp4":t.endsWith(".mp3")?"mp3":void 0}(e.streamUrl);if("mp4"===s||"mp3"===s)return"vod";if("hls"!==s&&"dash"!==s)return;const i=new AbortController,r=(n=t.manifestProbeTimeoutMs,Number.isFinite(n)?Math.max(200,Math.min(5e3,Math.floor(n))):2e3);var n;let a;const o=new Promise((e,t)=>{a=globalThis.setTimeout(()=>{i.abort(),t(new Error(`fallback manifest probe timed out after ${r} ms`))},r)});try{const r=await Promise.race([FE(e,t,i.signal),o]);return"hls"===s?BE(e,t,i.signal,r):function(e){return/<MPD\b/i.test(e)?/<MPD\b[^>]*\btype\s*=\s*["']dynamic["']/i.test(e)?"live":"vod":void 0}(r)}catch{return}finally{void 0!==a&&globalThis.clearTimeout(a)}}(e,t);if(!i)return;const r=e.sessionId?.trim()||t.sessionIdFactory?.()||`web-fallback-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`,n=M(e.contentId,e.streamUrl),a=e.contentId?.trim()?D(e.contentId):P(e.streamUrl),o=e.sessionToken?.trim()||await(e.sessionTokenProvider?.());return z(s,V({platform:"web",playbackMode:i,runtimeMode:"cdn",protocol:e.protocol,playerType:e.playerType,appId:e.appId,keyId:e.keyId??e.sdkConfig?.keyId,sdkVersion:Q,sessionId:r,contentId:n,swarmId:a,playbackUrl:e.streamUrl,stats:{httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0},capability:e.capability,load:{uploadSlots:0,activeUploadPeers:0,downloadSlots:0,activeDownloadPeers:0},diagnostics:{fallbackCount:1,playbackAuth:b(e.streamUrl,e.sdkConfig?.playbackAuth)}}),{fetcher:t.fetcher,authorizationHeader:o?`Bearer ${o}`:void 0})}function xE(e,t={}){OE(e,t).catch(()=>{})}async function FE(e,t,s,i=e.streamUrl){const r=await(t.manifestFetcher??t.fetcher??fetch)(i,{method:"GET",headers:UE(i,e.streamUrl)?g(e.originHeaders,e.originHeadersProvider,i,"manifest"):{},cache:"no-store",credentials:"same-origin",signal:s});if(!r.ok)throw new Error(`fallback manifest probe failed with ${r.status}`);return r.text()}async function BE(e,t,s,i,r=0){const n=i.replace(/^\uFEFF/,"");if(!/^#EXTM3U(?:\r?\n|$)/.test(n))return;if(/#EXT-X-ENDLIST(?:\r?\n|$)/.test(n))return"vod";const a=function(e,t){const s=e.split(/\r?\n/);for(let e=0;e<s.length;e+=1)if(/^#EXT-X-STREAM-INF:/i.test(s[e]?.trim()??""))for(let i=e+1;i<s.length;i+=1){const e=s[i]?.trim()??"";if(e){if(e.startsWith("#"))break;try{return new URL(e,t).toString()}catch{return}}}}(n,e.streamUrl);return a?r>=1?void 0:BE(e,t,s,await FE(e,t,s,a),r+1):/#EXT-X-STREAM-INF:/i.test(n)?void 0:"live"}function UE(e,t){try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}E(),w(),J(),W(),Z(),E();var NE=class{generation=0;begin(){return this.generation+=1,this.generation}cancel(){this.generation+=1}isCurrent(e){return e===this.generation}assertCurrent(e){if(!this.isCurrent(e))throw new DOMException("Playback session was disposed","AbortError")}};J(),W();var $E=class{accessUrl;appId;keyId;sessionId;platform;fetcher;now;timeoutMs;token;refreshAfterMs=0;expiresAtMs=0;refreshTimer;inFlight;activeAbortController;disposed=!1;authMetrics={attempts:0,successes:0,failures:0,durationMs:0};constructor(e,t={}){var s;this.accessUrl=function(e){const t=e?.trim();if(t)try{const e=new URL(t);for(const t of HE)e.searchParams.delete(t);if("undefined"!=typeof window){const{protocol:t,hostname:s,origin:i}=window.location;if(["localhost","127.0.0.1","::1"].includes(s)&&A(e.hostname)){if("https:"===t){const t=new URL(i);return t.pathname="/access-api/v1/sdk/sessions",t.search=e.search,t.hash="",t.toString()}e.hostname=s}}return e.toString()}catch{return t}}(e.accessUrl),this.appId=e.appId.trim(),this.keyId=e.keyId?.trim()||void 0,this.sessionId=e.sessionId.trim(),this.platform=e.platform,this.fetcher=t.fetcher??globalThis.fetch.bind(globalThis),this.now=t.now??Date.now,this.timeoutMs=(s=t.timeoutMs,Number.isFinite(s)?Math.max(1,Math.min(3e4,Math.floor(s))):8e3)}async getSessionToken(){if(this.accessUrl&&this.appId&&this.sessionId&&!this.disposed)return this.token&&this.now()<this.refreshAfterMs?this.token:this.refreshToken()}async getAuthorizationHeader(){const e=await this.getSessionToken();return e?`Bearer ${e}`:void 0}async getTrackerUrl(e){const t=await this.getSessionToken();if(!this.accessUrl||t)return function(e,t){if(!e)return;const s=t?.trim();if(!s)return e;try{const t=new URL(e);return t.searchParams.set("token",s),t.toString()}catch{return e}}(e,t)??e}diagnostics(){return{...this.authMetrics}}dispose(){this.disposed=!0,this.activeAbortController?.abort(),this.activeAbortController=void 0,void 0!==this.refreshTimer&&(globalThis.clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}async refreshToken(){return this.inFlight||(this.inFlight=this.fetchSessionToken().finally(()=>{this.inFlight=void 0})),this.inFlight}async fetchSessionToken(){if(this.disposed||!this.accessUrl)return;const e=performance.now();let t=!1;this.authMetrics.attempts+=1;try{const e=this.token?function(e){const t=new URL(e);return t.pathname=t.pathname.replace(/\/?$/,"/refresh"),t.toString()}(this.accessUrl):this.accessUrl,s=new AbortController;let i;this.activeAbortController=s;const r=new Promise((e,t)=>{i=globalThis.setTimeout(()=>{s.abort(),t(new Error(`SDK access request timed out after ${this.timeoutMs} ms`))},this.timeoutMs)}),n=new Promise((e,t)=>{s.signal.addEventListener("abort",()=>{t(s.signal.reason??new Error("SDK access request aborted"))},{once:!0})});let a;try{const t=this.fetcher(e,{method:"POST",headers:this.token?{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}:{"Content-Type":"application/json"},body:this.token?void 0:JSON.stringify({appId:this.appId,keyId:this.keyId,sessionId:this.sessionId,platform:this.platform,identity:{platform:this.platform}}),cache:"no-store",signal:s.signal});a=await Promise.race([t,r,n])}finally{void 0!==i&&globalThis.clearTimeout(i),this.activeAbortController===s&&(this.activeAbortController=void 0)}if(this.disposed)return;if(!a.ok)return 401===a.status&&this.token?(this.token=void 0,this.refreshAfterMs=0,this.expiresAtMs=0,this.fetchSessionToken()):void 0;const o=await a.json();if(this.disposed)return;const l=o.sessionToken?.trim();if(!l)return;return this.token=l,this.expiresAtMs=GE(o.expiresAt),this.refreshAfterMs=GE(o.refreshAfter)||Math.max(this.now()+3e4,this.expiresAtMs-3e4),this.scheduleRefresh(),t=!0,l}catch{return}finally{this.authMetrics.durationMs+=Math.max(0,Math.round(performance.now()-e)),t?this.authMetrics.successes+=1:this.authMetrics.failures+=1}}scheduleRefresh(){if(this.disposed)return;if(void 0!==this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0),!this.token)return;const e=this.refreshAfterMs||this.expiresAtMs,t=Math.max(1,e-this.now());this.refreshTimer=globalThis.setTimeout(()=>{this.refreshToken().catch(()=>{})},t),this.refreshTimer?.unref?.()}};function GE(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.floor(1e3*e)}var HE=["app_id","appId","application_id","applicationId","tenant_id","tenantId","key","sdkKey","key_id","keyId","session_id","sessionId","platform","token"],WE="/__meshstream__/v1/",qE=new Map,jE=class{registration;messageListener;segmentProviders=new Map;originHeadersProviders=new Map;statsListeners=new Map;sessionBridgePorts=new Map;bridgeRequests=0;bridgeUnavailableResponses=0;constructor(e){this.registration=e,this.messageListener=e=>{const t=e.data;if("MESHSTREAM_SW_SEGMENT_RESULT"===t?.type&&t.sessionId){const e=this.statsListeners.get(t.sessionId);if(!e)return;const s={sessionId:t.sessionId,resourceId:t.resourceId??"",url:t.url??"",source:"p2p"===t.source?"p2p":"cdn",bytes:Number.isFinite(t.bytes)?Math.max(0,t.bytes):0,status:Number.isFinite(t.status)?t.status:200,p2pBytes:Number.isFinite(t.p2pBytes)?Math.max(0,t.p2pBytes):void 0,cdnBytes:Number.isFinite(t.cdnBytes)?Math.max(0,t.cdnBytes):void 0};try{e(s)}catch{}return}const s=e.ports?.[0];if("MESHSTREAM_SW_ORIGIN_HEADERS_REQUEST"===t?.type&&t.sessionId&&s){let e;try{e=this.originHeadersProviders.get(t.sessionId)?.({url:t.url??"",kind:(i=t.kind,"manifest"===i||"segment"===i||"key"===i||"direct-file"===i||"unknown"===i?t.kind:"unknown")})}catch{}return void s.postMessage({type:"MESHSTREAM_SW_ORIGIN_HEADERS_RESPONSE",headers:e??{}})}var i;if("MESHSTREAM_SW_SEGMENT_REQUEST"!==t?.type||!t.sessionId||!s)return;this.bridgeRequests+=1;const r=this.segmentProviders.get(t.sessionId);if(!r)return n=t.sessionId,void((qE.get(n)??0)>0||(this.bridgeUnavailableResponses+=1,s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})));var n;r({sessionId:t.sessionId,resourceId:t.resourceId??"",url:t.url??"",headers:new Headers(t.headers??{})}).then(e=>{if(!e)return this.bridgeUnavailableResponses+=1,void s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"});e.stream?function(e,t){const s=t.stream;if(!s||!Number.isFinite(t.bytes)||(t.bytes??0)<0)return void e.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"});const i=s.getReader();let r=!1;const n=(s=!1,n=!1)=>{if(r)return;r=!0,s&&i.cancel().catch(()=>{});const a=t.transferStats?.p2pBytes??t.p2pBytes,o=t.transferStats?.cdnBytes??t.cdnBytes,l=(a??0)+(o??0);e.postMessage({type:n?"MESHSTREAM_SW_SEGMENT_STREAM_ERROR":"MESHSTREAM_SW_SEGMENT_STREAM_COMPLETE",source:YE(a,o,t.source),bytes:l>0?l:t.bytes,p2pBytes:a,cdnBytes:o});try{e.close()}catch{}};e.onmessage=async t=>{const s=t.data;if("MESHSTREAM_SW_SEGMENT_STREAM_CANCEL"!==s?.type){if("MESHSTREAM_SW_SEGMENT_STREAM_PULL"===s?.type&&!r)try{const t=await i.read();if(t.done)return void n();const s=function(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}(t.value);e.postMessage({type:"MESHSTREAM_SW_SEGMENT_STREAM_CHUNK",body:s},[s])}catch{n(!0,!0)}}else n(!0)},e.postMessage({type:"MESHSTREAM_SW_SEGMENT_STREAM_START",status:t.status,statusText:t.statusText,headers:t.headers,source:t.source,bytes:t.bytes})}(s,e):e.body?s.postMessage({type:"MESHSTREAM_SW_SEGMENT_RESPONSE",status:e.status,statusText:e.statusText,headers:e.headers,source:e.source,bytes:e.bytes??e.body.byteLength,p2pBytes:e.p2pBytes,cdnBytes:e.cdnBytes,body:e.body},[e.body]):s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})}).catch(()=>{this.bridgeUnavailableResponses+=1,s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})})},navigator.serviceWorker.addEventListener("message",this.messageListener)}async registerSession(e){const t=e.sessionId,s=this.segmentProviders.has(t);this.segmentProviders.set(t,e.segmentProvider??(async()=>{})),e.originHeadersProvider?this.originHeadersProviders.set(t,e.originHeadersProvider):this.originHeadersProviders.delete(t),s||function(e){qE.set(e,(qE.get(e)??0)+1)}(t),e.onSegmentStats&&this.statsListeners.set(t,e.onSegmentStats);const i=new MessageChannel;i.port1.onmessage=this.messageListener,i.port1.start?.(),this.closeSessionBridge(t),this.sessionBridgePorts.set(t,i.port1);try{await ZE(this.registration,{type:"MESHSTREAM_SW_REGISTER_SESSION",protocolVersion:1,sessionId:t,manifestUrl:e.manifestUrl,resourceKind:e.resourceKind,originHeaders:e.originHeaders,p2pTimeoutMs:(r=e.p2pTimeoutMs,Number.isFinite(r)?Math.max(100,Math.floor(r)):5e3)},[i.port2])}catch(e){throw this.closeSessionBridge(t),s||KE(t),this.segmentProviders.delete(t),this.originHeadersProviders.delete(t),this.statsListeners.delete(t),e}var r;const n=function(e,t){return"undefined"==typeof location?`${WE}${encodeURIComponent(e)}/${t}`:new URL(`${WE}${encodeURIComponent(e)}/${t}`,location.origin).toString()}(t,"manifest");let a=!1;return{sessionId:t,manifestUrl:n,dispose:async()=>{a||(a=!0,this.removeSession(t),this.statsListeners.delete(t),await ZE(this.registration,{type:"MESHSTREAM_SW_UNREGISTER_SESSION",protocolVersion:1,sessionId:t}))}}}dispose(){navigator.serviceWorker.removeEventListener("message",this.messageListener);for(const e of this.segmentProviders.keys())KE(e);this.segmentProviders.clear(),this.originHeadersProviders.clear(),this.statsListeners.clear();for(const e of this.sessionBridgePorts.values())VE(e);this.sessionBridgePorts.clear()}diagnostics(){return{serviceWorkerBridgeRequests:this.bridgeRequests,serviceWorkerBridgeUnavailableResponses:this.bridgeUnavailableResponses}}removeSession(e){this.closeSessionBridge(e),this.segmentProviders.delete(e)&&(this.originHeadersProviders.delete(e),KE(e))}closeSessionBridge(e){const t=this.sessionBridgePorts.get(e);t&&(this.sessionBridgePorts.delete(e),VE(t))}};function KE(e){const t=qE.get(e)??0;t<=1?qE.delete(e):qE.set(e,t-1)}function VE(e){try{e.close()}catch{}}function YE(e,t,s){return(e??0)>0&&0===(t??0)||"p2p"===s?"p2p":"cdn"}function zE(){return"undefined"!=typeof navigator&&"serviceWorker"in navigator&&!("undefined"!=typeof isSecureContext&&!isSecureContext)}async function QE(e={}){if(!zE())throw new Error("MeshStream Service Worker requires a secure context and navigator.serviceWorker");const t=e.registration??await navigator.serviceWorker.register(e.url??"/meshstream-sw.js",e.scope?{scope:e.scope}:void 0),s=e.readyTimeoutMs??1e4,i=await async function(e){return function(e,t){return new Promise((s,i)=>{const r=setTimeout(()=>i(new Error("Service Worker activation timed out")),t);e.then(e=>{clearTimeout(r),s(e)},e=>{clearTimeout(r),i(e)})})}(navigator.serviceWorker.ready,e)}(s);return await async function(e,t){!navigator.serviceWorker.controller&&t.active&&await new Promise((t,s)=>{const i=setTimeout(()=>{navigator.serviceWorker.removeEventListener("controllerchange",r),s(new Error("MeshStream Service Worker controller claim timed out"))},e),r=()=>{clearTimeout(i),navigator.serviceWorker.removeEventListener("controllerchange",r),t()};navigator.serviceWorker.addEventListener("controllerchange",r,{once:!0}),navigator.serviceWorker.controller&&r()})}(s,i),await JE(t,s),new jE(t)}async function XE(e){const t=!e.serviceWorker,s=e.serviceWorker??await async function(){if(!zE()||!navigator.serviceWorker.controller)return;const e=await navigator.serviceWorker.ready;try{return await JE(e,750),new jE(e)}catch{return}}();if(!s)return;const i=await s.registerSession({sessionId:e.sessionId??(r="sw",`${r}-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`),manifestUrl:e.manifestUrl,resourceKind:e.resourceKind,originHeaders:e.originHeaders,originHeadersProvider:e.originHeadersProvider,p2pTimeoutMs:e.p2pTimeoutMs,segmentProvider:e.segmentProvider,onSegmentStats:e.onSegmentStats});var r;if(!t)return i;const n=i.dispose;return{sessionId:i.sessionId,manifestUrl:i.manifestUrl,dispose:async()=>{try{await n()}finally{s.dispose()}}}}async function JE(e,t){const s=navigator.serviceWorker.controller??e.active??e.waiting??e.installing;if(!s)throw new Error("MeshStream Service Worker has no active worker");await new Promise((e,i)=>{const r=new MessageChannel,n=()=>{try{r.port1.close()}catch{}},a=setTimeout(()=>{n(),i(new Error("MeshStream Service Worker handshake timed out"))},t);r.port1.onmessage=t=>{clearTimeout(a),n(),"MESHSTREAM_SW_READY"===t.data?.type?e():i(new Error("Invalid MeshStream Service Worker handshake"))},s.postMessage({type:"MESHSTREAM_SW_PING",protocolVersion:1},[r.port2])})}async function ZE(e,t,s=[]){const i=navigator.serviceWorker.controller??e.active??e.waiting??e.installing;if(!i)throw new Error("MeshStream Service Worker is not active");await new Promise((e,r)=>{const n=new MessageChannel,a=()=>{try{n.port1.close()}catch{}},o=setTimeout(()=>{a(),r(new Error("MeshStream Service Worker session acknowledgement timed out"))},2e3);n.port1.onmessage=t=>{clearTimeout(o),a(),"MESHSTREAM_SW_SESSION_READY"===t.data?.type||"MESHSTREAM_SW_SESSION_REMOVED"===t.data?.type?e():r(new Error("Invalid MeshStream Service Worker session acknowledgement"))},i.postMessage(t,[n.port2,...s])})}re(),E(),Mt();var eb=1048576,tb=8388608,sb=class e{swarmId;core;trackerCandidates;createCore;streamIdFactory;manifestUrl;resourceKind;requestTimeoutMs;playbackIsLive;manifestRequestSetup;originHeaders;originHeadersProvider;streams=new Map;segmentIdsByRequestKey=new Map;playbackPositionsByRuntimeId=new Map;completedSources=new Map;eventListeners=new Set;startedAtMs=performance.now();eventTimer;p2pReady=!1;stats={httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0};pendingSegmentLoads=new Map;directChunks=new Map;directFile;disposed=!1;peerCount=0;peerInfoHashes=new Set;trackerErrors=0;lastTrackerError;peerConnectErrors=0;firstPeerConnectMs;fallbackCount=0;lastPeerError;lastErrorAtMs;ice={attempts:0,successes:0,failures:0,durationMs:0};peerSegmentAnnouncements=0;peerAnnouncedSegments=0;peerHttpLoadingSegments=0;p2pAttempts=0;httpAttempts=0;p2pErrors=0;httpErrors=0;p2pUploaded=0;p2pSegmentUploadSuccesses=0;p2pSegmentUploadFailures=0;lastLoadedBytes=0;segmentRequests=0;runtimeIdMisses=0;segmentLoadSuccesses=0;segmentLoadTimeouts=0;indexedSegments=0;activeTrackerIndex=0;failoverInFlight=!1;coreReady=Promise.resolve();coreGeneration=0;coreRebuildInFlight;coreRebuildGeneration;lastCoreRebuildAttemptAtMs=0;p2pEnabled=!0;directFileLoadQueue=Promise.resolve();hasIssuedCoreLoad=!1;constructor(e,t,s,i){this.swarmId=e.swarmId,this.manifestUrl=new URL(e.manifestUrl,globalThis.location?.href??"http://localhost/").toString(),this.resourceKind="direct-file"===e.resourceKind?"direct-file":"hls","direct-file"===this.resourceKind&&(this.playbackIsLive=!1),this.requestTimeoutMs=ub(e.requestTimeoutMs),this.streamIdFactory=i,this.originHeaders=e.originHeaders,this.originHeadersProvider=e.originHeadersProvider,this.manifestRequestSetup=u(e.originHeaders,e.originHeadersProvider,e.manifestUrl),this.trackerCandidates=[...new Set([e.trackerUrl,...e.trackerUrls??[]].map(e=>e?.trim()).filter(e=>Boolean(e)))],this.createCore=s,this.core=t,this.bindCoreEvents()}bindCoreEvents(){const e=this.core,t=this.coreGeneration;e.setManifestResponseUrl(this.manifestUrl),e.addEventListener("onSegmentLoaded",e=>{if(t!==this.coreGeneration)return;this.lastLoadedBytes=e.bytesLength;const s="p2p"===e.downloadSource?"p2p":"cdn";this.completedSources.set(e.segment.runtimeId,s),"p2p"===s?(this.stats.p2pDownloaded+=e.bytesLength,this.stats.p2pSegmentDownloadSuccesses+=1):(this.stats.httpDownloaded+=e.bytesLength,this.stats.httpSegmentDownloadSuccesses+=1,0===this.peerCount&&(this.fallbackCount+=1),this.notify(t=>t.onCdnFallback?.(e.bytesLength)))}),e.addEventListener("onSegmentStart",e=>{t===this.coreGeneration&&("p2p"===e.downloadSource?this.p2pAttempts+=1:this.httpAttempts+=1)}),e.addEventListener("onSegmentError",e=>{t===this.coreGeneration&&("p2p"===e.downloadSource?(this.p2pErrors+=1,this.stats.p2pSegmentDownloadFailures+=1):(this.httpErrors+=1,this.stats.httpSegmentDownloadFailures+=1))}),e.addEventListener("onChunkUploaded",e=>{t===this.coreGeneration&&(this.p2pUploaded+=e,this.p2pSegmentUploadSuccesses+=1,this.stats.p2pUploaded+=e,this.stats.p2pSegmentUploadSuccesses+=1)}),e.addEventListener("onPeerConnect",e=>{t===this.coreGeneration&&(this.ice.attempts+=1,this.ice.successes+=1,this.peerCount+=1,this.peerInfoHashes.add(e.infoHash),this.stats.connectedPeers=this.peerCount,this.notify(e=>e.onPeerCountChanged?.(this.peerCount)),!this.p2pReady&&this.p2pEnabled&&(this.firstPeerConnectMs??=this.elapsedSinceStartMs(),this.p2pReady=!0,this.notify(e=>e.onP2pReady?.()),this.notifyPlaybackState("p2p-ready")))}),e.addEventListener("onPeerClose",e=>{t===this.coreGeneration&&(this.peerCount=Math.max(0,this.peerCount-1),this.peerInfoHashes.delete(e.infoHash),this.stats.connectedPeers=this.peerCount,this.notify(e=>e.onPeerCountChanged?.(this.peerCount)),this.p2pReady&&0===this.peerCount&&this.notifyUnavailable(this.p2pEnabled?"NO_PEERS":"DISABLED"))}),e.addEventListener("onTrackerError",e=>{t===this.coreGeneration&&(this.trackerErrors+=1,this.stats.trackerErrors=this.trackerErrors,this.lastTrackerError=String(e.error?.message??e.error??"tracker request failed").slice(0,240),this.notify(e=>e.onTrackerError?.(this.trackerErrors)),this.notifyUnavailable("TRACKER_ERROR"),this.failoverTracker(e.trackerUrl))}),e.addEventListener("onPeerConnectError",e=>{t===this.coreGeneration&&(this.peerConnectErrors+=1,this.stats.peerConnectErrors=this.peerConnectErrors,this.ice.attempts+=1,this.ice.failures+=1,this.lastPeerError=function(e){if(e instanceof Error)return e.message.slice(0,240);if("string"==typeof e)return e.slice(0,240);try{return JSON.stringify(e??"peer connection failed").slice(0,240)}catch{return String(e??"peer connection failed").slice(0,240)}}(e),this.lastErrorAtMs=Date.now(),this.notify(e=>e.onPeerConnectError?.(this.peerConnectErrors)))}),e.addEventListener("onPeerSegmentsAnnouncement",(e,s,i,r,n)=>{t===this.coreGeneration&&(this.peerSegmentAnnouncements+=1,this.peerAnnouncedSegments=Number(r)||0,this.peerHttpLoadingSegments=Number(n)||0)})}static async create(t){const s=await Promise.resolve().then(()=>($o(),_t)),i=ub(t.requestTimeoutMs),r={swarmId:t.swarmId,rtcConfig:{iceServers:t.iceServers??(t.sdkConfig?.iceServers?.length?[{urls:t.sdkConfig.iceServers}]:ee())},httpRequestSetup:u(t.originHeaders,t.originHeadersProvider,t.manifestUrl),customSegmentStorageFactory:ne,httpDownloadInitialTimeoutMs:Math.min(3e3,i),highDemandTimeWindow:0,httpDownloadTimeWindow:0,p2pDownloadTimeWindow:15e3,preferP2PForEngineRequest:!0,simultaneousP2PDownloads:3,webRtcMaxMessageSize:16384,p2pNotReceivingBytesTimeoutMs:2e3,webRtcConnectionTimeoutMs:15e3},n=e=>{const t=new s.Core({...r,announceTrackers:[e]});return t.setIsLive(!1),t},a=n(t.trackerUrl);return new e(t,a,n,s.generateStreamShortId)}async failoverTracker(e){if(this.disposed||this.failoverInFlight||this.trackerCandidates.length<2)return;const t=this.trackerCandidates.indexOf(e),s=(t>=0?t:this.activeTrackerIndex)+1;if(!(s>=this.trackerCandidates.length)){this.failoverInFlight=!0;try{this.coreGeneration+=1,this.core.destroy(),this.activeTrackerIndex=s,this.peerCount=0,this.peerInfoHashes.clear(),this.core=this.createCore(this.trackerCandidates[s]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild(),await this.coreReady}finally{this.failoverInFlight=!1}}}async rebuildCoreState(e=this.coreGeneration){const t=this.core;"direct-file"!==this.resourceKind?await this.indexPlaylist(this.manifestUrl,new Set,void 0,t,e):this.rebuildDirectFileStream(t,e)}scheduleCoreRebuild(){const e=this.coreGeneration;if(this.coreRebuildInFlight&&this.coreRebuildGeneration===e)return this.coreRebuildInFlight;const t=this.rebuildCoreState(e).catch(()=>{});return this.coreRebuildInFlight=t,this.coreRebuildGeneration=e,t.finally(()=>{this.coreRebuildInFlight===t&&(this.coreRebuildInFlight=void 0,this.coreRebuildGeneration=void 0)}),t}async ensureCoreState(){if(this.disposed)return;if(this.coreRebuildInFlight)return void await this.coreRebuildInFlight;const e=Date.now();e-this.lastCoreRebuildAttemptAtMs<1e3||(this.lastCoreRebuildAttemptAtMs=e,await this.scheduleCoreRebuild())}async initialize(){"direct-file"!==this.resourceKind?await this.indexPlaylist(this.manifestUrl,new Set):await this.initializeDirectFile()}createSegmentProvider(){return e=>this.provideSegment(e)}addEventListener(e){this.eventListeners.add(e),fb(()=>e.onPlaybackStateChanged?.(this.p2pEnabled&&this.p2pReady?"p2p-ready":this.p2pEnabled?"connecting":"cdn-fallback")),void 0===this.eventTimer&&(this.eventTimer=globalThis.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)fb(()=>t.onStatistics?.(e))},1e3))}removeEventListener(e){this.eventListeners.delete(e),0===this.eventListeners.size&&void 0!==this.eventTimer&&(globalThis.clearInterval(this.eventTimer),this.eventTimer=void 0)}setP2pEnabled(e){if(this.disposed||this.p2pEnabled===e)return;const t=this.peerCount>0;if(this.p2pEnabled=e,this.hasIssuedCoreLoad=!1,this.coreGeneration+=1,this.core.destroy(),this.peerCount=0,this.peerInfoHashes.clear(),this.stats.connectedPeers=0,this.completedSources.clear(),t&&this.notify(e=>e.onPeerCountChanged?.(0)),!e)return this.notifyUnavailable("DISABLED"),void(this.coreReady=Promise.resolve());this.core=this.createCore(this.trackerCandidates[this.activeTrackerIndex]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild()}diagnostics(){return{p2pEnabled:this.p2pEnabled,directFileReady:Boolean(this.directFile),connectedPeers:this.peerCount,peerInfoHashes:[...this.peerInfoHashes].sort(),trackerErrors:this.trackerErrors,lastTrackerError:this.lastTrackerError,peerConnectErrors:this.peerConnectErrors,firstPeerConnectMs:this.firstPeerConnectMs,fallbackCount:this.fallbackCount,lastPeerError:this.lastPeerError,lastErrorAtMs:this.lastErrorAtMs,ice:{...this.ice},peerSegmentAnnouncements:this.peerSegmentAnnouncements,peerAnnouncedSegments:this.peerAnnouncedSegments,peerHttpLoadingSegments:this.peerHttpLoadingSegments,p2pAttempts:this.p2pAttempts,httpAttempts:this.httpAttempts,p2pErrors:this.p2pErrors,httpErrors:this.httpErrors,p2pUploaded:this.p2pUploaded,p2pSegmentUploadSuccesses:this.p2pSegmentUploadSuccesses,p2pSegmentUploadFailures:this.p2pSegmentUploadFailures,lastLoadedBytes:this.lastLoadedBytes,segmentRequests:this.segmentRequests,runtimeIdMisses:this.runtimeIdMisses,segmentLoadSuccesses:this.segmentLoadSuccesses,segmentLoadTimeouts:this.segmentLoadTimeouts,indexedSegments:this.indexedSegments}}statistics(){return{...this.stats}}isLive(){return!0===this.playbackIsLive}isPlaybackModeKnown(){return void 0!==this.playbackIsLive}dispose(){this.disposed||(this.disposed=!0,void 0!==this.eventTimer&&globalThis.clearInterval(this.eventTimer),this.eventTimer=void 0,this.streams.clear(),this.segmentIdsByRequestKey.clear(),this.playbackPositionsByRuntimeId.clear(),this.peerInfoHashes.clear(),this.completedSources.clear(),this.pendingSegmentLoads.clear(),this.directChunks.clear(),this.directFile=void 0,this.core.destroy(),this.eventListeners.clear())}notifyUnavailable(e){(this.p2pReady||"TRACKER_ERROR"===e||"DISABLED"===e)&&(this.p2pReady=!1,this.notify(t=>t.onP2pUnavailable?.(e)),this.notifyPlaybackState("cdn-fallback"))}notify(e){for(const t of this.eventListeners)fb(()=>e(t))}notifyPlaybackState(e){this.notify(t=>t.onPlaybackStateChanged?.(e))}elapsedSinceStartMs(){return Math.max(0,Math.round(performance.now()-this.startedAtMs))}async provideSegment(e){if(!this.p2pEnabled)return;if("direct-file"===this.resourceKind&&this.isLargeDirectFileRange(e))return this.loadSegmentResponse(e);const t=`${e.url}|${e.headers.get("range")??""}`;let s=this.pendingSegmentLoads.get(t);s||(s=this.loadSegmentResponse(e).finally(()=>{this.pendingSegmentLoads.get(t)===s&&this.pendingSegmentLoads.delete(t)}),this.pendingSegmentLoads.set(t,s));const i=await s;return i?function(e){return e.body?{...e,body:e.body.slice(0)}:e}(i):void 0}async loadSegmentResponse(e){if(this.disposed)return;if(this.segmentRequests+=1,"direct-file"===this.resourceKind)return this.loadDirectFileRange(e);await this.coreReady,await this.resetInitialCoreRequestWindow();let t=this.segmentIdsByRequestKey.get(ab(e.url,e.headers));if(t&&this.core.isSegmentLoadable(t)||(await this.ensureCoreState(),t=this.segmentIdsByRequestKey.get(ab(e.url,e.headers))),!t||!this.core.isSegmentLoadable(t))return void(this.runtimeIdMisses+=1);const s=this.core,i=await this.loadSegmentFromCore(s,t,this.requestTimeoutMs);if(!i)return void(this.segmentLoadTimeouts+=1);this.segmentLoadSuccesses+=1;const r=ob(e.headers.get("range")),n=this.completedSources.get(t)??"p2p",a={"content-length":String(i.byteLength),"content-type":"application/octet-stream"};return r&&(a["content-range"]=`bytes ${r.start}-${r.start+i.byteLength-1}/*`),{body:i,status:r?206:200,headers:a,source:n}}async initializeDirectFile(){const e=await this.fetchDirectFileMetadata("HEAD");let t=function(e){if(!e.ok||!/\bbytes\b/i.test(e.headers.get("accept-ranges")??""))return;const t=hb(e.headers.get("content-length"));return t?{contentLength:t,contentType:db(e)}:void 0}(e);if(!t&&(e.ok||405===e.status||501===e.status)){await cb(e);const s=await this.fetchDirectFileMetadata("GET");if(206!==s.status)throw await cb(s),new Error(`Direct media Range probe failed with ${s.status}`);if(t=function(e){const t=/^bytes\s+0-0\/(\d+)$/i.exec(e.headers.get("content-range")?.trim()??""),s=hb(t?.[1]??null);return s?{contentLength:s,contentType:db(e)}:void 0}(s),await cb(s),!t)throw new Error("Direct media P2P requires a valid Content-Range response header")}if(!t)throw new Error(`Direct media metadata request failed with ${e.status}`);this.directFile={contentLength:t.contentLength,contentType:t.contentType,streamId:"direct-file",streamIndex:this.streamIdFactory({bitrate:0,format:"direct-file",contentLength:t.contentLength})},this.rebuildDirectFileStream(this.core,this.coreGeneration)}async fetchDirectFileMetadata(e){const t="undefined"!=typeof AbortController?new AbortController:void 0,s=t?globalThis.setTimeout(()=>t.abort(),Math.min(this.requestTimeoutMs,5e3)):void 0;try{return await fetch(this.createDirectFileMetadataRequest(e,t?.signal))}catch(e){if(t?.signal.aborted)throw new Error("Direct media metadata request timed out");throw e}finally{void 0!==s&&globalThis.clearTimeout(s)}}createDirectFileMetadataRequest(e,t){const s=new Headers;for(const[e,t]of Object.entries(g(this.originHeaders,this.originHeadersProvider,this.manifestUrl,"direct-file")))try{s.set(e,t)}catch{}return"GET"===e?s.set("range","bytes=0-0"):s.delete("range"),new Request(this.manifestUrl,{method:e,headers:s,signal:t})}rebuildDirectFileStream(e,t){const s=this.directFile;s&&!this.disposed&&t===this.coreGeneration&&e===this.core&&(e.addStreamIfNoneExists({runtimeId:s.streamId,type:"main",index:s.streamIndex}),e.setIsLive(!1),e.updateStream(s.streamId,this.directChunks.values()),this.indexedSegments=this.directChunks.size)}async loadDirectFileRange(e){const t=this.directFile;if(!t||new URL(e.url,this.manifestUrl).toString()!==this.manifestUrl)return;const s=lb(e.headers.get("range"),t.contentLength);if(!s)return;if(s.end-s.start+1>tb)return this.streamDirectFileRange(s,t);await this.coreReady;const i=Math.floor(s.start/eb),r=Math.floor(s.end/eb),n=[];for(let e=i;e<=r;e+=1){const t=await this.loadDirectFileChunk(e);if(!t)return;n.push(t)}const a=function(e,t){const s=new Uint8Array(t.end-t.start+1);let i=0;for(const{segment:r,data:n}of e){const e=r.byteRange;if(!e)return;const a=Math.max(t.start,e.start),o=Math.min(t.end,e.end);if(o<a)continue;const l=a-e.start,h=o-a+1;if(l+h>n.byteLength||i+h>s.byteLength)return;s.set(new Uint8Array(n,l,h),i),i+=h}return i===s.byteLength?s.buffer:void 0}(n,s);if(!a||a.byteLength!==s.end-s.start+1)return;const o=function(e,t){let s=0,i=0;for(const r of e){const e=r.segment.byteRange;if(!e)continue;const n=Math.max(t.start,e.start),a=Math.min(t.end,e.end);if(a<n)continue;const o=a-n+1;"p2p"===r.source?s+=o:i+=o}return{p2pBytes:s,cdnBytes:i}}(n,s);return{body:a,status:206,headers:{"accept-ranges":"bytes","content-length":String(a.byteLength),"content-range":`bytes ${s.start}-${s.end}/${t.contentLength}`,"content-type":t.contentType},source:o.p2pBytes===a.byteLength?"p2p":"cdn",p2pBytes:o.p2pBytes,cdnBytes:o.cdnBytes}}isLargeDirectFileRange(e){const t=this.directFile;if(!t)return!1;const s=lb(e.headers.get("range"),t.contentLength);return Boolean(s&&s.end-s.start+1>tb)}streamDirectFileRange(e,t){const s={p2pBytes:0,cdnBytes:0};let i=Math.floor(e.start/eb);const r=Math.floor(e.end/eb);let n=!1;return{stream:new ReadableStream({pull:async t=>{if(n||i>r)return void t.close();const a=await this.loadDirectFileChunk(i);if(i+=1,!a?.segment.byteRange)return void t.error(new Error("Direct media chunk is unavailable"));const o=Math.max(e.start,a.segment.byteRange.start),l=Math.min(e.end,a.segment.byteRange.end),h=o-a.segment.byteRange.start,d=l-o+1;if(d<=0||h+d>a.data.byteLength)return void t.error(new Error("Direct media chunk range is invalid"));const c=new Uint8Array(a.data,h,d).slice();"p2p"===a.source?s.p2pBytes+=c.byteLength:s.cdnBytes+=c.byteLength,t.enqueue(c)},cancel:()=>{n=!0}}),bytes:e.end-e.start+1,status:206,headers:{"accept-ranges":"bytes","content-length":String(e.end-e.start+1),"content-range":`bytes ${e.start}-${e.end}/${t.contentLength}`,"content-type":t.contentType},source:"cdn",transferStats:s}}async loadDirectFileChunk(e){const t=this.ensureDirectFileChunk(e);return this.enqueueDirectFileLoad(async()=>{await this.resetInitialCoreRequestWindow();let e=this.core;if(e.isSegmentLoadable(t.runtimeId)||(await this.ensureCoreState(),e=this.core),!e.isSegmentLoadable(t.runtimeId))return void(this.runtimeIdMisses+=1);const s=await this.loadSegmentFromCore(e,t.runtimeId,this.requestTimeoutMs);if(s&&s.byteLength===t.byteRange.end-t.byteRange.start+1)return this.segmentLoadSuccesses+=1,{segment:t,data:s,source:this.completedSources.get(t.runtimeId)??"cdn"};this.segmentLoadTimeouts+=1})}async enqueueDirectFileLoad(e){const t=this.directFileLoadQueue.then(e,e);return this.directFileLoadQueue=t.then(()=>{},()=>{}),t}async resetInitialCoreRequestWindow(){this.disposed||this.hasIssuedCoreLoad||(this.hasIssuedCoreLoad=!0,this.coreGeneration+=1,this.core.destroy(),this.peerCount=0,this.peerInfoHashes.clear(),this.completedSources.clear(),this.core=this.createCore(this.trackerCandidates[this.activeTrackerIndex]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild(),await this.coreReady)}ensureDirectFileChunk(e){const t=this.directFile;if(!t)throw new Error("Direct media metadata is unavailable");const s=this.directChunks.get(e);if(s)return this.directChunks.delete(e),this.directChunks.set(e,s),s;const i=[];for(;this.directChunks.size>=256;){const e=this.directChunks.entries().next();if(e.done)break;this.directChunks.delete(e.value[0]),i.push(e.value[1].runtimeId),this.completedSources.delete(e.value[1].runtimeId),this.playbackPositionsByRuntimeId.delete(e.value[1].runtimeId)}const r=e*eb,n=Math.min(r+eb-1,t.contentLength-1),a={runtimeId:`${this.manifestUrl}|${r}-${n}`,externalId:e,url:this.manifestUrl,byteRange:{start:r,end:n},startTime:e,endTime:e+1};return this.directChunks.set(e,a),this.playbackPositionsByRuntimeId.set(a.runtimeId,e),this.core.addStreamIfNoneExists({runtimeId:t.streamId,type:"main",index:t.streamIndex}),this.core.updateStream(t.streamId,[a],i),this.indexedSegments=this.directChunks.size,a}loadSegmentFromCore(e,t,s){return new Promise(i=>{let r=!1;const n=e=>{r||(r=!0,clearTimeout(a),i(e))},a=globalThis.setTimeout(()=>{e.abortSegmentLoading(t),n(void 0)},s);try{const s=this.playbackPositionsByRuntimeId.get(t)??-1,i={onSuccess:e=>n(e.data),onError:()=>n(void 0)};e.updatePlayback(s,1),e.loadSegment(t,i)}catch{n(void 0)}})}async refreshPlaylists(){const e=Date.now(),t=[...this.streams.values()].filter(t=>t.isLive&&e-t.lastLoadedAtMs>=2e3).map(e=>e.url);await Promise.all(t.map(e=>this.indexPlaylist(e,new Set)))}async indexPlaylist(e,t,s,i=this.core,r=this.coreGeneration){const n=new URL(e,this.manifestUrl).toString();if(t.has(n)||this.disposed||r!==this.coreGeneration||i!==this.core)return;t.add(n);const a="undefined"!=typeof AbortController?new AbortController:void 0,o=a?globalThis.setTimeout(()=>a.abort(),5e3):void 0,l=await(this.manifestRequestSetup?.(n,void 0,a?.signal,void 0));let h;try{h=await fetch(l??new Request(n,{signal:a?.signal}))}finally{void 0!==o&&globalThis.clearTimeout(o)}if(!h.ok)return;const d=await h.text();if(this.disposed||r!==this.coreGeneration||i!==this.core)return;const c=function(e,t,s,i){const r=e.split(/\r?\n/),n=[],a=[];let o,l,h=0,d=0,c=0,u=0,f=0,g=!0;for(let e=0;e<r.length;e+=1){const s=r[e].trim();if(!s)continue;if(s.startsWith("#EXT-X-MEDIA-SEQUENCE:")){d=Number(s.slice(22))||0,c=d;continue}if("#EXT-X-ENDLIST"===s){g=!1;continue}if(s.startsWith("#EXTINF:")){u=Number(s.slice(8).split(",")[0])||0;continue}if(s.startsWith("#EXT-X-BYTERANGE:")){l=nb(s.slice(17));continue}if(s.startsWith("#EXT-X-STREAM-INF:")){o=rb(s.slice(18));continue}if(s.startsWith("#EXT-X-MEDIA:")){const e=rb(s.slice(13));e.URI&&n.push({url:new URL(e.URI,t).toString(),index:i({bitrate:0,codecs:e.CODECS,language:e.LANGUAGE,channels:e.CHANNELS,name:e.NAME})});continue}if(s.startsWith("#"))continue;const m=new URL(s,t).toString();if(o){n.push({url:m,index:ib(o,i)}),o=void 0;continue}const p=l?{start:l.offset??h,end:(l.offset??h)+l.length-1}:void 0;p&&(h=p.end+1),l=void 0;const v=p?`${m}|${p.start}-${p.end}`:m;a.push({runtimeId:v,url:m,externalId:c,byteRange:p,startTime:f,endTime:f+u}),c+=1,f+=u}return{children:n,segments:a,isLive:g}}(d,n,0,this.streamIdFactory);if(c.children.length)await Promise.all(c.children.map(e=>this.indexPlaylist(e.url,t,e,i,r)));else if(!this.disposed&&r===this.coreGeneration&&i===this.core){i.addStreamIfNoneExists({runtimeId:n,type:"main",index:s?.index??this.streamIdFactory({bitrate:0})}),this.playbackIsLive=c.isLive,i.setIsLive(c.isLive),i.updateStream(n,c.segments),this.streams.set(n,{url:n,isLive:c.isLive,lastLoadedAtMs:Date.now()});for(const e of c.segments)this.segmentIdsByRequestKey.set(ab(e.url,e.byteRange),e.runtimeId),this.playbackPositionsByRuntimeId.set(e.runtimeId,e.startTime);this.indexedSegments=this.segmentIdsByRequestKey.size}}};function ib(e,t){const s=e.RESOLUTION?.split("x");return t({bitrate:Number(e["AVERAGE-BANDWIDTH"]??e.BANDWIDTH)||0,codecs:e.CODECS,width:Number(s?.[0])||void 0,height:Number(s?.[1])||void 0,frameRate:e["FRAME-RATE"],videoRange:e["VIDEO-RANGE"]})}function rb(e){const t={};for(const s of e.matchAll(/([A-Z0-9-]+)=("[^"]*"|[^,]*)/g))t[s[1]]=s[2].replace(/^"|"$/g,"");return t}function nb(e){const[t,s]=e.split("@"),i=Number(t);if(!Number.isFinite(i)||i<=0)return;const r=void 0===s?void 0:Number(s);return{length:i,...Number.isFinite(r)?{offset:r}:{}}}function ab(e,t){const s=t instanceof Headers?ob(t.get("range")):t;return s?`${e}|${s.start}-${s.end}`:e}function ob(e){const t=/^bytes=(\d+)-(\d+)$/.exec(e??"");if(t)return{start:Number(t[1]),end:Number(t[2])}}function lb(e,t){const s=/^bytes=(\d+)-(\d*)$/i.exec(e?.trim()??"");if(!s)return;const i=Number(s[1]);if(!Number.isSafeInteger(i)||i<0||i>=t)return;const r=s[2]?Number(s[2]):t-1;return!Number.isSafeInteger(r)||r<i?void 0:{start:i,end:Math.min(r,t-1)}}function hb(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function db(e){return e.headers.get("content-type")?.split(";")[0]?.trim()||"video/mp4"}async function cb(e){try{await(e.body?.cancel())}catch{}}function ub(e){return Number.isFinite(e)?Math.max(100,Math.floor(e)):5e3}function fb(e){try{e()}catch{}}function gb(e,t=!1){if(t&&!e)return"SDK_CONFIG_PENDING";switch(e?.status?.reason){case"KEY_P2P_DISABLED":return"KEY_P2P_DISABLED";case"QUOTA_EXHAUSTED":return"QUOTA_EXHAUSTED";case"QUOTA_DISABLED":return"QUOTA_DISABLED";default:return"SDK_CONFIG_UNAVAILABLE"}}W(),Z();var mb=class{key;url;video;options;ownsHlsInstance;hls;p2p;serviceWorkerClient;serviceWorkerSession;serviceWorkerP2pEngine;serviceWorkerStats={};serviceWorkerReportUrl;serviceWorkerReportTimer;serviceWorkerReportInFlight=!1;serviceWorkerReportTask;serviceWorkerTeardownTask;serviceWorkerHasReportedContext=!1;serviceWorkerTrackerUrl;serviceWorkerAppId;serviceWorkerKeyId;serviceWorkerSwarmId;serviceWorkerUploadSlots=0;serviceWorkerDownloadSlots=0;serviceWorkerPagehideHandler=()=>{this.reportServiceWorkerStats()};sessionId="";sessionTokenManager;mode="unsupported";p2pEnabledOverride;eventListeners=new Set;fallbackStatsTimer;cdnStats={};cdnStatsHls;cdnFragLoadingHandler=()=>{this.cdnStats.httpAttempts=(this.cdnStats.httpAttempts??0)+1};cdnFragLoadedHandler=(e,t)=>{const s=t,i=Number(s?.stats?.loaded);Number.isFinite(i)&&i>0&&(this.cdnStats.httpDownloaded=(this.cdnStats.httpDownloaded??0)+i,this.cdnStats.lastLoadedBytes=i),this.cdnStats.httpSegmentDownloadSuccesses=(this.cdnStats.httpSegmentDownloadSuccesses??0)+1};cdnFragLoadErrorHandler=()=>{this.cdnStats.httpSegmentDownloadFailures=(this.cdnStats.httpSegmentDownloadFailures??0)+1,this.cdnStats.httpErrors=(this.cdnStats.httpErrors??0)+1};playbackState="idle";lifecycle=new NE;startPromise;startResult;constructor(e){this.key=e.key?.trim()||"",this.url=e.url.trim(),this.video=e.video,this.options=e,this.ownsHlsInstance=!e.hlsjsInstance}get p2pClient(){return this.p2p}get playbackMode(){return this.mode}start(){if(this.startResult)return Promise.resolve(this.startResult);if(this.startPromise)return this.startPromise;this.setPlaybackState("initializing");const e=this.startInternal(this.lifecycle.begin());return this.startPromise=e,e.then(t=>{this.startPromise===e&&(this.startResult=t)}).finally(()=>{this.startPromise===e&&(this.startPromise=void 0)}).catch(()=>{}),e}async startInternal(e){if(!this.options.key?.trim())throw new Error("MeshStreamHlsPlayer requires key");if(!this.url)throw new Error("MeshStreamHlsPlayer requires url");this.teardown();const t=this.options.dependencies??{},s=this.effectiveP2pEnabled(),i=await async function(e,t,s={},i=0){const r=Promise.resolve().then(()=>e(t,s)).catch(()=>{}),n=(a=i,Number.isFinite(a)?Math.max(0,Math.min(2e3,Math.floor(a))):0);var a;let o;const l=new Promise(e=>{o=setTimeout(()=>e({timedOut:!0}),n),o.unref?.()});try{return await Promise.race([r.then(e=>({config:e,timedOut:!1})),l])}finally{void 0!==o&&clearTimeout(o)}}(t.loadSdkConfig??kE,{bootstrapUrl:this.options.bootstrapUrl,key:this.options.key,platform:"web",contentId:(r=this.options.contentId,n=this.url,r?.trim()||P(n))},void 0,0);var r,n;const a=i.config;this.lifecycle.assertCurrent(e);const o=a?.applicationId?.trim()||this.key,l=a?.keyId?.trim()||void 0,h=`web-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`;this.sessionId=h,this.sessionTokenManager=a?.accessUrl?new $E({accessUrl:a.accessUrl,appId:o,keyId:l,sessionId:h,platform:"web"}):void 0;const d=Eb(this.options.mimeType,this.url);if(d&&this.options.hlsjsInstance)throw new Error("hlsjsInstance can only be used with HLS playback");const c=(t.detectCapability??(()=>function(e={}){const t=e.protocol??"hls",s=e.userAgent??("undefined"==typeof navigator?"":navigator.userAgent),i=function(e){const t=e.toLowerCase();return t.includes("edg/")?"edge":t.includes("firefox/")?"firefox":t.includes("chrome/")||t.includes("crios/")||t.includes("chromium/")?"chrome":t.includes("safari/")&&t.includes("version/")?"safari":"unknown"}(s),r=function(e){const t=e.toLowerCase();return t.includes("iphone")||t.includes("ipad")||t.includes("ipod")?"ios":t.includes("android")?"android":t.includes("mac os x")||t.includes("macintosh")?"macos":t.includes("windows")?"windows":"unknown"}(s),n=bE(e.hasWebSocket,EE("WebSocket"))&&bE(e.hasRtcPeerConnection,EE("RTCPeerConnection")||EE("webkitRTCPeerConnection"))&&bE(e.hasRtcDataChannel,function(){const e=globalThis,t=e.RTCPeerConnection??e.webkitRTCPeerConnection;return"function"==typeof t?.prototype?.createDataChannel}()),a=bE(e.hasMediaSource,EE("MediaSource")||EE("ManagedMediaSource")),o=bE(e.hasSecureContext,"undefined"==typeof isSecureContext||isSecureContext),l=bE(e.hasServiceWorker,"undefined"!=typeof navigator&&"serviceWorker"in navigator)&&o;if(!n)return{supported:!1,reason:"WEBRTC_UNSUPPORTED",recommendedMode:"cdn",browser:i,os:r,mseSupported:a,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o};if("hls"===t&&!a){const e="safari"===i&&"ios"===r;return{supported:!1,reason:e?"SAFARI_HLS_MSE_UNSUPPORTED":"MSE_UNSUPPORTED",recommendedMode:e?"native-hls-cdn":"cdn",browser:i,os:r,mseSupported:!1,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o}}return{supported:!0,recommendedMode:"p2p",browser:i,os:r,mseSupported:a,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o}}({protocol:bb(this.options.mimeType,this.url)??"hls"})))(),u=this.options.transportPreference??"auto";if(d)return this.startDirectFilePlayback(c,a,i.timedOut,t,o,l,u,s,e);if("cdn"===u)return this.startCdnFallback(c,a,t,e,"P2P_DISABLED");if(!c.supported){const s={appId:o,keyId:l,streamUrl:this.url,contentId:this.options.contentId,protocol:"hls",playerType:"native-hls-cdn"===c.recommendedMode?"native":"hlsjs",sdkConfig:a,sessionId:h,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,capability:c};if(t.reportFallback?await t.reportFallback({...s,sessionToken:await(this.sessionTokenManager?.getSessionToken())}):xE({...s,sessionTokenProvider:()=>this.sessionTokenManager?.getSessionToken()}),this.lifecycle.assertCurrent(e),!this.options.hlsjsInstance&&"mse"!==u&&("service-worker"===u||"MSE_UNSUPPORTED"===c.reason||"SAFARI_HLS_MSE_UNSUPPORTED"===c.reason)){const s=await this.startServiceWorkerFallback(c,a,i.timedOut,t,e);if(s.playback)return s.playback}return this.startCdnFallback(c,a,t,e,"CAPABILITY_UNSUPPORTED")}if("service-worker"===u){const s=await this.startServiceWorkerFallback(c,a,i.timedOut,t,e);return s.playback?s.playback:this.startCdnFallback(c,a,t,e,s.fallbackReason??"P2P_INITIALIZATION_FAILED")}if(!1===s)return this.startCdnFallback(c,a,t,e,"P2P_DISABLED");if(!ME(a))return this.startCdnFallback(c,a,t,e,gb(a,i.timedOut));const g=I(void 0,a.trackerUrls,o,this.options.contentId?.trim()?`${D(this.options.contentId)}-b${a.defaults?.swarmBucketId??0}`:F(this.url,h,a.defaults?.swarmBucketCount,a.defaults?.swarmBucketId),l,a.primaryTrackerUrl),m=(await Promise.all(g.map(e=>this.sessionTokenManager?this.sessionTokenManager.getTrackerUrl(e):Promise.resolve(e)))).filter(e=>Boolean(e?.trim()));this.lifecycle.assertCurrent(e);const p=m[0];if(!p)return this.startCdnFallback(c,a,t,e,"TRACKER_UNAVAILABLE");const v=this.options.hlsjsInstance??await(t.createHls??vb)(this.options.hlsConfig);let y;this.lifecycle.isCurrent(e)||(this.options.hlsjsInstance||v.destroy(),this.lifecycle.assertCurrent(e)),this.options.hlsjsInstance||this.options.onHlsCreated?.(v);try{y=await(t.createP2pClient??Sb)({hlsjsInstance:v,streamUrl:this.url,sdkConfig:{...a,trackerUrls:m},appId:o,sessionId:h,trackerUrl:p,networkType:this.options.networkType,liveWindowBucket:this.options.liveWindowBucket,p2pEnabled:s??a?.p2pEnabled,contentId:this.options.contentId,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,httpDownloadInitialTimeoutMs:this.options.httpDownloadInitialTimeoutMs,uploadSlots:a?.defaults?.uploadSlots,downloadSlots:a?.defaults?.downloadSlots,iceServers:this.options.iceServers,capability:c,logLevel:this.options.logLevel,sessionTokenManager:this.sessionTokenManager}),Object.assign(v.config,y.getHlsConfig()),f(v.config,this.options.originHeaders,this.options.originHeadersProvider),this.lifecycle.isCurrent(e)||(y?.dispose(),this.options.hlsjsInstance||v.destroy(),this.lifecycle.assertCurrent(e))}catch(s){if(y?.dispose(),this.options.hlsjsInstance||v.destroy(),!this.lifecycle.isCurrent(e))throw s;return this.startCdnFallback(c,a,t,e,"P2P_INITIALIZATION_FAILED")}return this.options.hlsjsInstance?this.hls=v:this.attachHls(v,this.url),this.p2p=y,this.stopFallbackStatsNotifications(),this.bindEventListeners(y),this.mode="p2p-hls",this.setPlaybackState("connecting"),{mode:this.mode,capability:c,sdkConfig:a}}statistics(){if(this.p2p)return q(this.p2p.statistics());const e=this.serviceWorkerP2pEngine?.diagnostics();return q({...this.cdnStats,...this.serviceWorkerStats,connectedPeers:e?.connectedPeers??0,trackerErrors:e?.trackerErrors??0,peerConnectErrors:e?.peerConnectErrors??0,p2pAttempts:e?.p2pAttempts??0,httpAttempts:e?.httpAttempts??this.cdnStats.httpAttempts??0,p2pErrors:e?.p2pErrors??0,httpErrors:e?.httpErrors??this.cdnStats.httpErrors??0,p2pUploaded:e?.p2pUploaded??0,p2pSegmentUploadSuccesses:e?.p2pSegmentUploadSuccesses??0,p2pSegmentUploadFailures:e?.p2pSegmentUploadFailures??0,lastLoadedBytes:e?.lastLoadedBytes??this.cdnStats.lastLoadedBytes??0})}diagnostics(){return this.p2p?this.p2p.diagnostics():{...this.serviceWorkerClient?.diagnostics(),...this.serviceWorkerP2pEngine?.diagnostics()}}qoe(){const e=this.statistics(),t=this.diagnostics();return function(e,t,s){const i=Math.max(0,t.p2pDownloaded),r=Math.max(0,t.httpDownloaded),n=i+r;return{state:e,downloadedBytes:n,p2pDownloadedBytes:i,cdnDownloadedBytes:r,p2pDownloadRatio:n>0?i/n:0,connectedPeers:Math.max(0,t.connectedPeers),...void 0!==s.firstPeerConnectMs?{firstPeerConnectMs:s.firstPeerConnectMs}:{},fallbackCount:Math.max(0,s.fallbackCount??0),...s.coldStart?{coldStartCdnBytes:Math.max(0,s.coldStart.httpDownloaded)}:{},...void 0!==s.liveLatency?.lastLatencyMs?{liveLatencyMs:Math.max(0,s.liveLatency.lastLatencyMs)}:{},...void 0!==s.liveLatency?.lastTargetLatencyMs?{liveTargetLatencyMs:Math.max(0,s.liveLatency.lastTargetLatencyMs)}:{},...void 0!==s.liveLatency?.lastMaxLatencyMs?{liveMaxLatencyMs:Math.max(0,s.liveLatency.lastMaxLatencyMs),...void 0!==s.liveLatency.lastLatencyMs?{liveLatencyOverMax:s.liveLatency.lastLatencyMs>s.liveLatency.lastMaxLatencyMs}:{}}:{}}}(this.resolveQoePlaybackState(e,t),e,t)}setP2pEnabled(e){this.p2pEnabledOverride=e,this.p2p?.setP2pEnabled(e),this.serviceWorkerP2pEngine?.setP2pEnabled(e),e||this.setPlaybackState("cdn-fallback")}addEventListener(e){this.eventListeners.add(e);try{e.onPlaybackStateChanged?.(this.playbackState)}catch{}return this.p2p?.addEventListener(e),this.serviceWorkerP2pEngine?.addEventListener(e),"unsupported"===this.mode||this.p2p||this.serviceWorkerP2pEngine||this.startFallbackStatsNotifications(),()=>this.removeEventListener(e)}dispose(){this.serviceWorkerTeardownTask||(this.lifecycle.cancel(),this.startPromise=void 0,this.startResult=void 0,this.serviceWorkerP2pEngine&&this.serviceWorkerReportUrl?(this.stopServiceWorkerReporting(),this.serviceWorkerTeardownTask=this.flushServiceWorkerReport().catch(()=>{}).finally(()=>this.teardown())):this.teardown(),this.setPlaybackState("disposed"))}teardown(){this.stopServiceWorkerReporting(),this.stopFallbackStatsNotifications(),this.unbindCdnStats();for(const e of Object.keys(this.cdnStats))delete this.cdnStats[e];this.p2p?.dispose();const e=this.serviceWorkerSession,t=this.serviceWorkerClient;e?e.dispose().catch(()=>{}).finally(()=>t?.dispose()):t?.dispose(),this.serviceWorkerP2pEngine?.dispose(),this.ownsHlsInstance&&this.hls?.destroy(),this.sessionTokenManager?.dispose(),this.p2p=void 0,this.serviceWorkerSession=void 0,this.serviceWorkerClient=void 0,this.serviceWorkerP2pEngine=void 0,this.serviceWorkerStats={},this.serviceWorkerReportUrl=void 0,this.serviceWorkerTrackerUrl=void 0,this.serviceWorkerAppId=void 0,this.serviceWorkerKeyId=void 0,this.serviceWorkerSwarmId=void 0,this.serviceWorkerUploadSlots=0,this.serviceWorkerDownloadSlots=0,this.serviceWorkerHasReportedContext=!1,this.hls=void 0,this.sessionTokenManager=void 0,this.mode="unsupported"}startServiceWorkerReporting(e){const t=e?.applicationId?.trim()||this.key,s=e?.keyId?.trim();if(this.serviceWorkerAppId=t,this.serviceWorkerKeyId=s,this.serviceWorkerSwarmId=this.resolveServiceWorkerSwarmId(e),this.serviceWorkerUploadSlots=this.serviceWorkerP2pEngine?pb(e?.defaults?.uploadSlots,4):0,this.serviceWorkerDownloadSlots=this.serviceWorkerP2pEngine?pb(e?.defaults?.downloadSlots,5):0,this.serviceWorkerReportUrl=k(C(e?.reportUrl,{appId:t,keyId:s}))??k(R(this.serviceWorkerTrackerUrl)),!this.serviceWorkerReportUrl)return;const i=j(e?.defaults?.reportIntervalMs);if("undefined"!=typeof window){window.addEventListener("pagehide",this.serviceWorkerPagehideHandler);const e=()=>{this.reportServiceWorkerStats(),this.serviceWorkerReportTimer=window.setInterval(()=>{this.reportServiceWorkerStats()},i)};this.serviceWorkerReportTimer=window.setTimeout(e,K(i))}}bindEventListeners(e){for(const t of this.eventListeners)e.addEventListener(t)}bindServiceWorkerEventListeners(e){for(const t of this.eventListeners)e.addEventListener(t)}completeFallbackStart(e,t,s){this.setPlaybackState("p2p-hls"===this.mode||"sw-hls-p2p"===this.mode?"connecting":"cdn-fallback");const i=function(e){switch(e){case"CAPABILITY_UNSUPPORTED":return"UNSUPPORTED";case"P2P_DISABLED":return"DISABLED";case"SDK_CONFIG_PENDING":default:return;case"SDK_CONFIG_UNAVAILABLE":return"CONFIG_UNAVAILABLE";case"KEY_P2P_DISABLED":return"KEY_P2P_DISABLED";case"QUOTA_EXHAUSTED":return"QUOTA_EXHAUSTED";case"QUOTA_DISABLED":return"QUOTA_DISABLED";case"TRACKER_UNAVAILABLE":return"TRACKER_ERROR";case"P2P_INITIALIZATION_FAILED":return"INITIALIZATION_FAILED"}}(s);if(i)for(const e of this.eventListeners)try{e.onP2pUnavailable?.(i)}catch{}return this.p2p||this.serviceWorkerP2pEngine||this.startFallbackStatsNotifications(),{mode:this.mode,capability:e,sdkConfig:t,fallbackReason:s}}startFallbackStatsNotifications(){void 0===this.fallbackStatsTimer&&0!==this.eventListeners.size&&(this.fallbackStatsTimer=globalThis.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)try{t.onStatistics?.(e)}catch{}},1e3),this.fallbackStatsTimer.unref?.())}stopFallbackStatsNotifications(){void 0!==this.fallbackStatsTimer&&(globalThis.clearInterval(this.fallbackStatsTimer),this.fallbackStatsTimer=void 0)}removeEventListener(e){this.eventListeners.delete(e)&&(this.p2p?.removeEventListener(e),this.serviceWorkerP2pEngine?.removeEventListener(e),0===this.eventListeners.size&&this.stopFallbackStatsNotifications())}setPlaybackState(e){if(this.playbackState!==e){this.playbackState=e;for(const t of this.eventListeners)try{t.onPlaybackStateChanged?.(e)}catch{}}}resolveQoePlaybackState(e,t){return"connecting"!==this.playbackState?this.playbackState:e.connectedPeers>0?"p2p-ready":void 0===t.firstPeerConnectMs?"connecting":"cdn-fallback"}stopServiceWorkerReporting(){void 0!==this.serviceWorkerReportTimer&&"undefined"!=typeof window&&window.clearInterval(this.serviceWorkerReportTimer),"undefined"!=typeof window&&window.removeEventListener("pagehide",this.serviceWorkerPagehideHandler),this.serviceWorkerReportTimer=void 0}async flushServiceWorkerReport(){await this.serviceWorkerReportTask,await this.reportServiceWorkerStats()}reportServiceWorkerStats(){if(!this.serviceWorkerReportUrl||!this.serviceWorkerP2pEngine?.isPlaybackModeKnown())return Promise.resolve();if(this.serviceWorkerReportTask)return this.serviceWorkerReportTask;this.serviceWorkerReportInFlight=!0;const e=(async()=>{try{const e=this.statistics(),t=this.serviceWorkerP2pEngine?.diagnostics(),s=await z(this.serviceWorkerReportUrl,V({platform:"web",playbackMode:!0===this.serviceWorkerP2pEngine?.isLive()?"live":"vod",runtimeMode:"service-worker",protocol:bb(this.options.mimeType,this.url)??"hls",playerType:Eb(this.options.mimeType,this.url)||this.canPlayNativeHls()?"native":"hlsjs",sdkVersion:Q,appId:this.serviceWorkerAppId,keyId:this.serviceWorkerKeyId,sessionId:this.sessionId,contentId:M(this.options.contentId,this.url),swarmId:this.serviceWorkerSwarmId??this.resolveServiceWorkerSwarmId(void 0),playbackUrl:this.url,stats:e,load:{uploadSlots:this.serviceWorkerUploadSlots,activeUploadPeers:Math.min(e.connectedPeers,this.serviceWorkerUploadSlots),downloadSlots:this.serviceWorkerDownloadSlots,activeDownloadPeers:Math.min(e.connectedPeers,this.serviceWorkerDownloadSlots)},diagnostics:{fallbackCount:t?.fallbackCount??(e.httpDownloaded>0&&0===e.p2pDownloaded?1:0),firstPeerConnectMs:t?.firstPeerConnectMs,ice:t?.ice,auth:this.sessionTokenManager?.diagnostics(),...t?.trackerErrors?{lastTrackerError:`tracker-errors:${t.trackerErrors}`}:{},...t?.lastPeerError?{lastPeerError:t.lastPeerError}:t?.peerConnectErrors?{lastPeerError:`peer-connect-errors:${t.peerConnectErrors}`}:{},...t?.lastErrorAtMs?{lastErrorAtMs:t.lastErrorAtMs}:{}}},!this.serviceWorkerHasReportedContext),{authorizationHeader:await(this.sessionTokenManager?.getAuthorizationHeader())});s?.ok&&(this.serviceWorkerHasReportedContext=!0)}catch{}})();return this.serviceWorkerReportTask=e,e.finally(()=>{this.serviceWorkerReportTask===e&&(this.serviceWorkerReportTask=void 0,this.serviceWorkerReportInFlight=!1)}),e}async startDirectFilePlayback(e,t,s,i,r,n,a,o,l){if("cdn"===a||"mse"===a||!1===o)return this.startDirectFileCdnFallback(e,t,l,"P2P_DISABLED");if(!e.supported){this.lifecycle.assertCurrent(l);const s={appId:r,keyId:n,streamUrl:this.url,contentId:this.options.contentId,protocol:bb(this.options.mimeType,this.url)??"mp4",playerType:"native",sdkConfig:t,sessionId:this.sessionId,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,capability:e};return i.reportFallback?await i.reportFallback({...s,sessionToken:await(this.sessionTokenManager?.getSessionToken())}):xE({...s,sessionTokenProvider:()=>this.sessionTokenManager?.getSessionToken()}),this.lifecycle.assertCurrent(l),this.startDirectFileCdnFallback(e,t,l,"CAPABILITY_UNSUPPORTED")}const h=this.options.serviceWorker;if(!(i.isServiceWorkerSupported??zE)())return this.startDirectFileCdnFallback(e,t,l,"CAPABILITY_UNSUPPORTED");let d,c,u,f;try{!1!==h?.autoRegister&&(d=await(i.registerServiceWorker??QE)({url:h?.url,scope:h?.scope,readyTimeoutMs:h?.readyTimeoutMs}),this.lifecycle.isCurrent(l)||(d.dispose(),this.lifecycle.assertCurrent(l))),h?.segmentProvider||(f=await this.createServiceWorkerP2pEngine(t,l,s),u=f.engine),c=await(i.createServiceWorkerSession??XE)({serviceWorker:d,manifestUrl:this.url,resourceKind:"direct-file",originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,p2pTimeoutMs:h?.p2pTimeoutMs,segmentProvider:h?.segmentProvider??u?.createSegmentProvider(),onSegmentStats:e=>this.recordServiceWorkerSegmentStats(e)}),this.lifecycle.isCurrent(l)||(u?.dispose(),d?.dispose(),c?.dispose().catch(()=>{}),this.lifecycle.assertCurrent(l))}catch(s){if(u?.dispose(),d?.dispose(),!this.lifecycle.isCurrent(l))throw s;return this.startDirectFileCdnFallback(e,t,l,"P2P_INITIALIZATION_FAILED")}return c?(this.serviceWorkerClient=d,this.serviceWorkerSession=c,this.serviceWorkerP2pEngine=u,u&&(this.stopFallbackStatsNotifications(),this.bindServiceWorkerEventListeners(u)),this.startServiceWorkerReporting(t),this.video.src=c.manifestUrl,await this.autoplay(),this.lifecycle.assertCurrent(l),this.mode=u?"sw-direct-p2p":"sw-direct-cdn",this.completeFallbackStart(e,t,f?.fallbackReason)):(u?.dispose(),d?.dispose(),this.startDirectFileCdnFallback(e,t,l,"P2P_INITIALIZATION_FAILED"))}async startDirectFileCdnFallback(e,t,s,i){return this.lifecycle.assertCurrent(s),c(this.options.originHeaders,this.options.originHeadersProvider)?(this.mode="unsupported",this.completeFallbackStart(e,t,i)):(this.video.src=this.url,this.mode="cdn-direct",await this.autoplay(),this.lifecycle.assertCurrent(s),this.completeFallbackStart(e,t,i))}recordServiceWorkerSegmentStats(e){const t=e.status>=200&&e.status<400,s=Math.min(e.bytes,Math.max(0,e.p2pBytes??("p2p"===e.source?e.bytes:0))),i=Math.min(e.bytes-s,Math.max(0,e.cdnBytes??("cdn"===e.source?e.bytes:0)));t?(s>0&&(this.serviceWorkerStats.p2pDownloaded=(this.serviceWorkerStats.p2pDownloaded??0)+s,this.serviceWorkerStats.p2pSegmentDownloadSuccesses=(this.serviceWorkerStats.p2pSegmentDownloadSuccesses??0)+1),i>0&&(this.serviceWorkerStats.httpDownloaded=(this.serviceWorkerStats.httpDownloaded??0)+i,this.serviceWorkerStats.httpSegmentDownloadSuccesses=(this.serviceWorkerStats.httpSegmentDownloadSuccesses??0)+1)):"p2p"===e.source?this.serviceWorkerStats.p2pSegmentDownloadFailures=(this.serviceWorkerStats.p2pSegmentDownloadFailures??0)+1:this.serviceWorkerStats.httpSegmentDownloadFailures=(this.serviceWorkerStats.httpSegmentDownloadFailures??0)+1;try{this.options.serviceWorker?.onSegmentStats?.(e)}catch{}}async startServiceWorkerFallback(e,t,s,i,r){const n=this.options.serviceWorker,a=i.isServiceWorkerSupported??zE;if(!n&&!1===e.serviceWorkerSupported)return{fallbackReason:"CAPABILITY_UNSUPPORTED"};if(!a())return{fallbackReason:"CAPABILITY_UNSUPPORTED"};const o=i.hlsIsSupported??yb,l=await o();if(this.lifecycle.assertCurrent(r),!l&&!this.canPlayNativeHls()&&!this.options.loadExternalHls)return{fallbackReason:"CAPABILITY_UNSUPPORTED"};let h,d,c,u;try{n?.autoRegister&&(h=await(i.registerServiceWorker??QE)({url:n.url,scope:n.scope,readyTimeoutMs:n.readyTimeoutMs}),this.lifecycle.isCurrent(r)||(h.dispose(),this.lifecycle.assertCurrent(r))),n?.segmentProvider||(u=await this.createServiceWorkerP2pEngine(t,r,s),c=u.engine),d=await(i.createServiceWorkerSession??XE)({serviceWorker:h,manifestUrl:this.url,resourceKind:"hls",originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,p2pTimeoutMs:n?.p2pTimeoutMs,segmentProvider:n?.segmentProvider??c?.createSegmentProvider(),onSegmentStats:e=>this.recordServiceWorkerSegmentStats(e)}),this.lifecycle.isCurrent(r)||(c?.dispose(),h?.dispose(),d?.dispose().catch(()=>{}),this.lifecycle.assertCurrent(r))}catch(e){if(c?.dispose(),h?.dispose(),!this.lifecycle.isCurrent(r))throw e;return{fallbackReason:"P2P_INITIALIZATION_FAILED"}}if(!d)return c?.dispose(),h?.dispose(),{fallbackReason:"P2P_INITIALIZATION_FAILED"};if(this.serviceWorkerClient=h,this.serviceWorkerSession=d,this.serviceWorkerP2pEngine=c,c&&(this.stopFallbackStatsNotifications(),this.bindServiceWorkerEventListeners(c)),this.startServiceWorkerReporting(t),this.options.loadExternalHls)await this.options.loadExternalHls(d.manifestUrl),this.lifecycle.assertCurrent(r),await this.autoplay(),this.lifecycle.assertCurrent(r);else if(l){const e=await(i.createHls??vb)(this.options.hlsConfig);this.lifecycle.isCurrent(r)||(e.destroy(),this.lifecycle.assertCurrent(r)),this.options.onHlsCreated?.(e),this.attachHls(e,d.manifestUrl)}else this.video.src=d.manifestUrl,await this.autoplay(),this.lifecycle.assertCurrent(r);return this.mode=c?"sw-hls-p2p":"sw-hls-cdn",{playback:this.completeFallbackStart(e,t,u?.fallbackReason)}}async createServiceWorkerP2pEngine(e,t,s=!1){if(!1===this.effectiveP2pEnabled())return{fallbackReason:"P2P_DISABLED"};if(!ME(e))return{fallbackReason:gb(e,s)};const i=e?.applicationId?.trim()||this.key,r=e?.keyId?.trim()||void 0,n=this.resolveServiceWorkerSwarmId(e),a=I(void 0,e?.trackerUrls,i,n,r,e?.primaryTrackerUrl),o=(await Promise.all(a.map(e=>this.sessionTokenManager?this.sessionTokenManager.getTrackerUrl(e):Promise.resolve(e)))).filter(e=>Boolean(e?.trim()));this.lifecycle.assertCurrent(t);const l=o[0];if(!l)return{fallbackReason:"TRACKER_UNAVAILABLE"};let h;this.serviceWorkerTrackerUrl=l;try{return h=await sb.create({manifestUrl:this.url,resourceKind:Eb(this.options.mimeType,this.url)?"direct-file":"hls",swarmId:n,trackerUrl:l,trackerUrls:o,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,iceServers:this.options.iceServers,sdkConfig:e,requestTimeoutMs:this.options.serviceWorker?.p2pTimeoutMs}),this.lifecycle.isCurrent(t)||(h.dispose(),this.lifecycle.assertCurrent(t)),await h.initialize(),this.lifecycle.isCurrent(t)||(h.dispose(),this.lifecycle.assertCurrent(t)),{engine:h}}catch(e){if(h?.dispose(),!this.lifecycle.isCurrent(t))throw e;return{fallbackReason:"P2P_INITIALIZATION_FAILED"}}}resolveServiceWorkerSwarmId(e){const t=e?.defaults?.swarmBucketCount,s=e?.defaults?.swarmBucketId;return this.options.contentId?.trim()?x(D(this.options.contentId),t??1,s??0):F(this.url,this.sessionId,t,s)}async startCdnFallback(e,t,s,i,r){if(this.lifecycle.assertCurrent(i),this.options.loadExternalHls)return c(this.options.originHeaders,this.options.originHeadersProvider)?(this.mode="unsupported",this.completeFallbackStart(e,t,r)):(await this.options.loadExternalHls(this.url),this.mode="cdn-hls",await this.autoplay(),this.lifecycle.assertCurrent(i),this.completeFallbackStart(e,t,r));if(this.options.hlsjsInstance)return this.hls=this.options.hlsjsInstance,this.bindCdnStats(this.hls),this.mode="cdn-hls",this.completeFallbackStart(e,t,r);if(!c(this.options.originHeaders,this.options.originHeadersProvider)&&"native-hls-cdn"===e.recommendedMode)return this.video.src=this.url,this.mode="native-hls-cdn",await this.autoplay(),this.lifecycle.assertCurrent(i),this.completeFallbackStart(e,t,r);const n=s.hlsIsSupported??yb;if(await n()){this.lifecycle.assertCurrent(i);const n=await(s.createHls??vb)(this.options.hlsConfig);return this.lifecycle.isCurrent(i)||(n.destroy(),this.lifecycle.assertCurrent(i)),this.options.onHlsCreated?.(n),this.bindCdnStats(n),f(n.config,this.options.originHeaders,this.options.originHeadersProvider),this.attachHls(n,this.url),this.mode="cdn-hls",this.completeFallbackStart(e,t,r)}return this.mode="unsupported",this.completeFallbackStart(e,t,r)}bindCdnStats(e){this.unbindCdnStats(),this.cdnStatsHls=e,e.on("hlsFragLoading",this.cdnFragLoadingHandler),e.on("hlsFragLoaded",this.cdnFragLoadedHandler),e.on("hlsFragLoadError",this.cdnFragLoadErrorHandler)}unbindCdnStats(){this.cdnStatsHls&&(this.cdnStatsHls.off?.("hlsFragLoading",this.cdnFragLoadingHandler),this.cdnStatsHls.off?.("hlsFragLoaded",this.cdnFragLoadedHandler),this.cdnStatsHls.off?.("hlsFragLoadError",this.cdnFragLoadErrorHandler),this.cdnStatsHls=void 0)}attachHls(e,t){this.hls=e,e.on("hlsManifestParsed",()=>{this.autoplay()}),e.loadSource(t),e.attachMedia(this.video)}async autoplay(){!1!==this.options.autoplay&&await this.video.play().catch(()=>{})}canPlayNativeHls(){return""!==this.video.canPlayType("application/vnd.apple.mpegurl")}effectiveP2pEnabled(){return this.p2pEnabledOverride??this.options.p2pEnabled}};function pb(e,t){return void 0!==e&&Number.isFinite(e)?Math.max(0,Math.floor(e)):t}async function vb(e){return new((await Promise.resolve().then(()=>(tf(),Go))).default)(e)}async function yb(){return(await Promise.resolve().then(()=>(tf(),Go))).default.isSupported()}async function Sb(e){return new((await Promise.resolve().then(()=>(SE(),cE))).HlsP2pClient)(e)}function Eb(e,t){return void 0!==bb(e,t)}function bb(e,t){if("mp4"===e||"mp3"===e)return e;try{const e=new URL(t).pathname.toLowerCase();if(e.endsWith(".mp4"))return"mp4";if(e.endsWith(".mp3"))return"mp3"}catch{const e=t.trim().toLowerCase().split("?")[0]??"";if(e.endsWith(".mp4"))return"mp4";if(e.endsWith(".mp3"))return"mp3"}}export{mb as MeshStreamHlsPlayer};
|
|
1
|
+
var e,t=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,s)=>function(){if(s)throw s[0];try{return e&&(t=(0,e[r(e)[0]])(e=0)),t}catch(e){throw s=[e],e}},l=(e,t)=>function(){try{return t||(0,e[r(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},h=(e,t)=>{for(var i in t)s(e,i,{get:t[i],enumerable:!0})},d=(e,o,l)=>(l=null!=e?t(n(e)):{},((e,t,n,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of r(t))a.call(e,n)||void 0===n||s(e,n,{get:()=>t[n],enumerable:!(o=i(t,n))||o.enumerable});return e})(!o&&e&&e.__esModule?l:s(l,"default",{value:e,enumerable:!0}),e));function c(e,t){return v(e).length>0||"function"==typeof t}function u(e,t,s){if(c(e,t))return async(i,r,n,a)=>{if(!function(e,t){if(!e||!t)return!0;try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}(i,s))return;const o=new Headers,l=a??r;l&&o.set("Range",`bytes=${l.start}-${l.end??""}`);for(const[s,r]of p(e,t,i))try{o.set(s,r)}catch{}return new Request(i,{method:"GET",headers:o,signal:n})}}function f(e,t,s){if(!c(t,s))return;const i=e.xhrSetup;e.xhrSetup=(e,r)=>{i?.(e,r);for(const[i,n]of p(t,s,r))try{e.setRequestHeader(i,n)}catch{}}}function g(e,t,s,i=m(s)){const r={};for(const[t,s]of v(e))r[t]=s;try{for(const[e,n]of v(t?.({url:s,kind:i})))r[e]=n}catch{}return r}function m(e){const t=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.split("?",1)[0]?.toLowerCase()??""}})();return/\.(m3u8|mpd)$/.test(t)?"manifest":/\.(key|lic)$/.test(t)?"key":/\.(mp4|mp3)$/.test(t)?"direct-file":/\.(ts|m4s|m4a|aac|mp4a|cmfv|cmfa|webm)$/.test(t)?"segment":"unknown"}function p(e,t,s,i=m(s)){return v(g(e,t,s,i))}function v(t){return Object.entries(t??{}).filter(([t,s])=>{const i=t.trim().toLowerCase();return i&&s.trim()&&!e.has(i)&&!i.startsWith("proxy-")})}var y,S,E=o({"src/origin-headers.ts"(){e=new Set(["connection","content-length","host","proxy-connection","range","transfer-encoding","upgrade"])}});function b(e,t,s={}){const i=t??{mode:"none"},r=i.mode?.trim()||"none";if("signed-url"!==r)return{mode:r,status:"none"};let n;try{n=new URL(e)}catch{return{mode:r,status:"invalid-url"}}const a=T(n,i.signatureQueryKeys??y);if(!a)return{mode:r,status:"missing-signature"};const o=T(n,i.expiresQueryKeys??S),l=o?Number(n.searchParams.get(o)):void 0,h=Number.isFinite(l)?l:void 0;if(o&&void 0!==h){const e=Math.floor((s.nowSeconds??(()=>Date.now()/1e3))());if(h+("number"==typeof(d=i.clockSkewSeconds)&&Number.isFinite(d)?Math.max(0,Math.min(3600,Math.floor(d))):0)<e)return{mode:r,status:"expired-url",signatureKey:a,expiresKey:o,expiresAtSeconds:h}}var d;return{mode:r,status:"valid",signatureKey:a,expiresKey:o,expiresAtSeconds:h}}function T(e,t){return t.map(e=>e.trim()).find(t=>t&&e.searchParams.has(t))}var w=o({"src/playback-auth.ts"(){y=["token","signature","sign","auth_key"],S=["expires","expire","exp","e"]}});function I(e,t,s,i,r,n,a){const o=[...new Set((t?.length?t:e?[e]:[]).map(e=>e?.trim()).filter(e=>Boolean(e)))];if(!o.length)return[];const l=n?.trim(),h=l&&o.includes(l)?l:o.reduce((e,t)=>U(s??"",i,t)>U(s??"",i,e)?t:e);return[h,...o.filter(e=>e!==h)].map(e=>L(C(e,{appId:s,keyId:r,...a}),"tracker")).filter(e=>Boolean(e?.trim()))}function L(e,t){if(!e)return;if("undefined"==typeof window)return e;const{protocol:s,hostname:i}=window.location;if(!["localhost","127.0.0.1","::1"].includes(i))return e;try{const r=new URL(e);if(!A(r.hostname))return e;if("https:"===s){const e=new URL(window.location.origin);return e.pathname="tracker"===t?r.pathname&&"/"!==r.pathname?r.pathname:"/tracker":"/events/v1/events/reports",e.search=r.search,e.hash="",e.toString()}return r.hostname=i,r.toString()}catch{return e}}function A(e){const t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(!t||"localhost"===t||"::1"===t||t.endsWith(".local"))return!0;if(/^\d{1,3}(?:\.\d{1,3}){3}$/.test(t)){const e=t.split(".").map(Number);return 10===e[0]||127===e[0]||172===e[0]&&e[1]>=16&&e[1]<=31||192===e[0]&&168===e[1]||169===e[0]&&254===e[1]}return!t.includes(".")}function k(e){return L(e,"report")}function R(e){if(e)try{const t=new URL(e);return t.protocol="wss:"===t.protocol?"https:":"http:",t.pathname="/reports",t.search="",t.hash="",t.toString()}catch{return}}function C(e,t){if(!e)return;const s=[["app_id",t.appId],["key_id",t.keyId],["platform","web"],["live_window_bucket",t.liveWindowBucket]].filter(([,e])=>e?.trim());if(!s.length)return e;try{const t=new URL(e);for(const[e,i]of s)t.searchParams.set(e,i.trim());return t.toString()}catch{return e}}function P(e){return`url-v1-${N(function(e){const t=e.trim();try{const e=new URL(t);e.hash="";const s=e.protocol.toLowerCase(),i=e.hostname.toLowerCase(),r="http:"===s&&"80"===e.port||"https:"===s&&"443"===e.port?"":e.port?`:${e.port}`:"",n=[...e.searchParams.entries()].filter(([e])=>!function(e){const t=e.toLowerCase();return["token","sign","signature","expires","expire","exp","e","auth","auth_key","authkey","key","policy","x-amz-signature","x-amz-expires","x-amz-date","x-amz-credential","x-amz-algorithm","x-amz-security-token","x-oss-signature","x-oss-expires","x-oss-date","x-oss-credential","x-oss-security-token","x-goog-signature","x-goog-expires","x-goog-date","x-goog-credential","x-goog-algorithm"].includes(t)||t.startsWith("x-amz-")||t.startsWith("x-oss-")||t.startsWith("x-goog-")}(e)).sort(([e,t],[s,i])=>e===s?t.localeCompare(i):e.localeCompare(s)),a=n.length?`?${new URLSearchParams(n).toString()}`:"";return`${s}//${i}${r}${e.pathname}${a}`}catch{return t.split("#",1)[0]?.trim()??t}}(e))}`}function D(e){return`content-v1-${N(e.trim())}`}function M(e,t){return e?.trim()?D(e):P(t)}function _(e){const t=e.trim();try{const e=new URL(t);return e.search="",e.hash="",e.toString()}catch{return t.split(/[?#]/,1)[0]?.trim()??t}}function O(e,t){const s=B(t);return Number($(e)%BigInt(s))}function x(e,t,s){const i=B(t);return`${e}-b${(Math.floor(Number.isFinite(s)?s:0)%i+i)%i}`}function F(e,t,s=1,i){const r=B(s);return x(P(e),r,i??O(t,r))}function B(e){return Number.isFinite(e)?Math.max(1,Math.min(4096,Math.floor(e))):1}function U(e,t,s){let i=0xcbf29ce484222325n;for(const r of(new TextEncoder).encode(`${e}\0${t}\0${s}`))i^=BigInt(r),i=BigInt.asUintN(64,0x100000001b3n*i);return i}function N(e){return $(e).toString(36)}function $(e){let t=0xcbf29ce484222325n;for(const s of(new TextEncoder).encode(e))t^=BigInt(s),t=1099511628211n*t&18446744073709551615n;return t}var G,H,W=o({"src/url.ts"(){}});function q(e){return{httpDownloaded:e?.httpDownloaded??0,p2pDownloaded:e?.p2pDownloaded??0,p2pUploaded:e?.p2pUploaded??0,httpSegmentDownloadSuccesses:e?.httpSegmentDownloadSuccesses??0,httpSegmentDownloadFailures:e?.httpSegmentDownloadFailures??0,p2pSegmentDownloadSuccesses:e?.p2pSegmentDownloadSuccesses??0,p2pSegmentDownloadFailures:e?.p2pSegmentDownloadFailures??0,p2pSegmentUploadSuccesses:e?.p2pSegmentUploadSuccesses??0,p2pSegmentUploadFailures:e?.p2pSegmentUploadFailures??0,connectedPeers:e?.connectedPeers??0,peerConnectErrors:e?.peerConnectErrors??0,trackerErrors:e?.trackerErrors??0,p2pAttempts:e?.p2pAttempts??0,httpAttempts:e?.httpAttempts??0,p2pErrors:e?.p2pErrors??0,httpErrors:e?.httpErrors??0,lastLoadedBytes:e?.lastLoadedBytes??0}}function j(e){return Number.isFinite(e)?Math.max(H,Math.min(3e5,Math.floor(e))):G}function K(e){return j(e)+Math.floor(10001*Math.random())}function V(e,t=!0){const s={firstPeerConnectMs:e.diagnostics.firstPeerConnectMs,...e.diagnostics.coldStart?{coldStart:{...e.diagnostics.coldStart}}:{},...e.diagnostics.liveLatency?{liveLatency:{...e.diagnostics.liveLatency}}:{},...e.diagnostics.liveSeed?{liveSeed:{...e.diagnostics.liveSeed}}:{},fallbackCount:e.diagnostics.fallbackCount,lastTrackerError:e.diagnostics.lastTrackerError,lastPeerError:e.diagnostics.lastPeerError,lastErrorAtMs:e.diagnostics.lastErrorAtMs,...t&&e.diagnostics.playbackAuth?{playbackAuth:e.diagnostics.playbackAuth}:{},...e.diagnostics.ice?{ice:{...e.diagnostics.ice}}:{},...e.diagnostics.auth?{auth:{...e.diagnostics.auth}}:{},...e.diagnostics.websocket?{websocket:{...e.diagnostics.websocket}}:{}},i=JSON.stringify({playbackMode:e.playbackMode,stats:e.stats,load:t?e.load:{activeUploadPeers:e.load.activeUploadPeers,activeDownloadPeers:e.load.activeDownloadPeers},diagnostics:s});return{reportType:"stats",reportId:`${e.sessionId}-${Y(i)}`,reportSeq:e.stats.httpDownloaded+e.stats.p2pDownloaded+e.stats.p2pUploaded,reportedAtMs:Date.now(),platform:e.platform,playbackMode:e.playbackMode,appId:e.appId?.trim()||void 0,keyId:e.keyId?.trim()||void 0,sessionId:e.sessionId,stats:e.stats,load:t?e.load:{activeUploadPeers:e.load.activeUploadPeers,activeDownloadPeers:e.load.activeDownloadPeers},diagnostics:s,...t?{protocol:e.protocol,playerType:e.playerType,runtimeMode:e.runtimeMode,sdkVersion:e.sdkVersion,contentId:e.contentId?.trim()||void 0,swarmId:e.swarmId,playbackUrl:_(e.playbackUrl),capability:e.capability}:{}}}function Y(e){let t=14695981039346656037n;for(let s=0;s<e.length;s+=1)t^=BigInt(e.charCodeAt(s)),t=BigInt.asUintN(64,1099511628211n*t);return t.toString(36)}async function z(e,t,s={}){const i=e?.trim();if(!i)return;const r={"Content-Type":"application/json"};return s.authorizationHeader?.trim()&&(r.Authorization=s.authorizationHeader.trim()),(s.fetcher??fetch)(i,{method:"POST",headers:r,keepalive:!0,body:JSON.stringify(t)})}var Q,X,J=o({"src/report.ts"(){W(),G=3e4,H=2e4}}),Z=o({"src/version.ts"(){Q="1.0.5"}});function ee(){return[{urls:[...X]}]}var te,se,ie,re=o({"src/ice.ts"(){X=Object.freeze(["stun:stun.cloudflare.com:3478","stun:stun.l.google.com:19302"])}});function ne(e){return new ie}function ae(e,t){return`${e}:${t}`}function oe(e){return Number.isFinite(e)?Math.max(0,Math.min(120,e)):se}var le,he,de,ce,ue,fe,ge,me,pe,ve,ye,Se,Ee,be,Te,we,Ie,Le,Ae,ke,Re,Ce,Pe,De,Me,_e,Oe,xe,Fe,Be,Ue,Ne,$e,Ge,He,We,qe,je,Ke,Ve,Ye,ze,Qe,Xe,Je,Ze,et,tt,st,it,rt,nt,at,ot,lt,ht,dt,ct,ut,ft,gt,mt,pt,vt,yt,St,Et,bt,Tt,wt,It,Lt,At,kt,Rt,Ct,Pt,Dt,Mt=o({"src/segment-storage.ts"(){te=1048576,se=15,ie=class{limitBytes=100663296;usedBytes=0;mainLiveRetentionSeconds=se;secondaryLiveRetentionSeconds=se;playbackPosition;cache=new Map;segmentChangeCallback;async initialize(e,t,s){const i=e.segmentMemoryStorageLimit,r="number"==typeof i&&Number.isFinite(i)&&i>0?i:96;this.limitBytes=Math.floor(r*te),this.mainLiveRetentionSeconds=oe(t.highDemandTimeWindow),this.secondaryLiveRetentionSeconds=oe(s.highDemandTimeWindow)}onPlaybackUpdated(e,t){Number.isFinite(e)&&(this.playbackPosition=e,this.notifyChanged(this.trimExpiredLiveSegments()))}onSegmentRequested(e,t,s,i,r,n,a){}async storeSegment(e,t,s,i,r,n,a,o){const l=ae(t,s),h=this.cache.get(l);var d;h&&(this.usedBytes-=h.data.byteLength,this.cache.delete(l)),this.cache.set(l,{streamId:t,segmentId:s,data:i,endTime:(d=n,Number.isFinite(d)?d:0),streamType:a,isLive:o}),this.usedBytes+=i.byteLength;const c=this.trimExpiredLiveSegments();for(const e of this.trimToLimit())c.add(e);c.add(t),this.notifyChanged(c),this.publishDebugSnapshot()}async getSegmentData(e,t,s){const i=ae(t,s),r=this.cache.get(i);if(r)return this.cache.delete(i),this.cache.set(i,r),r.data}getUsage(){return{totalCapacity:this.limitBytes/te,usedCapacity:this.usedBytes/te}}hasSegment(e,t,s){return this.cache.has(ae(t,s))}getStoredSegmentIds(e,t){return[...this.cache.values()].filter(e=>e.streamId===t).map(e=>e.segmentId).sort((e,t)=>e-t)}setSegmentChangeCallback(e){this.segmentChangeCallback=e}destroy(){this.cache.clear(),this.usedBytes=0,this.playbackPosition=void 0,this.segmentChangeCallback=void 0,this.publishDebugSnapshot()}trimToLimit(){const e=new Set;for(;this.usedBytes>this.limitBytes&&this.cache.size>1;){const t=this.cache.entries().next();if(t.done)break;const[s,i]=t.value;this.cache.delete(s),this.usedBytes-=i.data.byteLength,e.add(i.streamId)}return e}trimExpiredLiveSegments(){const e=new Set,t=this.playbackPosition;if(void 0===t)return e;for(const[s,i]of this.cache)!i.isLive||t<=i.endTime+this.liveRetentionSeconds(i.streamType)||(this.cache.delete(s),this.usedBytes-=i.data.byteLength,e.add(i.streamId));return e}liveRetentionSeconds(e){return"secondary"===e?this.secondaryLiveRetentionSeconds:this.mainLiveRetentionSeconds}notifyChanged(e){for(const t of e)this.segmentChangeCallback?.(t)}publishDebugSnapshot(){const e=globalThis;if(!e.__MESHSTREAM_DEBUG_SEGMENT_STORAGE__)return;const t={};for(const e of this.cache.values())t[e.streamId]??=[],t[e.streamId].push(e.segmentId);for(const e of Object.values(t))e.sort((e,t)=>e-t);e.__meshStreamSegmentStorageSnapshot={totalCapacityMiB:this.limitBytes/te,usedCapacityMiB:this.usedBytes/te,streams:t}}}}}),_t={};function Ot(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}function xt(e){Promise.resolve().then(e)}function Ft(e,t){t??=e.reduce((e,t)=>e+t.byteLength,0);const s=new Uint8Array(t);let i=0;for(const t of e)s.set(t,i),i+=t.byteLength;return s}function*Bt(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function Ut(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Nt(e){if(function(e){return Array.isArray(e)}(e))return e.map(e=>Nt(e));if(Ut(e)){const t={};for(const s of Object.keys(e))t[s]=Nt(e[s]);return t}return e}function $t(e,t,s={}){return"object"!=typeof e||null===e||"object"!=typeof t||null===t||Object.keys(t).forEach(i=>{const r="symbol"==typeof i?i.toString():String(i);if("__proto__"===i||"constructor"===i||"prototype"===i)throw new Error(`Attempt to modify restricted property '${r}'`);const n=t[i],a=s[i];i in e&&(e[i]=void 0===n?void 0===a?void 0:a:n)}),e}function Gt(e){const{defaultConfig:t,baseConfig:s={},specificStreamConfig:i={}}=e,r=Nt({...t,...s,...i}),n=Object.keys(t),a={};return n.forEach(e=>{e in r&&(a[e]=r[e])}),a}function Ht(e){const t=e.length,s=(e,s)=>{const i=8*(t-1-s);return e*Math.pow(2,i)};let i=s(127&e[0],0);for(let r=1;r<t;r++)i+=s(e[r],r);return(128&e[0])>>7&&(i=-i),i}function Wt(e){const t=function(e){const t=e<0,s=function(e){if(0===e)return 1;const t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}(e),i=new Uint8Array(s);e=Math.abs(e);for(let t=0;t<s;t++){const r=8*(s-1-t);i[t]=255&Math.floor(e/Math.pow(2,r))}return t&&(i[0]=128|i[0]),i}(e),s=0|t.length;return new Uint8Array([s,...t])}function qt(e){if(0===e.length)throw new Error("Buffer is too short");const t=e[0];if(t>>4)throw new Error("Trying to deserialize integer with invalid serialized item code");const s=15&t;if(0===s)throw new Error("Invalid integer: zero byte length");if(s>7)throw new Error("Invalid integer: byte length exceeds safe integer limit");const i=1+s;if(e.length<i)throw new Error("Buffer is too short");return{number:Ht(e.subarray(1,i)),byteLength:s+1}}function jt(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!=1)throw new Error("Trying to deserialize similar int array with invalid serialized item code");let i=2;const r=[];for(let t=0;t<s;t++){const{number:t,byteLength:s}=qt(e.subarray(i));i+=s;const n=255&t,a=0===n?256:n,o=t-n;if(i+a>e.length)throw new Error("Malformed similar int array: buffer too short");for(let t=0;t<a;t++){const t=e[i];r.push(o+t),i++}}return{numbers:r,byteLength:i}}function Kt(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!=2)throw new Error("Trying to deserialize bytes (sting) with invalid serialized item code.");const i=(15&t)<<8|s;if(e.length<i+2)throw new Error("Malformed string: buffer too short");const r=e.subarray(2,i+2);return{string:Be.decode(r),byteLength:i+2}}function Vt(e){if(e.length<Ve)return!1;const{length:t}=Ge,s=e.subarray(-t);return je.some(t=>Jt(e,t,$e))&&Ke.some(e=>Jt(s,e,$e))}function Yt(e){const[t]=e,s={c:t};let i=1;for(;i<e.length;){if(i+1>=e.length)throw new Error("Malformed command buffer: truncated name/type header");const t=String.fromCharCode(e[i]);switch(i++,zt(e[i])){case Ue.Int:{const{number:r,byteLength:n}=qt(e.subarray(i));s[t]=r,i+=n}break;case Ue.SimilarIntArray:{const{numbers:r,byteLength:n}=jt(e.subarray(i));s[t]=r,i+=n}break;case Ue.String:{const{string:r,byteLength:n}=Kt(e.subarray(i));s[t]=r,i+=n}}}return function(e){switch(e.c){case xe.SegmentsAnnouncement:return e;case xe.SegmentRequest:return Zt(e,"i","r"),e;case xe.SegmentData:return Zt(e,"i","r","s"),e;case xe.SegmentAbsent:case xe.CancelSegmentRequest:case xe.SegmentDataSendingCompleted:return Zt(e,"i","r"),e;default:throw new Error(`Unknown peer command type: ${String(e.c)}`)}}(s)}function zt(e){const t=e>>4;if(t<=Ue.Min||t>=Ue.Max)throw new Error("Not existing type");return t}function Qt(e,t){if(t&&e.length!==t)throw new Error("Wrong string length");const s=new Uint8Array(t??e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Xt(e,t,s){const i=new Uint8Array(e.length+t.length+s.length);return i.set(t),i.set(e,t.length),i.set(s,t.length+e.length),i}function Jt(e,t,s){for(let i=0;i<s;i++)if(e[i]!==t[i])return!1;return!0}function Zt(e,...t){for(const s of t)if("number"!=typeof e[s])throw new Error(`Expected number field "${s}", got ${typeof e[s]}`)}function es(e,t){switch(e.c){case xe.CancelSegmentRequest:case xe.SegmentAbsent:case xe.SegmentDataSendingCompleted:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t);case xe.SegmentRequest:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),e.b&&s.addInteger("b",e.b),s.complete(),s.getResultBuffers()}(e,t);case xe.SegmentsAnnouncement:return function(e,t){const{c:s,p:i,l:r}=e,n=new Qe(s,t);return r?.length&&n.addUniqueSimilarIntArr("l",r),i?.length&&n.addUniqueSimilarIntArr("p",i),n.complete(),n.getResultBuffers()}(e,t);case xe.SegmentData:return function(e,t){const s=new Qe(e.c,t);return s.addInteger("i",e.i),s.addInteger("s",e.s),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t)}}function ts(e,t="RTC error"){return function(e,t="RTC error"){const s=e;if(s.error instanceof Error)return s.error;const i=s.error?.message??t;return new Error(i)}(e,t).message}function ss(e){return"failed"===e||"closed"===e||"disconnected"===e}function is(e,t){return lt?e.setLocalDescription(t):new Promise((s,i)=>{try{e.setLocalDescription(t,s,i)}catch(e){i(e)}})}function rs(e,t){return lt?e.setRemoteDescription(t):new Promise((s,i)=>{try{e.setRemoteDescription(t,s,i)}catch(e){i(e)}})}function ns(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&ht.has(t.type)&&"string"==typeof t.sdp}function as(e){const t=(s=e,(new TextEncoder).encode(s));var s;const i=[],r=8*t.length;for(let e=0;e<t.length;e++)i[e>>2]|=(255&t[e])<<24-e%4*8;i[r>>5]|=128<<24-r%32,i[15+(r+64>>9<<4)]=r;let n=1732584193,a=4023233417,o=2562383102,l=271733878,h=3285377520;const d=[];for(let e=0;e<i.length;e+=16){const t=n,s=a,r=o,c=l,u=h;for(let t=0;t<80;t++){if(t<16)d[t]=0|i[e+t];else{const e=d[t-3]^d[t-8]^d[t-14]^d[t-16];d[t]=e<<1|e>>>31}let s;s=t<20?1518500249+(a&o|~a&l):t<40?1859775393+(a^o^l):t<60?(a&o|a&l|o&l)-1894007588:(a^o^l)-899497514;const r=(n<<5|n>>>27)+h+(d[t]>>>0)+s|0;h=l,l=o,o=a<<30|a>>>2,a=n,n=r}n=n+t|0,a=a+s|0,o=o+r|0,l=l+c|0,h=h+u|0}let c="";const u=[n,a,o,l,h];for(let e=0;e<20;e++){const t=24-e%4*8,s=u[e>>2];c+=String.fromCharCode(s>>>t&255)}return c}function os({bitrate:e,codecs:t,width:s,height:i,language:r,channels:n,name:a,frameRate:o,videoRange:l}){const h=t?t.split(",").map(e=>{const t=(e=e.trim().toLowerCase()).split(".");if(3===t.length&&("avc1"===t[0]||"avc"===t[0])){const s=parseInt(t[1],10),i=parseInt(t[2],10);if(!isNaN(s)&&!isNaN(i)&&t[1]===s.toString()&&t[2]===i.toString()){const r=`00${s.toString(16)}`.slice(-2),n=`00${i.toString(16)}`.slice(-2);e=`${t[0]}.${r}00${n}`}}return e}).sort().join(","):"",d=r&&"und"!==r?r.slice(0,2).toLowerCase():"",c=n?n.toString().split("/")[0]:"",u=a?a.toLowerCase().trim():"",f=o&&!isNaN(Number(o))?Number(o).toString():"",g=l?l.toUpperCase().trim():"";return btoa(as(`${e??0}-${h}-${s??""}-${i??""}-${d}-${c}-${u}-${f}-${g}`))}function ls(e,t){return`${ut}-${e}-${function(e){return`${e.type}-${e.index}`}(t)}`}function hs(e,t){for(const s of e.values()){const e=s.segments.get(t);if(e)return e}}function ds(e,t,s,i,r){const{highDemandTimeWindow:n,httpDownloadTimeWindow:a,p2pDownloadTimeWindow:o}=function(e,t){const{highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r}=e,n={highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r};return t<=5?(n.httpDownloadTimeWindow=0,n.p2pDownloadTimeWindow=0):t<=10&&(n.p2pDownloadTimeWindow=n.httpDownloadTimeWindow),n}(s,r);return{isHighDemand:cs(e,t,n),isHttpDownloadable:cs(e,t,a),isP2PDownloadable:cs(e,t,o)&&i.isSegmentLoadingOrLoadedBySomeone(e)}}function cs(e,t,s){const{startTime:i,endTime:r}=e,{position:n,rate:a}=t;return!(n+s*a<i||n>r)}function us(e){return btoa(as(e).slice(0,15))}function fs(e){if(1===e.length)return e[0];let t=0;for(const s of e){const e=s.getDownloadBandwidth();e>t&&(t=e)}if(t>0){const s=Math.max(1,.1*t);let i=0,r=0;for(const t of e)t.getDownloadBandwidth()<=s?i++:r+=t.getDownloadBandwidth();let n=s;return i>0&&r>0&&i*s>r&&(n=r/i),function(e){if(0===e.length)throw new Error("Cannot get item from empty array");if(1===e.length)return e[0];let t=0;const s=e.map(e=>{const s=(i=e,Math.max(i.getDownloadBandwidth(),n));var i;return t+=s,s});let i=Math.random()*t;for(let t=0;t<e.length;t++)if(i-=s[t],i<=0)return e[t];return e[e.length-1]}(e)}return(s=e)[Math.floor(Math.random()*s.length)];var s}function gs(e){return`${e.type}-${e.index}`}function ms(e){const{externalId:t}=e;return`(${gs(e.stream)} | ${t})`}function ps(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}function*vs(e,t,s,i,r){const{runtimeId:n,stream:a}=e,o=a.segments.get(n);if(!o)return;const l=a.segments.values();let h;do{const e=l.next();if(e.done)return;h=e.value}while(h!==o);const d=ds(h,t,s,i,r);if(ys(d)){const e=l.next();if(e.done)return;const n=e.value,a=ds(n,t,s,i,r);if(ys(a))return;d.isHighDemand=!0,yield{segment:h,statuses:d},yield{segment:n,statuses:a}}else yield{segment:h,statuses:d};for(const e of l){const n=ds(e,t,s,i,r);if(ys(n))break;yield{segment:e,statuses:n}}}function ys(e){const{isHighDemand:t,isHttpDownloadable:s,isP2PDownloadable:i}=e;return!t&&!s&&!i}h(_t,{Core:()=>Pt,CoreRequestError:()=>Le,PeerConnectError:()=>we,PeerError:()=>Se,PeerWarning:()=>Ee,RequestError:()=>Ie,TrackerError:()=>be,TrackerWarning:()=>Te,TypedError:()=>ye,debug:()=>Dt,generateStreamShortId:()=>os});var Ss,Es,bs,Ts,ws,Is,Ls,As,ks,Rs,Cs,Ps,Ds,Ms,_s,Os,xs,Fs,Bs,Us,Ns,$s,Gs,Hs,Ws,qs,js,Ks,Vs,Ys,zs,Qs,Xs,Js,Zs,ei,ti,si,ii,ri,ni,ai,oi,li,hi,di,ci,ui,fi,gi,mi,pi,vi,yi,Si,Ei,bi,Ti,wi,Ii,Li,Ai,ki,Ri,Ci,Pi,Di,Mi,_i,Oi,xi,Fi,Bi,Ui,Ni,$i,Gi,Hi,Wi,qi,ji,Ki,Vi,Yi,zi,Qi,Xi,Ji,Zi,er,tr,sr,ir,rr,nr,ar,or,lr,hr,dr,cr,ur,fr,gr,mr,pr,vr,yr,Sr,Er,br,Tr,wr,Ir,Lr,Ar,kr,Rr,Cr,Pr,Dr,Mr,_r,Or,xr,Fr,Br,Ur,Nr,$r,Gr,Hr,Wr,qr,jr,Kr,Vr,Yr,zr,Qr,Xr,Jr,Zr,en,tn,sn,rn,nn,an,on,ln,hn,dn,cn,un,fn,gn,mn,pn,vn,yn,Sn,En,bn,Tn,wn,In,Ln,An,kn,Rn,Cn,Pn,Dn,Mn,_n,On,xn,Fn,Bn,Un,Nn,$n,Gn,Hn,Wn,qn,jn,Kn,Vn,Yn,zn,Qn,Xn,Jn,Zn,ea,ta,sa,ia,ra,na,aa,oa,la,ha,da,ca,ua,fa,ga,ma,pa,va,ya,Sa,Ea,ba,Ta,wa,Ia,La,Aa,ka,Ra,Ca,Pa,Da,Ma,_a,Oa,xa,Fa,Ba,Ua,Na,$a,Ga,Ha,Wa,qa,ja,Ka,Va,Ya,za,Qa,Xa,Ja,Za,eo,to,so,io,ro,no,ao,oo,lo,ho,co,uo,fo,go,mo,po,vo,yo,So,Eo,bo,To,wo,Io,Lo,Ao,ko,Ro,Co,Po,Do,Mo,_o,Oo,xo,Fo,Bo,Uo,No,$o=o({"src/vendor/meshstream-p2p-core.js"(){le=Object.create,he=Object.defineProperty,de=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyNames,ue=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty,ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),me=(e,t)=>{let s={};for(var i in e)he(s,i,{get:e[i],enumerable:!0});return t||he(s,Symbol.toStringTag,{value:"Module"}),s},pe=(e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var r,n=ce(t),a=0,o=n.length;a<o;a++)r=n[a],fe.call(e,r)||r===s||he(e,r,{get:(e=>t[e]).bind(null,r),enumerable:!(i=de(t,r))||i.enumerable});return e},ve=(e,t,s)=>(s=null!=e?le(ue(e)):{},pe(!t&&e&&e.__esModule?s:he(s,"default",{value:e,enumerable:!0}),e)),ye=class extends Error{type;cause;constructor(e,t,s){super(t),this.type=e,this.cause=s}},Se=class extends ye{name="PeerError"},Ee=class extends ye{name="PeerWarning"},be=class extends ye{name="TrackerError"},Te=class extends ye{name="TrackerWarning"},we=class extends ye{name="PeerConnectError"},Ie=class extends ye{name="RequestError";timestamp;constructor(e,t,s){super(e,t,s),this.timestamp=performance.now()}},Le=class extends ye{name="CoreRequestError"},Ae=class{aborted=!1;#e=new Set;addEventListener(e,t){this.#e.add(t)}removeEventListener(e,t){this.#e.delete(t)}dispatchEvent(e){this.aborted=!0;for(const e of this.#e)try{e()}catch{}this.#e.clear()}},ke=class{signal=new Ae;abort(){this.signal.dispatchEvent("abort")}},Re="undefined"!=typeof AbortController,Ce=Re?AbortController:ke,Pe=class{request;httpConfig;abortController=new Ce;expectedBytesLength;requestByteRange;onChunkDownloaded;isAborted(){return this.abortController.signal.aborted}constructor(e,t,s){this.request=e,this.httpConfig=t,this.onChunkDownloaded=s.getEventDispatcher("onChunkDownloaded");const{byteRange:i}=this.request.segment;i&&(this.requestByteRange={...i})}execute(){const e={onAbort:()=>this.abortController.abort(),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs};if(this.request.tryCompleteByLoadedBytes({downloadSource:"http"},e,this.httpConfig.validateHTTPSegment,"http-segment-validation-failed"))return;0!==this.request.loadedBytes&&(this.requestByteRange=this.requestByteRange??{start:0},this.requestByteRange.start=this.requestByteRange.start+this.request.loadedBytes),this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes);const t=this.request.start({downloadSource:"http"},e);this.fetch(t)}async fetch(e){const{segment:t}=this.request;let s;if(this.isAborted())return;const i=()=>{try{s?.cancel().catch(()=>{})}catch{}};this.abortController.signal.addEventListener("abort",i);const r=Re?this.abortController.signal:void 0;try{let i=await(this.httpConfig.httpRequestSetup?.(t.url,t.byteRange,r,this.requestByteRange));if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!i){const e=new Headers;this.requestByteRange&&e.set("Range",`bytes=${this.requestByteRange.start}-${this.requestByteRange.end??""}`);const s={headers:e};r&&(s.signal=r),i=new Request(t.url,s)}if(this.isAborted())throw new DOMException("Request aborted before request fetch","AbortError");const n=await window.fetch(i);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(this.handleResponseHeaders(n),e.firstBytesReceived(),n.body&&"function"==typeof n.body.getReader){const i=n.body.getReader();for(s=i;;){if(this.isAborted())throw new DOMException("Request aborted","AbortError");const{done:s,value:r}=await i.read();if(s)break;if(this.isAborted())throw new DOMException("Request aborted","AbortError");e.addLoadedChunk(r),this.onChunkDownloaded(r.byteLength,"http",void 0,t.stream.type,this.request.infoHash)}}else{const s=await n.arrayBuffer();if(this.isAborted())throw new DOMException("Request aborted","AbortError");const i=new Uint8Array(s);e.addLoadedChunk(i),this.onChunkDownloaded(i.byteLength,"http",void 0,t.stream.type,this.request.infoHash)}if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(void 0!==this.request.totalBytes&&this.request.loadedBytes!==this.request.totalBytes)throw new Ie("http-bytes-mismatch",`HTTP response truncated: received ${this.request.loadedBytes} of ${this.request.totalBytes} bytes`);const a=await this.request.validateData(this.httpConfig.validateHTTPSegment);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!a)throw this.request.clearLoadedBytes(),new Ie("http-segment-validation-failed");e.completeOnSuccess()}catch(t){this.handleError(t,e)}finally{this.abortController.signal.removeEventListener("abort",i)}}handleResponseHeaders(e){if(!e.ok)throw 406===e.status||416===e.status?(this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText)):new Ie("http-error",e.statusText);const{requestByteRange:t}=this;if(t)if(200===e.status){if(this.request.segment.byteRange)throw new Ie("http-unexpected-status-code");this.request.clearLoadedBytes()}else{if(206!==e.status)throw new Ie("http-unexpected-status-code",e.statusText);const s=e.headers.get("Content-Length");if(s&&void 0!==this.expectedBytesLength&&this.expectedBytesLength!==+s)throw this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText);const i=e.headers.get("Content-Range"),r=i?function(e){const t=De.exec(e.trim());if(!t)return;const[,s,i,r]=t;return{from:s?parseInt(s):void 0,to:i?parseInt(i):void 0,total:r?parseInt(r):void 0}}(i):void 0;if(r){const{from:s,to:i}=r,n=void 0!==i&&void 0!==s?i-s+1:void 0;if(void 0!==n&&this.expectedBytesLength!==n||void 0!==s&&t.start!==s||void 0!==i&&void 0!==t.end&&t.end!==i)throw this.request.clearLoadedBytes(),new Ie("http-bytes-mismatch",e.statusText)}}if(200===e.status&&void 0===this.request.totalBytes){const t=e.headers.get("Content-Length");t&&this.request.setTotalBytes(+t)}}handleError(e,t){if(!this.isAborted()&&e instanceof Error){const s=e instanceof Ie?e:new Ie("http-error",e.message);t.failWithError(s)}}},De=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/,Me=ge((e,t)=>{var s=1e3,i=60*s,r=60*i,n=24*r,a=7*n;function o(e,t,s,i){var r=t>=1.5*s;return Math.round(e/s)+" "+i+(r?"s":"")}t.exports=function(e,t){t=t||{};var l,h,d=typeof e;if("string"===d&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return o*a;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*i;case"seconds":case"second":case"secs":case"sec":case"s":return o*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===d&&isFinite(e))return t.long?(l=e,(h=Math.abs(l))>=n?o(l,h,n,"day"):h>=r?o(l,h,r,"hour"):h>=i?o(l,h,i,"minute"):h>=s?o(l,h,s,"second"):l+" ms"):function(e){var t=Math.abs(e);return t>=n?Math.round(e/n)+"d":t>=r?Math.round(e/r)+"h":t>=i?Math.round(e/i)+"m":t>=s?Math.round(e/s)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),_e=ge((e,t)=>{t.exports=function(e){function t(e){let i,r,n,a=null;function o(...e){if(!o.enabled)return;const s=o,r=Number(new Date);s.diff=r-(i||r),s.prev=i,s.curr=r,i=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let n=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,r)=>{if("%%"===i)return"%";n++;const a=t.formatters[r];if("function"==typeof a){const t=e[n];i=a.call(s,t),e.splice(n,1),n--}return i}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=s,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==t.namespaces&&(r=t.namespaces,n=t.enabled(e)),n),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function s(e,s){const i=t(this.namespace+(void 0===s?":":s)+e);return i.log=this.log,i}function i(e,t){let s=0,i=0,r=-1,n=0;for(;s<e.length;)if(i<t.length&&(t[i]===e[s]||"*"===t[i]))"*"===t[i]?(r=i,n=s,i++):(s++,i++);else{if(-1===r)return!1;i=r+1,n++,s=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(i(e,s))return!1;for(const s of t.names)if(i(e,s))return!0;return!1},t.humanize=Me(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(s=>{t[s]=e[s]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}}),Oe=ve(ge((e,t)=>{e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;e.splice(1,0,s,"color: inherit");let i=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(r=i))}),e.splice(r,0,s)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=_e()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}})(),1),xe=function(e){return e[e.SegmentsAnnouncement=0]="SegmentsAnnouncement",e[e.SegmentRequest=1]="SegmentRequest",e[e.SegmentData=2]="SegmentData",e[e.SegmentDataSendingCompleted=3]="SegmentDataSendingCompleted",e[e.SegmentAbsent=4]="SegmentAbsent",e[e.CancelSegmentRequest=5]="CancelSegmentRequest",e}({}),Fe=new TextEncoder,Be=new TextDecoder("utf8"),Ue=function(e){return e[e.Min=-1]="Min",e[e.Int=0]="Int",e[e.SimilarIntArray=1]="SimilarIntArray",e[e.String=2]="String",e[e.Max=3]="Max",e}({}),Ne=class{#t=[];#s=0;push(e){this.#i(e,"end")}unshift(e){this.#i(e,"start")}#i(e,t){let s;s=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),this.#s+=s.length,this.#t["start"===t?"unshift":"push"](s)}getBytesChunks(){return this.#t}getBuffer(){return Ft(this.#t,this.#s)}get length(){return this.#s}},Ge=Qt("cstr",$e=4),He=Qt("cend",$e),We=Qt("dstr",$e),qe=Qt("dend",$e),je=[Ge,We],Ke=[He,qe],Ve=Ge.length+He.length,Ye=class extends Error{type;constructor(e){super(),this.type=e}},ze=class{#r=new Ne;#n="joining";#a;constructor(e){this.#a=e}addCommandChunk(e){if("completed"===this.#n)return;const t=!((s=e).length<Ve)&&Jt(s,Ge,$e);var s;if(!this.#r.length&&!t)throw new Ye("no-first-chunk");if(this.#r.length&&t)throw new Ye("incomplete-joining");this.#r.push(this.#o(e)),function(e){return!(e.length<Ve)&&Jt(e.subarray(-4),He,$e)}(e)&&(this.#n="completed",this.#a(this.#r.getBuffer()))}#o(e){if(e.length<Ve)throw new Error("Command chunk is too short to unframe");return e.subarray($e,e.length-$e)}},Qe=class{#t=new Ne;#l=[];#n="creating";#h;constructor(e,t){this.#h=t,this.#t.push(e)}addInteger(e,t){this.#t.push(e.charCodeAt(0));const s=Wt(t);this.#t.push(s)}addUniqueSimilarIntArr(e,t){this.#t.push(e.charCodeAt(0));const s=function(e){const t=new Map;for(const s of e){const e=255&s,i=s-e,r=t.get(i)??new Ne;r.length||t.set(i,r),r.push(e)}const s=new Ne;s.push([16,t.size]);for(const[e,i]of t){const{length:t}=i,r=e+(255&t);i.unshift(Wt(r)),s.push(i.getBuffer())}return s.getBuffer()}(t);this.#t.push(s)}addString(e,t){this.#t.push(e.charCodeAt(0));const s=function(e){const t=Fe.encode(e),{length:s}=t;if(s>4095)throw new Error("String exceeds maximum length of 4095 bytes");const i=new Ne;return i.push([32|s>>8&15,255&s]),i.push(t),i.getBuffer()}(t);this.#t.push(s)}complete(){if(!this.#t.length)throw new Error("Buffer is empty");if("completed"===this.#n)return;this.#n="completed";const e=this.#t.getBuffer();if(e.length+Ve<=this.#h)return void this.#l.push(Xt(e,Ge,He));let t=Math.ceil(e.length/this.#h);Math.ceil(e.length/t)+Ve>this.#h&&t++;for(const[s,i]of function*(e,t){const s=Math.ceil(e.length/t);for(let i=0;i<t;i++)yield[i,e.subarray(i*s,(i+1)*s)]}(e,t))0===s?this.#l.push(Xt(i,Ge,qe)):s===t-1?this.#l.push(Xt(i,We,He)):this.#l.push(Xt(i,We,qe))}getResultBuffers(){if("creating"===this.#n||!this.#l.length)throw new Error("Command is not complete.");return this.#l}},Xe=me({BinaryCommandChunksJoiner:()=>ze,BinaryCommandJoiningError:()=>Ye,PeerCommandType:()=>xe,deserializeCommand:()=>Yt,isCommandChunk:()=>Vt,serializePeerCommand:()=>es}),Je=class{channel;maxMessageSize;#d;constructor(e,t){this.channel=e,this.maxMessageSize=t}async sendData(e,t){if(this.#d)throw new Error("Already sending data");if("open"!==this.channel.readyState)throw new Error("Data channel is not open");this.channel.bufferedAmountLowThreshold=8192;const{promise:s,resolve:i,reject:r}=Ot();let n,a=0,o=!1;const l=()=>!o&&(o=!0,void 0!==n&&clearTimeout(n),this.#d=void 0,this.channel.removeEventListener("bufferedamountlow",g),this.channel.removeEventListener("closing",h),this.channel.removeEventListener("close",h),this.channel.removeEventListener("error",d),!0);this.#d={cancel:()=>{l()&&r(new Error("Send cancelled"))}};const h=()=>{l()&&r(new Error("Data channel closed"))},d=e=>{if(!l())return;const t=ts(e,"Unknown error");r(new Error(`Data channel error: ${t}`))},c=ArrayBuffer.isView(e)?e.buffer:e,u=ArrayBuffer.isView(e)?e.byteOffset:0,f=()=>{void 0===n&&(n=setTimeout(()=>{n=void 0,g()},25))},g=()=>{if(!o)if("open"===this.channel.readyState){try{for(;a<e.byteLength;){if(this.channel.bufferedAmount>=16384)return void f();const s=Math.min(this.maxMessageSize,e.byteLength-a),i=new Uint8Array(c,u+a,s);if(this.channel.send(i),a+=s,t?.(s),!this.#d)return}}catch(e){return void(l()&&r(e instanceof Error?e:new Error(String(e))))}l()&&i()}else l()&&r(new Error(`Data channel not open (state: ${this.channel.readyState})`))};return this.channel.addEventListener("bufferedamountlow",g),this.channel.addEventListener("closing",h),this.channel.addEventListener("close",h),this.channel.addEventListener("error",d),g(),s}cancel(){this.#d?.cancel()}},Ze=(0,Oe.default)("p2pml-core:peer-protocol"),et=class{#c;#u;#f;#g;#m;#p;#v;#y;#S;constructor(e,t,s,i,r){if(this.#p=e,this.#v=t,this.#y=s,this.#S=r,this.#u=new Je(e,t.webRtcMaxMessageSize),this.#g=i.getEventDispatcher("onChunkDownloaded"),this.#m=i.getEventDispatcher("onChunkUploaded"),"arraybuffer"!==e.binaryType)throw new Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener("message",this.#E)}#E=e=>{try{const t=new Uint8Array(e.data);Vt(t)?this.#b(t):(this.#y.onSegmentChunkReceived(t),this.#g(t.byteLength,"p2p",this.#S,this.#v.streamType,this.#v.infoHash))}catch(e){Ze("error handling data channel message: %O",e),this.#y.onProtocolError(e)}};sendCommand(e){if("open"!==this.#p.readyState)throw new Error(`cannot send command ${e.c} (channel state: ${this.#p.readyState})`);const t=es(e,this.#v.webRtcMaxMessageSize);for(const e of t)this.#p.send(e)}stopUploadingSegmentData(){this.#u.cancel(),this.#f=void 0}getUploadingRequestId(){return this.#f}async splitSegmentDataToChunksAndUploadAsync(e,t){if(void 0!==this.#f)throw new Error("Some segment data is already uploading.");this.#f=t;try{await this.#u.sendData(e,e=>{this.#m(e,this.#S,this.#v.streamType,this.#v.infoHash)})}finally{this.#f===t&&(this.#f=void 0)}}#b(e){this.#c??=new ze(e=>{let t;this.#c=void 0;try{t=Yt(e)}catch(e){return Ze("error deserializing command: %O",e),void this.#y.onProtocolError(e)}this.#y.onCommandReceived(t)});try{this.#c.addCommandChunk(e)}catch(e){Ze("error receiving command chunks: %O",e),this.#c=void 0,this.#y.onProtocolError(e)}}destroy(){this.#p.removeEventListener("message",this.#E),this.#u.cancel(),this.#c=void 0,this.#f=void 0}},tt=class{clearThresholdMs;loadingsCount=0;bytes=[];loadingOnlyTimestamps=[];timestamps=[];noLoadingsTime=0;loadingsStoppedAt=0;constructor(e=2e4){this.clearThresholdMs=e}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),0===this.loadingsCount&&0!==this.loadingsStoppedAt&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,0===this.loadingsCount&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=Number.NEGATIVE_INFINITY){if(!this.loadingOnlyTimestamps.length)return 0;const s=1e3*e,i=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1];let r=i;const n=i-s;let a=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.loadingOnlyTimestamps[e];if(s<n||this.timestamps[e]<t)break;r=s,a+=this.bytes[e]}return 8e3*a/Math.max(i-r,1)}getBandwidth(e,t=Number.NEGATIVE_INFINITY,s=performance.now()){if(!this.timestamps.length)return 0;const i=s-1e3*e;let r=s,n=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.timestamps[e];if(s<i||s<t)break;r=s,n+=this.bytes[e]}return 8e3*n/Math.max(s-r,1)}clearStale(){if(!this.loadingOnlyTimestamps.length)return;const e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs;let t=0;for(const s of this.loadingOnlyTimestamps){if(s>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}clear(){this.bytes.length=0,this.loadingOnlyTimestamps.length=0,this.timestamps.length=0,this.loadingsCount=0,this.noLoadingsTime=0,this.loadingsStoppedAt=0}},({PeerCommandType:st}=Xe),it=class{id;channel;eventTarget;#T;#w;#I=new Set;#L=new Set;#A=0;#k=new tt;#R={value:0,timestamp:0};#C=(0,Oe.default)("p2pml-core:peer");#P=0;#D;#M=!1;connectedAt=performance.now();#_;#y;#v;get isDestroyed(){return this.#M}constructor(e,t,s,i,r,n){this.id=e,this.channel=t,this.eventTarget=n,this.#_=s,this.#y=i,this.#v=r,this.#T=new et(t,r,{onSegmentChunkReceived:this.#O,onCommandReceived:e=>{this.#x(e).catch(t=>{this.#C("error processing command %O: %O",e,t),this.destroy(!1,new Se("protocol-violation",t instanceof Error?t.message:"Error processing command",t))})},onProtocolError:e=>{this.destroy(!1,new Se("protocol-violation",e instanceof Error?e.message:"Protocol error",e))}},n,e)}get downloadingSegment(){return this.#w?.request.segment}get isUploadingSegment(){return void 0!==this.#T.getUploadingRequestId()}getDownloadBandwidth(){const e=performance.now();return e-this.#R.timestamp>1e3&&(this.#R.value=this.#k.getBandwidthLoadingOnly(15),this.#R.timestamp=e),this.#R.value}getSegmentStatus(e){const{externalId:t}=e;return this.#I.has(t)?"loaded":this.#L.has(t)?"http-loading":void 0}#x=async e=>{switch(e.c){case st.SegmentsAnnouncement:this.#I=new Set(e.l),this.#L=new Set(e.p),this.#y.onSegmentsAnnouncement(this.#I.size,this.#L.size);break;case st.SegmentRequest:this.#D=e.r,this.#T.stopUploadingSegmentData(),this.#y.onSegmentRequested(this,e.i,e.r,e.b);break;case st.SegmentData:{if(!this.#w)break;if(this.#w.isSegmentDataCommandReceived)break;const{request:t,controls:s,requestId:i}=this.#w;if(t.segment.externalId!==e.i||i!==e.r)break;this.#w.isSegmentDataCommandReceived=!0,s.firstBytesReceived(),void 0===t.totalBytes?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&this.#F("bytes-length-mismatch","Peer response bytes length mismatch")}break;case st.SegmentDataSendingCompleted:{const t=this.#w;if(!t?.isSegmentDataCommandReceived)return;const{request:s,controls:i,requestId:r}=t;if(s.segment.externalId!==e.i||r!==e.r)return void this.#F("protocol-violation","Peer protocol violation");if(s.loadedBytes!==s.totalBytes)return void this.#F("bytes-length-mismatch","Peer response bytes length mismatch");const n=await s.validateData(this.#v.validateP2PSegment);if(this.#M)return;if(this.#w!==t)return;if(!n)return void this.#F("validation-failed","P2P segment validation failed");this.#A=0,i.completeOnSuccess(),this.#k.stopLoading(),this.#w=void 0;break}case st.SegmentAbsent:this.#I.delete(e.i),this.#w?.request.segment.externalId===e.i&&this.#w.requestId===e.r&&this.#B("peer-segment-absent");break;case st.CancelSegmentRequest:if(this.#D===e.r&&(this.#D=void 0),this.#T.getUploadingRequestId()!==e.r)break;this.#T.stopUploadingSegmentData()}};#O=e=>{if(!this.#w?.isSegmentDataCommandReceived)return;const{request:t,controls:s}=this.#w;void 0!==t.totalBytes&&t.loadedBytes+e.byteLength>t.totalBytes?this.#F("bytes-length-mismatch","Peer response bytes length mismatch"):(this.#k.addBytes(e.byteLength),this.#R.timestamp=0,s.addLoadedChunk(e))};downloadSegment(e){if(this.#M)return;if(this.#w)throw new Error("Some segment already is downloading");if(e.tryCompleteByLoadedBytes({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:this.#v.p2pNotReceivingBytesTimeoutMs,onAbort:()=>{}},this.#v.validateP2PSegment,"p2p-segment-validation-failed"))return;this.#k.startLoading(),this.#P=(this.#P+1)%1e9,this.#w={request:e,requestId:this.#P,isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:this.#v.p2pNotReceivingBytesTimeoutMs,onAbort:t=>{if(!this.#w||this.#w.request!==e)return;const{request:s,requestId:i}=this.#w;this.#U(s.segment,i),this.#k.stopLoading(),"abort"!==t.type&&(this.#k.clear(),this.#R.timestamp=0,this.#C(`cleared bandwidth history due to ${t.type}`)),this.#w=void 0,"bytes-receiving-timeout"===t.type&&this.#A++,this.#A>=this.#v.p2pErrorRetries?this.destroy(!1,new Se("timeout","Too many timeout errors")):"bytes-receiving-timeout"===t.type&&this.#y.onWarning(new Ee("timeout-strike",`Timeout strike ${this.#A}/${this.#v.p2pErrorRetries}`))}})};const t={c:st.SegmentRequest,r:this.#w.requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),this.#N(t)||this.#B("peer-closed")}async uploadSegmentData(e,t,s){if(this.#M)return;if(t!==this.#D)return void this.#C(`discarding obsolete upload request ${t} for segment ${e.externalId}`);const{externalId:i}=e;this.#C(`send segment ${e.externalId} to ${this.id} (byteLength: ${s.byteLength})`);const r={c:st.SegmentData,i:i,r:t,s:s.byteLength};if(this.#N(r))try{if(await this.#T.splitSegmentDataToChunksAndUploadAsync(s,t),this.isDestroyed||t!==this.#D)return;this.#$(e,t),this.#C(`segment ${i} has been sent to ${this.id}`)}catch(e){this.#C(`cancel segment uploading ${i}: %O`,e)}}#F(e,t){this.#w?.request.clearLoadedBytes();const s=new Se(e,t);this.#B("peer-closed",s),this.destroy(!1,s)}#B(e,t){if(!this.#w)return;const{request:s,controls:i}=this.#w,{segment:r}=s;this.#C(`cancel segment request ${r.externalId} (${e})`);const n=new Ie(e,void 0,t);i.failWithError(n),this.#k.stopLoading(),"peer-segment-absent"!==e&&(this.#k.clear(),this.#R.timestamp=0,this.#C(`cleared bandwidth history due to ${n.type}`)),this.#w=void 0}sendSegmentsAnnouncementCommand(e,t){const s={c:st.SegmentsAnnouncement,p:t,l:e};this.#N(s)}sendSegmentAbsentCommand(e,t){this.#N({c:st.SegmentAbsent,i:e,r:t})}#U(e,t){this.#N({c:st.CancelSegmentRequest,i:e.externalId,r:t})}#$(e,t){this.#N({c:st.SegmentDataSendingCompleted,r:t,i:e.externalId})}destroy(e=!1,t){this.#M||(this.#M=!0,this.#B("peer-closed",t),this.#T.destroy(),e||this.#_(t),this.#C(`peer closed ${this.id}`))}#N(e){if(this.#M)return!1;try{return this.#T.sendCommand(e),!0}catch(t){return this.#C("error sending command %d: %O",e.c,t),!1}}},rt=class{events=new Map;dispatchEvent(e,t,s,i,r,n){const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch{}}getEventDispatcher(e){return(t,s,i,r,n)=>{const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch{}}}addEventListener(e,t){const s=this.events.get(e);s?this.events.set(e,[...s,t]):this.events.set(e,[t])}removeEventListener(e,t){const s=this.events.get(e);if(!s)return;const i=s.indexOf(t);if(-1===i)return;if(1===s.length)return void this.events.delete(e);const r=s.slice();r.splice(i,1),this.events.set(e,r)}clear(){this.events.clear()}},nt="undefined"!=typeof window?window:{},at=nt.RTCPeerConnection??nt.webkitRTCPeerConnection??nt.mozRTCPeerConnection,ot=nt.RTCSessionDescription??nt.webkitRTCSessionDescription??nt.mozRTCSessionDescription,lt=(()=>{if(!nt.RTCPeerConnection&&!nt.webkitRTCPeerConnection&&!nt.mozRTCPeerConnection)return!1;let e;try{e=new at;const t=e.createOffer();if("function"==typeof t?.then)return t.catch(()=>{}),!0}catch{}finally{try{e?.close()}catch{}}return!1})(),ht=new Set(["offer","answer","pranswer","rollback"]),dt=class e{static#G=120;static#H=20;#W;#q;#j=new rt;#K=new Map;#V=new Set;#Y=new Ce;#z=null;#Q=null;#X=0;#J=null;#Z=!1;#ee=void 0;#te=null;#se=!1;#M(){return this.#Y.signal.aborted}#ie(){if(this.#Y.signal.aborted)throw new Error("Client destroyed")}constructor(e){this.#W={infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:e.offerTimeout??(()=>5e4),offersCount:e.offersCount??(()=>5),iceGatheringTimeout:e.iceGatheringTimeout??(()=>5e3),connectionTimeout:e.connectionTimeout??(()=>15e3),claimPeer:e.claimPeer??(()=>!0),shouldGenerateOffers:e.shouldGenerateOffers??(()=>!0)},this.#q=e.wsClient}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}start(){this.#M()||this.#se||(this.#se=!0,this.#q.addEventListener("connected",this.#re),this.#q.addEventListener("disconnected",this.#ne),this.#q.addEventListener("message",this.#ae),"connected"===this.#q.state&&this.#re())}destroy(){this.#M()||(this.#Y.abort(),this.#oe(),this.#le(),this.#he(),this.#de(),this.#se&&(this.#q.removeEventListener("connected",this.#re),this.#q.removeEventListener("disconnected",this.#ne),this.#q.removeEventListener("message",this.#ae)),this.#j.clear())}#re=()=>{this.#ce(e.#G),this.#ue("started").catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("announce-failed",`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})};#ne=()=>{this.#oe(),this.#Q=null};#ae=t=>{if(this.#M())return;let s;try{const e="string"==typeof t?t:(new TextDecoder).decode(t);s=JSON.parse(e)}catch(e){return void this.#j.dispatchEvent("error",new be("parse-error",`Failed to parse tracker message: ${e instanceof Error?e.message:String(e)}`,e))}if("object"!=typeof s||null===s||Array.isArray(s))return;const i=s,r=i.info_hash;if("string"==typeof r&&r!==this.#W.infoHash)return;const n=i["warning message"];"string"==typeof n&&this.#j.dispatchEvent("warning",new Te("tracker-response",n));const a=i["failure reason"];if("string"==typeof a)return void this.#j.dispatchEvent("error",new be("tracker-response",a));const{interval:o}=i;if("number"==typeof o&&o>0){const t=Math.max(e.#H,o);this.#Q!==t&&this.#ce(t)}const l=i["tracker id"];"string"==typeof l&&(this.#te=l),!0===i.request_offers&&this.#fe();const h=i.peer_id;if("string"==typeof h&&h===this.#W.peerId)return;const d=i.offer_id;"string"==typeof h&&"string"==typeof d&&(ns(i.offer)?this.#ge({sdp:i.offer,peerId:h,offerId:d}).catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("signaling-failed",`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):ns(i.answer)&&this.#me({sdp:i.answer,peerId:h,offerId:d}).catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("signaling-failed",`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))};#ce(e){this.#oe(),this.#Q=e;const t=++this.#X,s=async()=>{try{await this.#ue()}catch(e){if(this.#M())return;this.#j.dispatchEvent("error",new be("announce-failed",`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}this.#M()||null===this.#Q||this.#X!==t||(this.#z=setTimeout(s,1e3*this.#Q))};this.#z=setTimeout(s,1e3*e)}#oe(){null!==this.#z&&(clearTimeout(this.#z),this.#z=null)}#fe(){this.#M()||"connected"!==this.#q.state||(this.#J?this.#Z=!0:this.#ue().catch(e=>{this.#M()||this.#j.dispatchEvent("error",new be("announce-failed",`Requested announce failed: ${e instanceof Error?e.message:String(e)}`,e))}))}async#ue(e){if(this.#M()||"connected"!==this.#q.state)return;if(e&&(this.#ee=e),this.#J)return this.#J;const t=(async()=>{const e=this.#W.shouldGenerateOffers()?this.#W.offersCount():0,t=await Promise.all(Array.from({length:e},()=>this.#pe()));if(this.#M()){for(const e of t)e&&this.#ve(e.offer_id);return}const s=[];for(const e of t)e&&s.push(e);const i=this.#ee;this.#ee=void 0;const r=this.#ye({numwant:s.length,offers:s,event:i});if("connected"===this.#q.state)try{this.#q.send(JSON.stringify(r))}catch(e){for(const e of s)this.#ve(e.offer_id);throw e}else for(const e of s)this.#ve(e.offer_id)})();this.#J=t;try{await t}finally{this.#J===t&&(this.#J=null,this.#Z&&(this.#Z=!1,xt(()=>this.#fe())))}}async#pe(){if(this.#M())return;let e;try{e=new at(this.#W.rtcConfig?.()),this.#V.add(e);const t=e.createDataChannel("webtorrent",this.#W.channelConfig),s=await function(e,t){return lt?e.createOffer(t):new Promise((s,i)=>{try{e.createOffer(s,i,t)}catch(e){i(e)}})}(e);this.#ie(),await is(e,s),this.#ie(),await this.#Se(e),this.#ie();const i=e.localDescription;if(!i?.sdp)return void e.close();const r=function(){let e="";for(let t=0;t<20;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e}();return this.#K.set(r,{connection:e,channel:t,timeoutId:setTimeout(()=>{this.#ve(r)},this.#W.offerTimeout())}),{offer:{type:i.type,sdp:i.sdp},offer_id:r}}catch(t){e?.close(),this.#M()||this.#j.dispatchEvent("warning",new Te("offer-failed",`Failed to create offer: ${t instanceof Error?t.message:String(t)}`,t))}finally{e&&this.#V.delete(e)}}#le(){if("connected"!==this.#q.state)return;const e=this.#ye({numwant:0,offers:[],event:"stopped"});try{this.#q.send(JSON.stringify(e))}catch{}}#ye({numwant:e,offers:t,event:s}){const i={action:"announce",info_hash:this.#W.infoHash,peer_id:this.#W.peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return s&&(i.event=s),this.#te&&(i.trackerid=this.#te),i}async#ge({sdp:e,peerId:t,offerId:s}){if(this.#M())return;if(!this.#W.claimPeer(t))return;let i;try{i=new at(this.#W.rtcConfig?.()),this.#V.add(i),await rs(i,new ot(e)),this.#ie();const r=await function(e,t){return lt?e.createAnswer(t):new Promise((s,i)=>{try{e.createAnswer(s,i,t)}catch(e){i(e)}})}(i);this.#ie(),await is(i,r),this.#ie(),await this.#Se(i),this.#ie();const n=i.localDescription;if(!n)throw new Error("Failed to get local description after ICE gathering");const a={action:"announce",info_hash:this.#W.infoHash,peer_id:this.#W.peerId,to_peer_id:t,offer_id:s,answer:{type:n.type,sdp:n.sdp}};this.#q.send(JSON.stringify(a));const o=await this.#Ee(i);this.#ie(),this.#j.dispatchEvent("peerConnected",{peerId:t,connection:i,channel:o})}catch(e){i?.close(),this.#j.dispatchEvent("peerConnectFailed",{peerId:t,error:new we("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{i&&this.#V.delete(i)}}async#me({sdp:e,peerId:t,offerId:s}){if(this.#M())return;const i=this.#K.get(s);if(i)if(this.#K.delete(s),clearTimeout(i.timeoutId),this.#W.claimPeer(t)){this.#V.add(i.connection);try{await rs(i.connection,new ot(e)),this.#ie();const s=await this.#Ee(i.connection,i.channel);this.#ie(),this.#j.dispatchEvent("peerConnected",{peerId:t,connection:i.connection,channel:s})}catch(e){i.connection.close(),this.#j.dispatchEvent("peerConnectFailed",{peerId:t,error:new we("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{this.#V.delete(i.connection)}}else i.connection.close()}#Se(e){return new Promise((t,s)=>{if("complete"===e.iceGatheringState)return void t();if("closed"===e.signalingState)return void s(new Error("RTCPeerConnection closed"));let i;const r=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",n),e.removeEventListener("icecandidate",a),e.removeEventListener("signalingstatechange",o),this.#Y.signal.removeEventListener("abort",l)},n=()=>{"complete"===e.iceGatheringState&&(r(),t())},a=e=>{null===e.candidate&&(r(),t())},o=()=>{"closed"===e.signalingState&&(r(),s(new Error("RTCPeerConnection closed")))},l=()=>{r(),s(new Error("ICE gathering aborted due to teardown"))};this.#Y.signal.aborted?l():(i=setTimeout(()=>{r(),t()},this.#W.iceGatheringTimeout()),e.addEventListener("icegatheringstatechange",n),e.addEventListener("icecandidate",a),e.addEventListener("signalingstatechange",o),this.#Y.signal.addEventListener("abort",l))})}#Ee(e,t){const{promise:s,resolve:i,reject:r}=Ot();let n,a=t;const o=()=>!!ss(e.iceConnectionState)&&(g(),r(new Error(`ICE connection ${e.iceConnectionState}`)),!0),l=()=>{g(),a?i(a):r(new Error("Data channel missing on open"))},h=()=>{g(),r(new Error("Data channel error"))},d=()=>{g(),r(new Error("Data channel closed prematurely"))},c=e=>{a=e,"open"===e.readyState?l():"closed"===e.readyState||"closing"===e.readyState?d():(e.addEventListener("open",l),e.addEventListener("error",h),e.addEventListener("close",d),e.addEventListener("closing",d))},u=e=>{a||c(e.channel)},f=()=>{g(),r(new Error("Connection aborted due to teardown"))},g=()=>{clearTimeout(n),e.removeEventListener("iceconnectionstatechange",o),e.removeEventListener("datachannel",u),a&&(a.removeEventListener("open",l),a.removeEventListener("error",h),a.removeEventListener("close",d),a.removeEventListener("closing",d)),this.#Y.signal.removeEventListener("abort",f)};return this.#Y.signal.aborted?(f(),s):(o()||(n=setTimeout(()=>{g(),r(new Error("Data channel open timeout"))},this.#W.connectionTimeout()),e.addEventListener("iceconnectionstatechange",o),this.#Y.signal.addEventListener("abort",f),a?c(a):e.addEventListener("datachannel",u)),s)}#ve(e,t){const s=t??this.#K.get(e);s&&(clearTimeout(s.timeoutId),s.connection.close(),this.#K.delete(e))}#he(){for(const[e,t]of this.#K)this.#ve(e,t)}#de(){for(const e of this.#V)e.close();this.#V.clear()}},ct=class{#W;#j=new rt;#be=new Set;#Te=new Map;#we=new Set;#Ie=!1;#se=!1;#Le=e=>{if(this.#Ie)return!1;if(this.#be.has(e)||this.#Te.has(e))return!1;const t=Math.floor(this.#W.maxPeers()*Math.max(1,this.#W.maxPeersMultiplier()));return!(this.#be.size+this.#Te.size>=t||(this.#be.add(e),0))};constructor(e){this.#W={...e,maxPeers:e.maxPeers??(()=>50),maxPeersMultiplier:e.maxPeersMultiplier??(()=>1.5)}}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}start(){if(!this.#Ie&&!this.#se){this.#se=!0;try{for(const e of this.#W.trackerUrls){const{client:t,release:s}=this.#W.socketPool.acquire(e);let i=!1;try{const r=new dt({infoHash:this.#W.infoHash,peerId:this.#W.peerId,wsClient:t,rtcConfig:this.#W.rtcConfig,channelConfig:this.#W.channelConfig,claimPeer:this.#Le,offersCount:this.#W.offersCount,offerTimeout:this.#W.offerTimeout,iceGatheringTimeout:this.#W.iceGatheringTimeout,connectionTimeout:this.#W.connectionTimeout,shouldGenerateOffers:()=>this.#be.size+this.#Te.size<this.#W.maxPeers()}),n=t=>{this.#be.delete(t.peerId),this.#Ae(t.peerId,t.connection,t.channel,e)},a=t=>{this.#be.has(t.peerId)&&(this.#be.delete(t.peerId),this.#j.dispatchEvent("peerConnectFailed",{peerId:t.peerId,trackerUrl:e,error:t.error}))},o=t=>{this.#j.dispatchEvent("warning",{trackerUrl:e,warning:t})},l=t=>{this.#j.dispatchEvent("error",{trackerUrl:e,error:t})};r.addEventListener("peerConnected",n),r.addEventListener("peerConnectFailed",a),r.addEventListener("warning",o),r.addEventListener("error",l);const h=()=>{r.removeEventListener("peerConnected",n),r.removeEventListener("peerConnectFailed",a),r.removeEventListener("warning",o),r.removeEventListener("error",l)};this.#we.add({client:r,releaseSocket:s,cleanupListeners:h}),i=!0,r.start()}catch(e){throw i||s(),e}}}catch(e){throw this.destroy(),e}}}destroy(){if(this.#Ie)return;this.#Ie=!0;for(const{client:e,releaseSocket:t,cleanupListeners:s}of this.#we)s(),e.destroy(),t();this.#we.clear(),this.#be.clear();const e=[...this.#Te.entries()];this.#Te.clear();for(const[t,s]of e){s.cleanup();try{s.channel.close()}catch{}try{s.connection.close()}catch{}this.#j.dispatchEvent("peerDisconnected",{peerId:t,trackerUrl:s.trackerUrl,disconnectReason:"Manager destroyed"})}this.#j.clear()}#ke(e,t){if(this.#Ie)return;const s=this.#Te.get(e);if(s){this.#Te.delete(e),s.cleanup();try{s.channel.close()}catch{}try{s.connection.close()}catch{}this.#j.dispatchEvent("peerDisconnected",{peerId:e,trackerUrl:s.trackerUrl,...t})}}#Ae(e,t,s,i){if(ss(t.iceConnectionState)){try{t.close()}catch{}return void this.#j.dispatchEvent("peerConnectFailed",{peerId:e,trackerUrl:i,error:new we("connection-failed","Connection failed during promotion")})}const r=t=>this.#ke(e,t),n=()=>{ss(t.iceConnectionState)&&r({error:new Se("connection-lost",`ICE connection state became ${t.iceConnectionState}`)})},a=()=>r({disconnectReason:"Data channel closed"}),o=()=>r({disconnectReason:"Data channel closing"}),l=e=>{r({error:new Se("transport-error",`Data channel error: ${ts(e,"Data channel error")}`)})};let h=t=>this.#ke(e,t?{error:t}:{disconnectReason:"Closed by consumer"});this.#Te.set(e,{connection:t,channel:s,trackerUrl:i,cleanup:()=>{h=null,t.removeEventListener("iceconnectionstatechange",n),s.removeEventListener("close",a),s.removeEventListener("closing",o),s.removeEventListener("error",l)}}),t.addEventListener("iceconnectionstatechange",n),s.addEventListener("close",a),s.addEventListener("closing",o),s.addEventListener("error",l),this.#j.dispatchEvent("peerConnected",{peerId:e,connection:t,channel:s,trackerUrl:i,close:e=>h?.(e)})}},ut="v2",ft=`-PM${function(){const e="3.0.1".split(".");return`${`00${e[0]}`.slice(-2)}${`00${e[1]}`.slice(-2)}`}()}-`,gt=class{#Re;#Ce=new Map;#Pe;#De;#Me=!1;#_e=(0,Oe.default)("p2pml-core:webtorrent-manager");#Oe=(0,Oe.default)("p2pml-core:churn-cleanup");#xe;#Fe;#Be;#Ue;#Ne;#W;#$e;#j;#Ge;#He;#We;#qe;#je;#Ke;#Ve;#Ye;#ze;#Qe;constructor(e,t,s,i,r,n,a,o,l){this.#Fe=e,this.#Be=t,this.#Ue=s,this.#Ne=i,this.#W=r,this.#$e=n,this.#j=a,this.#Ge=l,this.#We=a.getEventDispatcher("onPeerConnect"),this.#qe=a.getEventDispatcher("onPeerConnectError"),this.#je=a.getEventDispatcher("onPeerClose"),this.#Ke=a.getEventDispatcher("onPeerError"),this.#Ve=a.getEventDispatcher("onPeerWarning"),this.#Ye=a.getEventDispatcher("onTrackerWarning"),this.#ze=a.getEventDispatcher("onTrackerError"),this.#Qe=a.getEventDispatcher("onPeerSegmentsAnnouncement"),this.#Pe=this.#W.swarmId??this.#Fe,this.#De=ls(this.#Pe,this.#Be);const h=us(this.#De);this.#xe=h,this.#Re=new ct({infoHash:h,peerId:o,trackerUrls:this.#W.announceTrackers,rtcConfig:()=>this.#W.rtcConfig,socketPool:this.#$e,maxPeers:()=>this.#W.p2pMaxPeers,maxPeersMultiplier:()=>this.#W.p2pChurnMaxPeersMultiplier,offersCount:()=>this.#W.webRtcOffersCount,offerTimeout:()=>this.#W.webRtcOfferTimeoutMs,iceGatheringTimeout:()=>this.#W.webRtcIceGatheringTimeoutMs,connectionTimeout:()=>this.#W.webRtcConnectionTimeoutMs}),this.#Re.addEventListener("peerConnected",this.#Xe),this.#Re.addEventListener("peerDisconnected",this.#Je),this.#Re.addEventListener("peerConnectFailed",e=>{this.#_e(`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),this.#qe({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type,trackerUrl:e.trackerUrl,error:e.error})}),this.#Re.addEventListener("warning",e=>{this.#_e(`Tracker warning (${e.trackerUrl}):`,e.warning),this.#Ye({trackerUrl:e.trackerUrl,infoHash:this.#xe,streamType:this.#Be.type,warning:e.warning})}),this.#Re.addEventListener("error",e=>{this.#_e(`Tracker error (${e.trackerUrl}):`,e.error),this.#ze({trackerUrl:e.trackerUrl,infoHash:this.#xe,streamType:this.#Be.type,error:e.error})}),this.#j.addEventListener(`onStorageUpdated-${this.#De}`,this.broadcastAnnouncement),this.#Re.start(),this.#He=setTimeout(this.#Ze,Math.max(1e3,this.#W.p2pChurnCleanupIntervalMs))}#Ze=()=>{this.#He=setTimeout(this.#Ze,Math.max(1e3,this.#W.p2pChurnCleanupIntervalMs));const e=this.#Ce.size-this.#W.p2pMaxPeers;if(e<=0)return;const t=[],s=performance.now();for(const e of this.#Ce.values())e.downloadingSegment||e.isUploadingSegment||s-e.connectedAt<this.#W.p2pChurnGracePeriodMs||t.push(e);if(0===t.length)return;t.sort((e,t)=>e.getDownloadBandwidth()-t.getDownloadBandwidth()||e.connectedAt-t.connectedAt);const i=t.slice(0,e);this.#Oe(`Background churn cleanup: dropping ${i.length} excess peers (total: ${this.#Ce.size}, target: ${this.#W.p2pMaxPeers}, eligible: ${t.length})`);for(const e of i)this.#Oe(`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()};downloadSegment(e){const t=[];for(const s of this.#Ce.values())s.downloadingSegment||"loaded"!==s.getSegmentStatus(e)||t.push(s);if(0===t.length)return;const s=fs(t),i=this.#Ue.getOrCreateRequest(e);s.downloadSegment(i)}isSegmentLoadingOrLoadedBySomeone(e){for(const t of this.#Ce.values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(const t of this.#Ce.values())if("loaded"===t.getSegmentStatus(e))return!0;return!1}get connectedPeerCount(){return this.#Ce.size}*peers(){for(const e of this.#Ce.values())yield e}#et(){const e=this.#Ne.getStoredSegmentIds(this.#Pe,this.#De),t=[];for(const e of this.#Ue.httpRequests()){const s=this.#Be.segments.get(e.segment.runtimeId);s&&t.push(s.externalId)}return{loaded:e,httpLoading:t}}#Xe=e=>{if(this.#_e(`peerConnected: peerId=${e.peerId}`),this.#Ce.has(e.peerId))return void e.close();const t=new it(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,s,i)=>{this.#tt(e,t,s,i).catch(s=>{this.#_e(`Error in onSegmentRequested ${t} for peer ${e.id}:`,s)})},onSegmentsAnnouncement:(t,s)=>{this.#Qe(e.peerId,this.#xe,this.#Be.type,t,s),this.#Ge()},onWarning:e=>{this.#Ve({peerId:t.id,infoHash:this.#xe,streamType:this.#Be.type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:this.#W.p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:this.#W.webRtcMaxMessageSize,p2pErrorRetries:this.#W.p2pErrorRetries,validateP2PSegment:this.#W.validateP2PSegment,streamType:this.#Be.type,infoHash:this.#xe},this.#j);if(this.#Ce.set(e.peerId,t),this.#We({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type}),this.#W.isP2PUploadDisabled)return;const{httpLoading:s,loaded:i}=this.#et();t.sendSegmentsAnnouncementCommand(i,s)};#Je=e=>{this.#_e("peerDisconnected: peerId=%s error=%s reason=%s",e.peerId,e.error?.message,e.disconnectReason);const t=this.#Ce.get(e.peerId);t&&(this.#Ce.delete(e.peerId),t.destroy(!0),e.error&&this.#Ke({peerId:e.peerId,infoHash:this.#xe,streamType:this.#Be.type,error:e.error}),this.#je({peerId:t.id,infoHash:this.#xe,streamType:this.#Be.type}))};broadcastAnnouncement=(e=!1)=>{e?this.#st(e):this.#Me||this.#W.isP2PUploadDisabled||this.#st()};#st=(e=!1)=>{this.#Me=!0,xt(()=>{const{loaded:t=[],httpLoading:s=[]}=e?{}:this.#et();for(const e of this.#Ce.values())e.sendSegmentsAnnouncementCommand(t,s);this.#Me=!1})};#tt=async(e,t,s,i)=>{const r=function(e,t){for(const s of e.segments.values())if(s.externalId===t)return s}(this.#Be,t);if(!r)return;if(this.#W.isP2PUploadDisabled)return void e.sendSegmentAbsentCommand(t,s);let n;try{n=await this.#Ne.getSegmentData(this.#Pe,this.#De,r.externalId)}catch(s){this.#_e(`Storage error for segment ${t} requested by peer ${e.id}:`,s)}this.#Ce.has(e.id)&&(n?await e.uploadSegmentData(r,s,void 0!==i?new Uint8Array(n).subarray(i):n):e.sendSegmentAbsentCommand(t,s))};destroy(){clearTimeout(this.#He),this.#He=void 0,this.#j.removeEventListener(`onStorageUpdated-${this.#De}`,this.broadcastAnnouncement),this.#Re.destroy();for(const e of this.#Ce.values())e.destroy();this.#Ce.clear()}},mt=class{#it=new Map;#rt;#C=(0,Oe.default)("p2pml-core:p2p-loaders-container");#Fe;#Ue;#Ne;#W;#$e;#j;#S;#Ge;constructor(e,t,s,i,r,n,a,o,l){this.#Fe=e,this.#Ue=s,this.#Ne=i,this.#W=r,this.#$e=n,this.#j=a,this.#S=o,this.#Ge=l,this.#rt=this.#nt(t),this.#C(`set current p2p loader: ${gs(t)}`)}#at(e){if(this.#it.has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new gt(this.#Fe,e,this.#Ue,this.#Ne,this.#W,this.#$e,this.#j,this.#S,()=>{this.#rt.loader===t&&this.#Ge()}),s=gs(e);return this.#C(`created new loader: ${s}`),{loader:t,stream:e,loggerInfo:s}}#nt(e){const t=this.#it.get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{const t=this.#at(e);return this.#it.set(e.runtimeId,t),t}}changeCurrentLoader(e){const t=this.#W.swarmId??this.#Fe,s=ls(t,this.#rt.stream);this.#Ne.getStoredSegmentIds(t,s).length?this.#ot(this.#rt):this.#lt(this.#rt),this.#rt=this.#nt(e),this.#C(`change current p2p loader: ${gs(e)}`)}#ot(e){e.destroyTimeoutId=window.setTimeout(()=>this.#lt(e),this.#W.p2pInactiveLoaderDestroyTimeoutMs)}#lt(e){e.loader.destroy(),this.#it.delete(e.stream.runtimeId),this.#C("destroy p2p loader: ",e.loggerInfo)}get currentLoader(){return this.#rt.loader}destroy(){for(const{loader:e,destroyTimeoutId:t}of this.#it.values())e.destroy(),clearTimeout(t);this.#it.clear()}},pt=class{segment;requestProcessQueueCallback;bandwidthCalculators;playback;playbackConfig;infoHash;currentAttempt;_failedAttempts=new vt;finalData;bytes=[];_loadedBytes=0;_totalBytes;_status="not-started";progress;notReceivingBytesTimeout;_onAbortCallback;notReceivingBytesTimeoutMs;_logger;_isHandledByProcessQueue=!1;onSegmentError;onSegmentAbort;onSegmentStart;onSegmentLoaded;constructor(e,t,s,i,r,n,a){this.segment=e,this.requestProcessQueueCallback=t,this.bandwidthCalculators=s,this.playback=i,this.playbackConfig=r,this.infoHash=a,this.onSegmentError=n.getEventDispatcher("onSegmentError"),this.onSegmentAbort=n.getEventDispatcher("onSegmentAbort"),this.onSegmentStart=n.getEventDispatcher("onSegmentStart"),this.onSegmentLoaded=n.getEventDispatcher("onSegmentLoaded");const{byteRange:o}=this.segment;if(o){const{end:e,start:t}=o;this._totalBytes=e-t+1}this.notReceivingBytesTimeout=new yt(this.abortOnTimeout);const{type:l}=this.segment.stream;this._logger=(0,Oe.default)(`p2pml-core:request-${l}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){return this.currentAttempt?.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){return this.finalData??=Ft(this.bytes).buffer,this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(void 0!==this._totalBytes)throw new Error("Request total bytes value is already set");this._totalBytes=e}tryCompleteByLoadedBytes(e,t,s,i){if(!this._totalBytes)return!1;if(this._loadedBytes>this._totalBytes)return this.logger(`${e.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`),this.clearLoadedBytes(),!1;if(this._loadedBytes!==this._totalBytes)return!1;const r=this.start(e,t);return this.notReceivingBytesTimeout.clear(),s?this.validateAndComplete(e.downloadSource,r,s,i):r.completeOnSuccess(),!0}async validateData(e){if(!e)return!0;try{return await e(this.segment.url,this.segment.byteRange,this.data)}catch(e){return this.logger(`validation threw an error: ${String(e)}`),!1}}async validateAndComplete(e,t,s,i){const r=await this.validateData(s);if("loading"===this._status){if(!r)return this.logger(`${e} ${this.segment.externalId} validation failed for already-loaded bytes, clearing`),this.clearLoadedBytes(),void t.failWithError(new Ie(i));this.logger(`${e} ${this.segment.externalId} validation passed for already-loaded bytes`),t.completeOnSuccess()}}start(e,t){if("succeed"===this._status)throw new Error(`Request ${this.segment.externalId} has been already succeed.`);if("loading"===this._status)throw new Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus("loading"),this.currentAttempt={...e},this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState("start");const{notReceivingBytesTimeoutMs:s}=t;return this._onAbortCallback=t.onAbort,this.notReceivingBytesTimeoutMs=s,void 0!==s&&this.notReceivingBytesTimeout.start(s),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:ps(this.segment),downloadSource:e.downloadSource,peerId:"p2p"===e.downloadSource?e.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,failWithError:this.failWithError}}cancel(){this.throwErrorIfNotLoadingStatus(),this.setStatus("aborted"),this.logger(`${this.currentAttempt?.downloadSource} ${this.segment.externalId} aborted`),this._onAbortCallback?.(new Ie("abort")),this.onSegmentAbort({segment:ps(this.segment),downloadSource:this.currentAttempt?.downloadSource,peerId:"p2p"===this.currentAttempt?.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this._onAbortCallback=void 0,this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear()}abortOnTimeout=()=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress||void 0===this.notReceivingBytesTimeoutMs)return;const e=performance.now()-(this.progress.lastLoadedChunkTimestamp??this.progress.startTimestamp);if(e<this.notReceivingBytesTimeoutMs)return void this.notReceivingBytesTimeout.restart(this.notReceivingBytesTimeoutMs-e);const t=new Ie("bytes-receiving-timeout");this._onAbortCallback?.(t),this.handleFailure(t)};failWithError=e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)};handleFailure=e=>{this.currentAttempt&&(this.setStatus("failed"),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add({...this.currentAttempt,error:e}),this.onSegmentError({segment:ps(this.segment),error:e,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback())};completeOnSuccess=()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear(),this.setStatus("succeed"),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,segment:ps(this.segment),bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())};addLoadedChunk=e=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;const{byteLength:t}=e,{all:s,http:i}=this.bandwidthCalculators;s.addBytes(t),"http"===this.currentAttempt.downloadSource&&i.addBytes(t),this.bytes.push(e),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=t,this._loadedBytes+=t};firstBytesReceived=()=>{this.throwErrorIfNotLoadingStatus()};throwErrorIfNotLoadingStatus(){if("loading"!==this._status)throw new Error(`Request has been already ${this.status}.`)}logger(e){this._logger.color="http"===this.currentAttempt?.downloadSource?"green":"red",this._logger(e),this._logger.color=""}manageBandwidthCalculatorsState(e){const{all:t,http:s}=this.bandwidthCalculators,i="start"===e?"startLoading":"stopLoading";"http"===this.currentAttempt?.downloadSource&&s[i](),t[i]()}},vt=class{attempts=[];add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>"http"===t.downloadSource?e+1:e,0)}get p2pAttemptsCount(){return this.attempts.reduce((e,t)=>"p2p"===t.downloadSource?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}},yt=class{action;timeoutId;ms;constructor(e){this.action=e}start(e){if(this.timeoutId)throw new Error("Timeout is already started.");this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.clear(),void 0!==e&&(this.ms=e),void 0!==this.ms&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}},St=class{requestProcessQueueCallback;bandwidthCalculators;playback;config;eventTarget;swarmId;requests=new Map;constructor(e,t,s,i,r,n){this.requestProcessQueueCallback=e,this.bandwidthCalculators=t,this.playback=s,this.config=i,this.eventTarget=r,this.swarmId=n}get executingHttpCount(){let e=0;for(const t of this.httpRequests())"loading"===t.status&&e++;return e}get executingP2PCount(){let e=0;for(const t of this.p2pRequests())"loading"===t.status&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);if(!t){const s=us(ls(this.swarmId,e.stream));t=new pt(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,s),this.requests.set(e,t)}return t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(const e of this.requests.values())"http"===e.downloadSource&&(yield e)}*p2pRequests(){for(const e of this.requests.values())"p2p"===e.downloadSource&&(yield e)}destroy(){for(const e of this.requests.values())"loading"===e.status&&e.cancel();this.requests.clear()}},Et=class{segment;engineCallbacks;_status="pending";_shouldBeStartedImmediately=!1;constructor(e,t){this.segment=e,this.engineCallbacks=t}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){"pending"===this._status&&(this._status="succeed",this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){"pending"===this._status&&(this._status="failed",this.engineCallbacks.onError(new Le("failed")))}abort(){"pending"===this._status&&(this._status="aborted",this.engineCallbacks.onError(new Le("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}},bt=class{streamManifestUrl;lastRequestedSegment;streamDetails;config;bandwidthCalculators;segmentStorage;webTorrentSocketPool;eventTarget;peerId;requests;engineRequest;p2pLoaders;playback;segmentAvgDuration;logger;levelChangedTimestamp;lastQueueProcessingTimeStamp;randomHttpDownloadTimeout;initialHttpDelayTimeoutId;isProcessQueueMicrotaskCreated=!1;swarmId;createdAt=performance.now();constructor(e,t,s,i,r,n,a,o,l){this.streamManifestUrl=e,this.lastRequestedSegment=t,this.streamDetails=s,this.config=i,this.bandwidthCalculators=r,this.segmentStorage=n,this.webTorrentSocketPool=a,this.eventTarget=o,this.peerId=l;const h=this.lastRequestedSegment.stream;this.swarmId=this.config.swarmId??this.streamManifestUrl,this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=function(e){const{segments:t}=e;let s=0;const{size:i}=t;if(0===i)return 0;for(const e of t.values())s+=e.endTime-e.startTime;return s/i}(h),this.requests=new St(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new mt(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,Oe.default)(`p2pml-core:hybrid-loader-${h.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=1e3*Math.random()*e+1e3;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}async loadSegment(e,t){this.logger(`requests: ${ms(e)}`);const{stream:s}=e;s!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${gs(s)}`),this.p2pLoaders.changeCurrentLoader(s)),this.lastRequestedSegment=e;const i=ls(this.swarmId,s);this.segmentStorage.onSegmentRequested(this.swarmId,i,e.externalId,e.startTime,e.endTime,s.type,this.streamDetails.isLive);const r=new Et(e,t);try{if(this.segmentStorage.hasSegment(this.swarmId,i,e.externalId)){const t=await this.segmentStorage.getSegmentData(this.swarmId,i,e.externalId);if(t){const{queueDownloadRatio:e}=this.generateQueue();return void r.resolve(t,this.getBandwidth(e))}}this.engineRequest?.abort(),this.engineRequest=r;const t=this.requests.get(e);"failed"===t?.status&&t.failedAttempts.clear()}catch(t){this.logger(`request failed for ${ms(e)} in ${gs(s)}`,t),r.reject()}finally{this.requestProcessQueueMicrotask()}}requestProcessQueueMicrotask=(e=!0)=>{const t=performance.now();!e&&void 0!==this.lastQueueProcessingTimeStamp&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,xt(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))};processRequests(e,t){const{stream:s}=this.lastRequestedSegment,{httpErrorRetries:i}=this.config,r=performance.now();for(const n of this.requests.items()){const{downloadSource:a,status:o,segment:l,isHandledByProcessQueue:h}=n,d=this.engineRequest?.segment===l?this.engineRequest:void 0;switch(o){case"loading":e.has(l.runtimeId)||d||(n.cancel(),this.requests.remove(n));break;case"succeed":{if(!a)break;"http"===a&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),d&&(d.resolve(n.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(n),this.logger(`succeed: ${ms(l)} (byteLength: ${n.data.byteLength})`);const e=ls(this.swarmId,s);this.segmentStorage.storeSegment(this.swarmId,e,l.externalId,n.data,l.startTime,l.endTime,l.stream.type,this.streamDetails.isLive);break}case"failed":"http"!==a||h||this.p2pLoaders.currentLoader.broadcastAnnouncement(),d||s.segments.has(n.segment.runtimeId)||this.requests.remove(n),n.failedAttempts.httpAttemptsCount>=i&&d&&(this.engineRequest=void 0,d.reject());break;case"not-started":case"aborted":this.requests.remove(n)}n.markHandledByProcessQueue();const{lastAttempt:c}=n.failedAttempts;c&&r-c.error.timestamp>6e4&&n.failedAttempts.clear()}}processQueue(){const{queue:e,queueSegmentIds:t,queueDownloadRatio:s}=this.generateQueue();this.processRequests(t,s);const{simultaneousHttpDownloads:i,simultaneousP2PDownloads:r,httpErrorRetries:n,httpDownloadInitialTimeoutMs:a}=this.config,o=performance.now()-this.createdAt,l=a>0&&o<a;l&&(this.initialHttpDelayTimeoutId??=window.setTimeout(()=>{this.initialHttpDelayTimeoutId=void 0,this.requestProcessQueueMicrotask()},a-o));const{engineRequest:h}=this;if(h){const{segment:e}=h,t=this.requests.get(e);if(h.shouldBeStartedImmediately&&"pending"===h.status&&(!t||"not-started"===t.status||"failed"===t.status||"aborted"===t.status)){const s=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(e)&&this.requests.executingP2PCount<r;this.config.preferP2PForEngineRequest&&s?this.loadThroughP2P(e):!l&&(t?.failedAttempts.httpAttemptsCount??0)<n&&this.requests.executingHttpCount<i?this.loadThroughHttp(e):s&&this.loadThroughP2P(e)}}for(const t of e){const{statuses:s,segment:a}=t,o=this.requests.get(a);if("succeed"!==o?.status)if(s.isHighDemand){const t=!l&&(o?.failedAttempts.httpAttemptsCount??0)<n;if("loading"===o?.status){!this.config.preferP2PForEngineRequest&&t&&"p2p"===o.downloadSource&&(this.requests.executingHttpCount<i||this.abortLastHttpLoadingInQueueAfterItem(e,a))&&(o.cancel(),this.loadThroughHttp(a));continue}const s=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(a)&&(this.requests.executingP2PCount<r||this.abortLastP2PLoadingInQueueAfterItem(e,a));if(this.config.preferP2PForEngineRequest&&s){this.loadThroughP2P(a);continue}if(t&&(this.requests.executingHttpCount<i||this.abortLastHttpLoadingInQueueAfterItem(e,a))){this.loadThroughHttp(a);continue}s&&this.loadThroughP2P(a)}else s.isP2PDownloadable&&"loading"!==o?.status&&this.requests.executingP2PCount<r&&this.loadThroughP2P(a)}}abortSegmentRequest(e){this.engineRequest?.segment.runtimeId===e&&(this.engineRequest.abort(),this.logger("abort: ",ms(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){new Pe(this.requests.getOrCreateRequest(e),this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){const{httpDownloadInitialTimeoutMs:e}=this.config;if(e>0&&performance.now()-this.createdAt<e)return;const t=this.getAvailableStorageCapacityPercent();if(t<=10)return;const{simultaneousHttpDownloads:s,httpErrorRetries:i}=this.config,r=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=s||!r.connectedPeerCount)return;const n=[];for(const{segment:e,statuses:s}of vs(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){const t=ls(this.swarmId,e.stream);if(!s.isHttpDownloadable||s.isP2PDownloadable||this.segmentStorage.hasSegment(this.swarmId,t,e.externalId))continue;const r=this.requests.get(e);r&&("loading"===r.status||"succeed"===r.status||r.failedAttempts.httpAttemptsCount>=i)||n.push(e)}if(!n.length)return;if(s-this.requests.executingHttpCount===0)return;const a=r.connectedPeerCount+1,o=Math.min(n.length,s*a),l=function(e){for(let t=e.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]]}return e}(Array.from({length:o},(e,t)=>t));let h=o/a;for(const e of l){if(this.requests.executingHttpCount>=s)break;if(h>=1||Math.random()<=h){const t=n[e];this.loadThroughHttp(t)}if(h--,h<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:s}of Bt(e)){if(s===t)break;const e=this.requests.get(s);if("http"===e?.downloadSource&&"loading"===e.status)return e.cancel(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(const{segment:s}of Bt(e)){if(s===t)break;const e=this.requests.get(s);if("p2p"===e?.downloadSource&&"loading"===e.status)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){const{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){const e=[],t=new Set;let s=0,i=0;const r=this.getAvailableStorageCapacityPercent();for(const n of vs(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,r)){s++;const{segment:r}=n,a=ls(this.swarmId,r.stream);this.segmentStorage.hasSegment(this.swarmId,a,r.externalId)||"succeed"===this.requests.get(r)?.status?i++:(e.push(n),t.add(r.runtimeId))}return{queue:e,queueSegmentIds:t,maxPossibleLength:s,alreadyLoadedCount:i,queueDownloadRatio:0!==s?i/s:0}}getBandwidth(e){const{http:t,all:s}=this.bandwidthCalculators,{activeLevelBitrate:i}=this.streamDetails;if(0===i)return s.getBandwidthLoadingOnly(3);const r=Math.max(s.getBandwidth(30,this.levelChangedTimestamp),s.getBandwidth(60,this.levelChangedTimestamp),s.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||r>=.9*i)return Math.max(s.getBandwidthLoadingOnly(1),s.getBandwidthLoadingOnly(3),s.getBandwidthLoadingOnly(5));const n=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(r,n)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){const s=this.playback.rate!==t,i=this.playback.position!==e;if(!s&&!i)return;const r=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;i&&(this.playback.position=e),s&&0!==t&&(this.playback.rate=t),r&&(this.logger("position significantly changed"),this.engineRequest?.markAsShouldBeStartedImmediately()),this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(r)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${gs(e)}`),this.requestProcessQueueMicrotask())}destroy(){clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),this.engineRequest?.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}},Tt=(e,t)=>`${e}|${t}`,wt=e=>/Android/i.test(e),It=e=>/iPad|iPhone/i.test(e),Lt=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e)),At=1048576,kt=class{userAgent=navigator.userAgent;segmentMemoryStorageLimit=4096;currentStorageUsage=0;cache=new Map;logger;coreConfig;mainStreamConfig;secondaryStreamConfig;currentPlayback;lastRequestedSegment;segmentChangeCallback;constructor(){this.logger=(0,Oe.default)("p2pml-core:segment-memory-storage"),this.logger.color="RebeccaPurple"}async initialize(e,t,s){this.coreConfig=e,this.mainStreamConfig=t,this.secondaryStreamConfig=s,this.setMemoryStorageLimit(),this.logger("initialized")}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,s,i,r,n,a){this.lastRequestedSegment={streamId:t,segmentId:s,startTime:i,endTime:r,swarmId:e,streamType:n,isLiveStream:a}}async storeSegment(e,t,s,i,r,n,a,o){this.clear(o,i.byteLength);const l=Tt(t,s);if(this.cache.set(l,{data:i,segmentId:s,streamId:t,startTime:r,endTime:n,streamType:a}),this.increaseStorageUsage(i.byteLength),this.logger(`add segment: ${s} to ${t}`),!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)}async getSegmentData(e,t,s){const i=Tt(t,s),r=this.cache.get(i);if(void 0!==r)return r.data}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};const e=this.currentPlayback.position;let t=0;for(const{endTime:s,data:i}of this.cache.values())e>s||(t+=i.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/At}}hasSegment(e,t,s){const i=Tt(t,s);return void 0!==this.cache.get(i)}getStoredSegmentIds(e,t){const s=[];for(const{segmentId:e,streamId:i}of this.cache.values())i===t&&s.push(e);return s}clear(e,t){if(!(this.currentPlayback&&this.mainStreamConfig&&this.secondaryStreamConfig&&this.coreConfig))return;if(!this.isMemoryLimitReached(t)&&!e)return;const s=new Set,i=Array.from(this.cache.values()).sort((e,t)=>e.startTime-t.startTime);for(const r of i){const{streamId:i,segmentId:n,data:a}=r,o=Tt(i,n);if(this.shouldRemoveSegment(r,e,this.currentPlayback.position)&&(this.cache.delete(o),s.add(i),this.decreaseStorageUsage(a.byteLength),this.logger(`Removed segment ${n} from stream ${i}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(s)}isMemoryLimitReached(e){return this.currentStorageUsage+e/At>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){0!==e.size&&e.forEach(e=>{if(!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(e)})}shouldRemoveSegment(e,t,s){const{endTime:i,streamType:r}=e,n=this.getStreamTimeWindow(r,"highDemandTimeWindow");return!(s<=i)&&(!t||s>n+i)}increaseStorageUsage(e){this.currentStorageUsage+=e/At}decreaseStorageUsage(e){this.currentStorageUsage-=e/At}setMemoryStorageLimit(){this.coreConfig?.segmentMemoryStorageLimit?this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit:Lt(this.userAgent)||It(this.userAgent)?this.segmentMemoryStorageLimit=1024:wt(this.userAgent)&&(this.segmentMemoryStorageLimit=2048)}getStreamTimeWindow(e,t){return("main"===e?this.mainStreamConfig:this.secondaryStreamConfig)?.[t]??0}destroy(){this.cache.clear(),this.segmentChangeCallback=void 0}},Rt=class{#W;#ht="disconnected";#dt=null;#ct=0;#ut=null;#j=new rt;constructor(e){const t=Math.max(100,e.initialDelay??1e3);this.#W={url:e.url,initialDelay:t,maxDelay:Math.max(t,e.maxDelay??3e4),jitterMultiplier:Math.max(0,e.jitterMultiplier??.2)}}get state(){return this.#ht}addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}connect(){if("connected"!==this.#ht&&"connecting"!==this.#ht&&"disposed"!==this.#ht){this.#ht="connecting",this.#ft();try{this.#dt=new WebSocket(this.#W.url),this.#dt.binaryType="arraybuffer",this.#dt.onopen=this.#gt,this.#dt.onclose=this.#mt,this.#dt.onerror=this.#pt,this.#dt.onmessage=this.#vt}catch(e){this.#ht="disconnected";const t=new ErrorEvent("error",{message:e instanceof Error?e.message:"Unknown WebSocket creation error",error:e});this.#j.dispatchEvent("error",t)}}}send(e){if("connected"!==this.#ht||!this.#dt)throw new Error("WebSocketClient: Cannot send data when not connected");this.#dt.send(e)}dispose(){this.#ht="disposed",this.#ft(),this.#dt&&(this.#dt.onopen=null,this.#dt.onclose=null,this.#dt.onerror=null,this.#dt.onmessage=null,this.#dt.close(),this.#dt=null),this.#j.clear()}#gt=()=>{"disposed"!==this.#ht&&(this.#ht="connected",this.#ct=0,this.#j.dispatchEvent("connected"))};#mt=()=>{"disposed"!==this.#ht&&(this.#dt&&(this.#dt.onopen=null,this.#dt.onclose=null,this.#dt.onerror=null,this.#dt.onmessage=null,this.#dt=null),this.#yt(),this.#j.dispatchEvent("disconnected"))};#pt=e=>{"disposed"!==this.#ht&&this.#j.dispatchEvent("error",e)};#vt=e=>{"disposed"!==this.#ht&&this.#j.dispatchEvent("message",e.data)};#yt(){if("disposed"===this.#ht)return;this.#ht="reconnecting";const e=Math.min(this.#W.initialDelay*Math.pow(2,this.#ct),this.#W.maxDelay),t=e*this.#W.jitterMultiplier,s=2*Math.random()*t-t,i=Math.max(0,e+s);e<this.#W.maxDelay&&this.#ct++,this.#ut=setTimeout(()=>{"disposed"!==this.#ht&&this.connect()},i),this.#j.dispatchEvent("reconnecting")}#ft(){null!==this.#ut&&(clearTimeout(this.#ut),this.#ut=null)}},Ct=class{#St=new Map;#j=new rt;addEventListener(e,t){this.#j.addEventListener(e,t)}removeEventListener(e,t){this.#j.removeEventListener(e,t)}acquire(e){let t=this.#St.get(e);if(!t){const s=new Rt({url:e});s.addEventListener("error",t=>{this.#j.dispatchEvent("error",t,e)}),s.connect(),t={client:s,refCount:0},this.#St.set(e,t)}t.refCount++;let s=!1;return{client:t.client,release:()=>{s||(s=!0,t.refCount--,t.refCount<=0&&(t.refCount<0&&console.error(`[WebTorrentSocketPool] Negative refCount detected for ${e}`),this.#St.get(e)===t&&this.#St.delete(e),t.client.dispose()))}}}destroy(){this.#j.clear();const e=Array.from(this.#St.values());this.#St.clear();for(const t of e)try{t.client.dispose()}catch(e){console.error("[WebTorrentSocketPool] Failed to dispose WebSocketClient:",e)}}},Pt=class e{static DEFAULT_COMMON_CORE_CONFIG={segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:ft};static DEFAULT_STREAM_CONFIG={isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,preferP2PForEngineRequest:!1,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:65535,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:3e4,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:["wss://tracker.novage.com.ua","wss://tracker.openwebtorrent.com"],rtcConfig:{iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478"}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3};eventTarget=new rt;manifestResponseUrl;streams=new Map;mainStreamConfig;secondaryStreamConfig;commonCoreConfig;bandwidthCalculators={all:new tt,http:new tt};segmentStorage;webTorrentSocketPool=new Ct;socketPoolLogger=(0,Oe.default)("p2pml-core:webtorrent-socket-pool");peerId;mainStreamLoader;secondaryStreamLoader;streamDetails={isLive:!1,activeLevelBitrate:0};storageInitPromise;constructor(t){const s=function e(t){if(Ut(t)){const s={};return Object.keys(t).forEach(i=>{if(void 0!==t[i]){const r=e(t[i]);void 0!==r&&(s[i]=r)}}),s}return t}(t??{});this.commonCoreConfig=Gt({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:s}),this.mainStreamConfig=Gt({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.mainStream}),this.secondaryStreamConfig=Gt({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.secondaryStream}),this.peerId=function(e){const t=[e],s=20-e.length;for(let e=0;e<s;e++)t.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(62*Math.random())]);return t.join("")}(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener("error",(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return{...Nt(this.commonCoreConfig),mainStream:Nt(this.mainStreamConfig),secondaryStream:Nt(this.secondaryStreamConfig)}}applyDynamicConfig(e){const{mainStream:t,secondaryStream:s}=e,i=Nt(this.mainStreamConfig),r=Nt(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,s),this.processSpecificDynamicConfigParams(i,e,"main"),this.processSpecificDynamicConfigParams(r,e,"secondary")}processSpecificDynamicConfigParams(e,t,s){const i=this.getUpdatedStreamProperty("isP2PDisabled",t,s);i&&e.isP2PDisabled!==i&&this.destroyStreamLoader(s);const r=this.getUpdatedStreamProperty("isP2PUploadDisabled",t,s);void 0!==r&&e.isP2PUploadDisabled!==r&&("main"===s?this.mainStreamLoader:this.secondaryStreamLoader)?.sendBroadcastAnnouncement(r)}getUpdatedStreamProperty(e,t,s){return("main"===s?t.mainStream:t.secondaryStream)?.[e]??t[e]}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split("?")[0]}hasSegment(e){return!!hs(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,{...e,segments:new Map})}updateStream(e,t,s){const i=this.streams.get(e);if(i){if(t)for(const e of t)i.segments.has(e.runtimeId)||i.segments.set(e.runtimeId,{...e,stream:i});if(s)for(const e of s)i.segments.delete(e);this.mainStreamLoader?.updateStream(i),this.secondaryStreamLoader?.updateStream(i)}}async loadSegment(e,t){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");await this.initializeSegmentStorage();const s=this.identifySegment(e);this.getStreamHybridLoader(s).loadSegment(s,t)}abortSegmentLoading(e){this.mainStreamLoader?.abortSegmentRequest(e),this.secondaryStreamLoader?.abortSegmentRequest(e)}updatePlayback(e,t){this.mainStreamLoader?.updatePlayback(e,t),this.secondaryStreamLoader?.updatePlayback(e,t)}setActiveLevelBitrate(e){e!==this.streamDetails.activeLevelBitrate&&(this.streamDetails.activeLevelBitrate=e,this.mainStreamLoader?.notifyLevelChanged(),this.secondaryStreamLoader?.notifyLevelChanged())}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{const t=this.identifySegment(e);return!("main"===t.stream.type&&this.mainStreamConfig.isP2PDisabled||"secondary"===t.stream.type&&this.secondaryStreamConfig.isP2PDisabled)}catch{return!1}}destroy(){this.streams.clear(),this.mainStreamLoader?.destroy(),this.secondaryStreamLoader?.destroy(),this.segmentStorage?.setSegmentChangeCallback(void 0),this.segmentStorage?.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}async initializeSegmentStorage(){if(!this.segmentStorage){if(this.storageInitPromise)return this.storageInitPromise;this.storageInitPromise=(async()=>{const{isLive:e}=this.streamDetails,t=this.commonCoreConfig.customSegmentStorageFactory;if(t&&"function"!=typeof t)throw new Error("Storage configuration is invalid");const s=t?t(e):new kt;try{await s.initialize(this.commonCoreConfig,this.mainStreamConfig,this.secondaryStreamConfig)}catch(e){throw s.destroy(),e}if(!this.storageInitPromise)return s.setSegmentChangeCallback(void 0),void s.destroy();s.setSegmentChangeCallback(e=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${e}`)}),this.segmentStorage=s})();try{await this.storageInitPromise}finally{this.storageInitPromise=void 0}}}identifySegment(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is undefined");const t=hs(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,s){$t(this.commonCoreConfig,e),$t(this.mainStreamConfig,e),$t(this.secondaryStreamConfig,e),t&&$t(this.mainStreamConfig,t),s&&$t(this.secondaryStreamConfig,s)}destroyStreamLoader(e){"main"===e?(this.mainStreamLoader?.destroy(),this.mainStreamLoader=void 0):(this.secondaryStreamLoader?.destroy(),this.secondaryStreamLoader=void 0)}getStreamHybridLoader(e){return"main"===e.stream.type?(this.mainStreamLoader??=this.createNewHybridLoader(e),this.mainStreamLoader):(this.secondaryStreamLoader??=this.createNewHybridLoader(e),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");if(!this.segmentStorage)throw new Error("Segment storage is not initialized");const t="main"===e.stream.type?this.mainStreamConfig:this.secondaryStreamConfig;return new bt(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}},Dt=Oe.debug}}),Go={};function Ho(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Wo(e){return"initSegment"!==e.sn}function qo(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function jo(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}function Ko(e,t){const s=Object.getPrototypeOf(e);if(s){return Object.getOwnPropertyDescriptor(s,t)||Ko(s,t)}}function Vo(e,t){const s=Ko(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}function Yo(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function zo(){return zo=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},zo.apply(null,arguments)}function Qo(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function Xo(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Qo(Object(s),!0).forEach(function(t){Yo(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Qo(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}function Jo(e,t){if(null==e)return{};var s,i,r=function(e,t){if(null==e)return{};var s={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;s[i]=e[i]}return s}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(i=0;i<n.length;i++)s=n[i],-1===t.indexOf(s)&&{}.propertyIsEnumerable.call(e,s)&&(r[s]=e[s])}return r}function Zo(e){switch(e.details){case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_TIMEOUT:case ws.LEVEL_LOAD_TIMEOUT:case ws.MANIFEST_LOAD_TIMEOUT:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.SUBTITLE_TRACK_LOAD_TIMEOUT:case ws.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function el(e){return e.details.startsWith("key")}function tl(e){return el(e)&&!!e.frag&&!e.frag.decryptdata}function sl(e,t){const s=Zo(t);return e.default[(s?"timeout":"error")+"Retry"]}function il(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function rl(e){return Xo(Xo({},e),{errorRetry:null,timeoutRetry:null})}function nl(e,t,s,i){if(!e)return!1;const r=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return al(e)||!!e&&(e<400||e>499)}(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function al(e){return 0===e&&!1===navigator.onLine}function ol(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}function ll(){return zo({},Ns)}function hl(e,t,s){return t[e]?t[e].bind(t):function(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Us}(e,s)}function dl(e=!0){if("undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function cl(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(e=>-1===i.indexOf(e))}function ul(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}function fl(e,t){if(e<0)return-fl(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}function gl(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)})}}}function ml(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function pl(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function vl(e,t){return ml(e,t)&&pl(e,t+6)+10<=e.length-t}function yl(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Sl(e,t){const s=t;let i=0;for(;ml(e,t);)i+=10,i+=pl(e,t+6),yl(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(s,s+i)}function El(e,t=0,s=1/0){return function(e,t,s,i){const r=ul(n=e)?n:n.buffer;var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(c=e)&&ul(c.buffer)&&void 0!==c.byteLength&&void 0!==c.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/a,h=(o+t)/a,d=Math.floor(Math.max(0,Math.min(h,l)));var c;return new i(r,d,Math.floor(Math.min(d+Math.max(s,0),l))-d)}(e,t,s,Uint8Array)}function bl(e,t=!1){const s=t?e.indexOf(0):e.length,i=function(e,t={}){let s;s=ul(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0,{encoding:r}=t;if(!r){const e=s.getUint8(0),t=s.getUint8(1);239==e&&187==t&&191==s.getUint8(2)?(r=js,i=3):254==e&&255==t?(r=Ws,i=2):255==e&&254==t?(r=qs,i=2):r=js}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(s);const{byteLength:n}=s,a=r!==Ws;let o,l="";for(;i<n;){switch(r){case js:if(o=s.getUint8(i),o<128)i++;else if(o>=194&&o<=223)if(i+1<n){const e=s.getUint8(i+1);e>=128&&e<=191?(o=(31&o)<<6|63&e,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=n-1){const e=s.getUint8(i+1),t=s.getUint8(i+2);e>=128&&e<=191&&t>=128&&t<=191?(o=(15&o)<<12|(63&e)<<6|63&t,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=n-1){const e=s.getUint8(i+1),t=s.getUint8(i+2),r=s.getUint8(i+3);e>=128&&e<=191&&t>=128&&t<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&e)<<12|(63&t)<<6|63&r,i+=4):i++}else i++;else i++;break;case Ws:case Hs:case qs:o=s.getUint16(i,a),i+=2}l+=String.fromCodePoint(o)}return l}(new DataView(e.buffer,e.byteOffset,s),{encoding:js});return t?i:i.replace(/\0/g,"")}function Tl(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=bl(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=bl(e.data.subarray(t),!0);t+=s.length+1;const i=bl(e.data.subarray(t));return{key:e.type,info:s,data:i}}const t=bl(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?function(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const i=bl(El(e.data,1,s)),r=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=bl(El(e.data,3+s,n));let o;var l;return o="--\x3e"===i?bl(El(e.data,4+s+n)):ul(l=e.data.subarray(4+s+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,t.mimeType=i,t.pictureType=r,t.description=a,t.data=o,t}(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const{data:s}=e,i=bl(s.subarray(t),!0);t+=i.length+1;const r=bl(s.subarray(t));return{key:e.type,info:i,data:r}}const t=bl(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function wl(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=pl(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}function Il(e){let t=0;const s=[];for(;ml(e,t);){const i=pl(e,t+6);e[t+5]>>6&1&&(t+=Ks),t+=Ks;const r=t+i;for(;t+Vs<r;){const i=wl(e.subarray(t)),r=Tl(i);r&&s.push(r),t+=i.size+Ks}yl(e,t)&&(t+=Ks)}return s}function Ll(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Al(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}}function kl(e){const t=Il(e);for(const e of t)if(Ll(e))return Al(e)}function Rl(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Cl(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Pl(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Dl(e){return String.fromCharCode.apply(null,e)}function Ml(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function _l(e,t){const s=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return s<0?4294967296+s:s}function Ol(e,t){let s=_l(e,t);return s*=Math.pow(2,32),s+=_l(e,t+4),s}function xl(e,t){let s="";for(let i=t;i<e.length;i++)if(s+=String.fromCharCode(e[i]),0===e[i])return s;return null}function Fl(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Bl(e,t,s){e[t]=s>>24,e[t+1]=s>>16&255,e[t+2]=s>>8&255,e[t+3]=255&s}function Ul(e,t,s){const i=t.byteOffset-e.byteOffset-8,r=8+s,n=t.byteLength+8-r;n<8||(Bl(e,i,r),Bl(e,i+r,n),Bl(e,i+r+4,zs.free))}function Nl(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function $l(e,t){t.sort((e,t)=>e[0]-t[0]);const s=t.reduce((e,[t,s])=>e+s-t,0),i=new Uint8Array(e.byteLength-s);let r=0,n=0;for(let s=0;s<t.length;s++){const[a,o]=t[s];i.set(e.subarray(r,a),n),n+=a-r,r=o}return i.set(e.subarray(r),n),{result:i,dropped:s,droppedBefore:e=>t.reduce((t,[s,i])=>i<=e?t+i-s:t,0)}}function Gl(e,t){const s=[];return t.length?(Hl(e,t,0,0,e.byteLength,s),s):s}function Hl(e,t,s,i,r,n){const a=t[s];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),d=a.charCodeAt(3),c=t.length-1;for(let a=i;a<r;){const i=a+8<=r,u=a+4<=r?16777216*e[a]+(e[a+1]<<16|e[a+2]<<8|e[a+3]):_l(e,a),f=u>1?a+u:r;if(i&&e[a+4]===o&&e[a+5]===l&&e[a+6]===h&&e[a+7]===d){const i=Math.min(f,r);s===c?n.push(e.subarray(a+8,i)):Hl(e,t,s+1,a+8,i,n)}a=f}}function Wl(e){const t=[],s=e[0];let i=8;const r=_l(e,i);i+=4;let n=0,a=0;0===s?(n=_l(e,i),a=_l(e,i+4),i+=8):(n=Ol(e,i),a=Ol(e,i+8),i+=16),i+=2;let o=e.length+a;const l=Ml(e,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=_l(e,s);s+=4;const a=2147483647&n;if(1==(2147483648&n)>>>31)return Gs.warn("SIDX has hierarchical references (not supported)"),null;const l=_l(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function ql(e){const t=[],s=Gl(e,["moov","trak"]);for(let e=0;e<s.length;e++){const i=s[e],r=Gl(i,["tkhd"])[0];if(r){let e=r[0];const s=_l(r,0===e?12:20),n=Gl(i,["mdia","mdhd"])[0];if(n){e=n[0];const r=_l(n,0===e?12:20),a=Gl(i,["mdia","hdlr"])[0];if(a){const e=Dl(a.subarray(8,12)),n={soun:Ds.AUDIO,vide:Ds.VIDEO}[e],o=jl(Gl(i,["mdia","minf","stbl","stsd"])[0]);n?(t[s]={timescale:r,type:n,stsd:o},t[n]=Xo({timescale:r,id:s},o)):t[s]={timescale:r,type:e,stsd:o}}}}}return Gl(e,["moov","mvex","trex"]).forEach(e=>{const s=_l(e,4),i=t[s];i&&(i.default={duration:_l(e,12),sampleSize:_l(e,16),flags:_l(e,20)})}),t}function jl(e){const t=e.subarray(8),s=t.subarray(86),i=Dl(t.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const e=Gl(t,[i])[0];Gl(e.subarray("enca"===i?28:78),["sinf"]).forEach(e=>{const t=Gl(e,["schm"])[0];if(t){const s=Dl(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Gl(e,["frma"])[0];t&&(n=Dl(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Gl(s,["avcC"])[0];e&&e.length>3&&(n+="."+Yl(e[1])+Yl(e[2])+Yl(e[3]),r=Kl("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=Gl(t,[i])[0],s=Gl(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=Vl(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=Vl(s,e);const i=s[e++];if(64!==i)break;if(n+="."+Yl(i),e+=12,5!==s[e++])break;e=Vl(s,e);const r=s[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=Gl(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],i=31&t,r=_l(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+i,n+="."+function(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let e=l.length;e--;){const t=l[e];(t||h)&&(h="."+t.toString(16).toUpperCase()+h)}n+=h}r=Kl("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Kl(n,s)||n;break;case"vp09":{const e=Gl(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],i=e[6]>>4&15;n+="."+zl(t)+"."+zl(s)+"."+zl(i)}break}case"av01":{const e=Gl(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,i=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,h=2===t&&o?l?12:10:o?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,v=0;n+="."+t+"."+zl(i)+a+"."+zl(h)+"."+d+"."+c+u+f+"."+zl(g)+"."+zl(m)+"."+zl(p)+"."+v,r=Kl("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:r}}function Kl(e,t){const s=Gl(t,["dvvC"]),i=s.length?s[0]:Gl(t,["dvcC"])[0];if(i){const t=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return e+"."+zl(t)+"."+zl(s)}}function Vl(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function Yl(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function zl(e){return(e<10?"0":"")+e}function Ql(e,t){Gl(e,["moov","trak"]).forEach(e=>{const s=Gl(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=Gl(i,["enca"]);const n=r.length>0;n||(r=Gl(i,["encv"])),r.forEach(e=>{Gl(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const s=Xl(e);s&&t(s,n)})})})}function Xl(e){const t=Gl(e,["schm"])[0];if(t){const s=Dl(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=Gl(e,["schi","tenc"])[0];if(t)return t}}}function Jl(e){return"undefined"==typeof TextDecoder?bl(e):(Xs||(Xs=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function Zl(e,t,s,i,r){const n={};let a=!1;const o=function(e){const t=e.byteLength,s=[];for(let i=0;i<t;){const r=i+8<=t,n=i+4<=t?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):_l(e,i),a=n>1?i+n:t;if(r&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7]){const r=Math.min(a,t);for(let t=i+8;t<r;){const n=t+8<=r,a=t+4<=r?16777216*e[t]+(e[t+1]<<16|e[t+2]<<8|e[t+3]):_l(e,t),o=a>1?t+a:r;if(n&&116===e[t+4]&&114===e[t+5]&&97===e[t+6]&&102===e[t+7]){const n=Math.min(o,r);let a,l;const h=[];for(let s=t+8;s<n;){const t=s+8<=n,i=s+4<=n?16777216*e[s]+(e[s+1]<<16|e[s+2]<<8|e[s+3]):_l(e,s),r=i>1?s+i:n;if(t&&116===e[s+4]){const t=Math.min(r,n);102===e[s+5]&&104===e[s+6]&&100===e[s+7]?l||(l=e.subarray(s+8,t)):102===e[s+5]&&100===e[s+6]&&116===e[s+7]?a||(a=e.subarray(s+8,t)):114===e[s+5]&&117===e[s+6]&&110===e[s+7]&&h.push(e.subarray(s+8,t))}s=r}s.push({moofOffset:e.byteOffset+i,tfdt:a,tfhd:l,truns:h})}t=o}}i=a}return s}(e),l=e.byteLength;for(let c=0;c<o.length;c++){const{moofOffset:u,tfdt:f,tfhd:g,truns:m}=o[c],p=_l(g,4),v=t[p];if(!v)continue;const y=n[p]||(n[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type});let S;if(f){const e=f[0];S=_l(f,4),1===e&&(S===Ys?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Ys+1,S+=_l(f,8))),Ss(S)&&(!Ss(y.start)||S<y.start)&&(y.start=S),r&&Ss(S)&&(r.timeOffset=S/r.timescale)}const E=(null==r?void 0:r.trackId)===p&&v.type===Ds.VIDEO,b=v.default,T=16777215&_l(g,0);let w,I=(null==b?void 0:b.duration)||0,L=(null==b?void 0:b.sampleSize)||0,A=8;1&T&&(A+=8),2&T&&(A+=4),8&T&&(I=_l(g,A),w=g.byteOffset-e.byteOffset+A,A+=4),16&T&&(L=_l(g,A));let k=0;const R=!!(1&T),C=!R&&!!(131072&T);R?(k=_l(g,8),k*=Math.pow(2,32),k+=_l(g,12)):C&&(k=u);let P=S||0,D=0,M=I;for(let t=0;t<m.length;t++){const s=m[t],n=_l(s,4),a=y.sampleCount;y.sampleCount+=n;const o=1&s[3];let c=0;const u=4&s[3],f=1&s[2],g=2&s[2],p=4&s[2],v=8&s[2];let S=8;o&&(c=Fl(s,S),S+=4),u&&(1&s[S+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=a),S+=4);let b,T,A,R=k+c;if(!i&&0===s[1]&&6===s[2]&&1===s[3]){var h,d;const t=P,i=R,a=S;let o=-1,c=0,u=0,f=null!=(h=null==r?void 0:r.timeOffset)?h:0;const g=I/(null!=(d=null==r?void 0:r.timescale)?d:1),m=!0===(null==r?void 0:r.isHEVCFlavor),p=m?2:1;for(let t=0;t<n;t++){const i=0===s[S]?s[S+1]<<16|s[S+2]<<8|s[S+3]:_l(s,S),n=-1===o&&void 0===y.keyFrameIndex&&!(1&s[S+5]);S+=8;const a=R+i;if(E){if(i>0){let t=R;do{const s=0===e[t]?e[t+1]<<16|e[t+2]<<8|e[t+3]:_l(e,t);t+=4;const i=e[t],n=m?i>>1&63:31&i;(m?39===n||40===n:6===n)&&ih(e.subarray(t,t+s),p,f,r.samples),t+=s}while(t<a)}f+=g}R=a,n&&(o=t,c=R)}if(R<=l)u=n;else{let e=i,t=a;for(let i=0;i<n&&(e+=0===s[t]?s[t+1]<<16|s[t+2]<<8|s[t+3]:_l(s,t),!(e>l));i++)u=i+1,t+=8}if(E&&(r.timeOffset=f),-1!==o&&c<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=o,y.keyFrameStart=t+o*I),u){(!Ss(y.ptsMin)||t<y.ptsMin)&&(y.ptsMin=t);const e=t+u*I;(!Ss(y.ptsMax)||e>y.ptsMax)&&(y.ptsMax=e)}const v=I*n;P=t+v,D+=v;continue}i&&(b=[],T={sampleOffset:R,samples:b,defaultSampleDurationOffset:w},R<=l&&y.trun.push(T));for(let t=0;t<n;t++){let n,a,o;f?(i&&(n=s.byteOffset-e.byteOffset+S),M=_l(s,S),S+=4):M=I,g?(A=_l(s,S),S+=4):A=L,p&&(o=1&s[S+1]?1:0,i&&(a={isNonSync:o,dependsOn:1==(3&s[S])?1:2}),S+=4);let h=0;if(v&&(h=0===s[0]?_l(s,S):Fl(s,S),S+=4),E){let t=R,s=0;for(;s<A;){const i=_l(e,t);t+=4,sh(r.isHEVCFlavor,e[t])&&ih(e.subarray(t,t+i),r.isHEVCFlavor?2:1,r.timeOffset+h/r.timescale,r.samples),t+=i,s+=i+4}r.timeOffset+=M/r.timescale}if(R+=A,R<=l){T&&void 0!==n&&(T.lastSampleDurationOffset=n),0===o&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=t,y.keyFrameStart=P);const e=P+h;(!Ss(y.ptsMin)||e<y.ptsMin)&&(y.ptsMin=e),(!Ss(y.ptsMax)||e+M>y.ptsMax)&&(y.ptsMax=e+M),b&&(b[t]={cts:h,duration:M,flags:a,size:A})}P+=M,D+=M}!D&&I&&(D+=I*n)}y.duration+=D,y.duration&&(a=!0)}if(!a){let t=1/0,s=0;const i=Gl(e,["sidx"]);for(let e=0;e<i.length;e++){const r=Wl(i[e]);if(null!=r&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);const e=r.references.reduce((e,t)=>e+t.info.duration||0,0);s=Math.max(s,e+r.earliestPresentationTime/r.timescale)}}s&&Ss(s)&&Object.keys(n).forEach(e=>{n[e].duration||(n[e].duration=s*n[e].timescale-n[e].start)})}return n}function eh(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function th(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function sh(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6==(31&t)}function ih(e,t,s,i){const r=rh(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){Gs.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=Ml(r,t);if(t+=2,49===e){const e=_l(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=r[t++]}i.push({type:e,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const i=r[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];i.push({payloadType:a,pts:s,uuid:e.join(""),userData:Jl(l),userDataBytes:l})}}}function rh(e){const t=e.byteLength;let s,i=e.indexOf(3,3);for(;-1!==i;)0===e[i-1]&&0===e[i-2]&&(s||(s=[])).push(i),i=e.indexOf(3,i+1);if(!s)return e;const r=t-s.length,n=new Uint8Array(r);let a=0,o=0;for(let t=0;t<r;o++,t++)o===s[a]&&(o++,a++),n[t]=e[o];return n}function nh(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let i=0;for(;i+32<s;){const s=ah(new DataView(e,i));t.push(s),i+=s.size}}return t}function ah(e){const t=e.getUint32(0),s=e.byteOffset,i=e.byteLength;if(i<t)return{offset:s,size:i};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:s,size:t};const n=e.buffer,a=Rl(new Uint8Array(n,s+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=e.getUint32(28);if(!r||i<32+16*r)return{offset:s,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,s+32+16*e,16));h=32+16*r}if(!h)return{offset:s,size:t};const d=e.getUint32(h);return t-32<d?{offset:s,size:t}:(l=new Uint8Array(n,s+h+4,d),0===r&&(o=function(e){const t=[];for(let s=0;s<e.length;){const i=e[s++],r=7&i;if(0===r){for(;128&e[s++];);continue}if(2!==r){s+=1===r?8:4;continue}let n=0;for(let t=0,i=128;128&i;t+=7)n|=(127&(i=e[s++]))<<t;if(i>>3==2)if(32===n){const i=new Uint8Array(16);for(let t=0;t<16;t++)i[t]=parseInt(String.fromCharCode(e[s+2*t],e[s+2*t+1]),16);t.push(i)}else 16===n&&t.push(e.subarray(s,s+16));s+=n}return t}(l)),{version:r,systemId:a,kids:o,data:l,offset:s,size:t})}function oh(e){try{return navigator[e]||""}catch(e){}return""}function lh(){if(void 0===ei){const e=Js.match(/Chrome\/(\d+)/i);ei=e?parseInt(e[1]):0}return ei}function hh(){return/\(Windows.+Firefox\//i.test(Js)}function dh(e,t){const s=ii[t];return!!s&&!!s[e.slice(0,4)]}function ch(e,t,s=!0){return!e.split(",").some(e=>!uh(e,t,s))}function uh(e,t,s=!0){var i;const r=dl(s);return null!=(i=null==r?void 0:r.isTypeSupported(fh(e,t)))&&i}function fh(e,t){return`${t}/mp4;codecs=${e}`}function gh(e){if(e){const t=e.substring(0,4);return ii.video[t]}return 2}function mh(e){const t=hh();return e.split(",").reduce((e,s)=>{const i=t&&th(s)?9:ii.video[s];return i?(2*i+e)/(e?3:2):(ii.audio[s]+e)/(e?2:1)},0)}function ph(e,t=!0){return e.replace(ni,e=>function(e,t=!0){if(ri[e])return ri[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(uh(s[r],"audio",t))return ri[e]=s[r],s[r];if("mp3"===s[r]&&null!=(i=dl(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function vh(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(yh(e,"audio")||yh(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function yh(e,t){return dh(e,t)&&uh(e,t)}function Sh(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function Eh(e){const t=dl(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function bh(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function Th(e,t){return{supported:!1,configurations:t,decodingInfoResults:[ai],error:e}}function wh(e,t,s,i,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,s)=>{if(s){const i=t.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach(t=>{e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>th(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(r,8e6))||!!c&&Ss(d)&&Object.keys(c).some(e=>parseInt(e)>d)}function Ih(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(oi);const n=[],a=function(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),i=Ah(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map(e=>{const t={contentType:fh(Sh(e),"video"),width:r,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,s){var i;const r=null==(i=e.audioCodec)?void 0:i.split(","),n=Ah(e);return r&&e.audioGroups?e.audioGroups.reduce((e,i)=>{var a;const o=i?null==(a=t.groups[i])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===i){const i=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:fh(t,"audio"),bitrate:s?Lh(t,n):n};i&&(r.channels=""+i),e.push(r)})}return e},e):e},[]):[]}(e,t,o>0),h=l.length;for(let e=o||1*h||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),h){t.audio=l[e%h];const s=t.audio.bitrate;t.video&&s&&(t.video.bitrate-=s)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>th(e))&&hh())return Promise.resolve(Th(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:s,video:i}=e;return i&&(t+=`${bh(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`),s&&(t+=`${i?"_":""}${bh(s.contentType)}_c${s.channels}`),t}(e);return i[t]||(i[t]=s.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function Lh(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function Ah(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function kh(e,t,s){const i=encodeURIComponent(t),r=`${i}=${encodeURIComponent(s)}`;let n=!1;const a=[];e.search.substring(1).split("&").forEach(e=>{e===i||e.startsWith(i+"=")?n||(a.push(r),n=!0):e&&a.push(e)}),n||a.push(r),e.search=a.join("&")}function Rh(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e;return t&&i<t/2?s?di.v2:di.Yes:di.No}function Ch(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Ph(e,t){Gs.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Dh(e){return e.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Mh(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function _h(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let i=0;i<t.length;i++)if(Oh(e,t[i],s))return i;return-1}function Oh(e,t,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const s=e.split(","),i=t.split(",");return s.length===i.length&&!s.some(e=>-1===i.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===s||s(e,t))}function xh(e,t){const{audioCodec:s,channels:i}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Fh(e,t,s){for(let i=t;i>-1;i--)if(s(e[i]))return i;for(let i=t+1;i<e.length;i++)if(s(e[i]))return i;return-1}function Bh(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}function Uh(e,t){return!t||-1!==t.indexOf(e)}function Nh(e,t){if(t||e){const s=zo({},t);return e&&(e.videoCodec&&(s.videoCodec=e.videoCodec),e.videoRange&&(s.allowedVideoRanges=[e.videoRange])),s}}function $h(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const i=e.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Gh(s,i,n)||function(e,t,s){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),s);return e.start<=i}return!1}(n,e,Math.min(r,i))))return n;const a=pi.search(t,Gh.bind(null,s,i));return!a||a===e&&n?n:a}function Gh(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function Hh(e,t,s){const i=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>e}function Wh(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;let n;return r&&(i=i.concat(r)),pi.search(i,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0)),n||null}return null}function qh(e,t,s){return s&&t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}function jh(e){const t=e.details;return t===ws.BUFFER_ADD_CODEC_ERROR||t===ws.MEDIA_SOURCE_REQUIRES_RESET||t===ws.BUFFER_APPEND_ERROR&&!Kh(e)}function Kh(e){return e.details===ws.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function Vh(e){const t={action:vi.DoNothing,flags:yi.None};return e&&(t.resolved=!0),t}function Yh(e){var t,s,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(r=e.range.subs)&&r.partial)}function zh(e){return`${e.type}_${e.level}_${e.sn}`}function Qh(e,t){return e.filter(e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s})}function Xh(e,t=null,s){const i=t||e,r={type:Cs.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=Jh(e,t,s);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function Jh(e,t=null,s){const i={},r=t||e,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;var o,l;if(Ss(n)&&Ss(a))if("initSegment"!==e.sn&&!s||"AES-128"!==(l=null==(o=e.decryptdata)?void 0:o.method)&&"AES-256"!==l)i.byteRange={start:n,end:a};else{let e=16*Math.floor(n/16);const t=16*Math.ceil(a/16);i.decryptRange={start:n-e,end:a-e},e>=16&&(i.resetIV=!0,e-=16),i.byteRange={start:e,end:t}}return i}function Zh(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:Ts.MEDIA_ERROR,details:ws.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Ci(i)}function ed(e){return Oi.test(e)}function td(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(Oi,t=>{const i=t.substring(2,t.length-1),r=null==s?void 0:s[i];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),t):r})}return t}function sd(e,t,s){let i,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=e.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else i=t.NAME,r=t.VALUE;i in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function id(e,t,s){const i=t.IMPORT;if(s&&i in s){let t=e.variableList;t||(e.variableList=t={}),t[i]=s[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function rd(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function nd(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}function ad(e,t){return e.length===t.length&&!e.some((e,s)=>e!==t[s])}function od(e,t){return!e&&!t||!(!e||!t)&&ad(e,t)}function ld(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function hd(e){switch(e){case"AES-128":case"AES-256":return Ti.cbc;case"AES-256-CTR":return Ti.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function dd(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function cd(e){const t=function(e,t,s){const i=e[t];e[t]=e[s],e[s]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ud(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),i=e[e.length-1].split(",");if(2===i.length){const t="base64"===i[0],r=i[1];t?(e.splice(-1,1),s=Pl(r)):s=function(e){const t=dd(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}(r)}}return s}function fd(e){switch(e){case Hi.FAIRPLAY:return Gi.FAIRPLAY;case Hi.PLAYREADY:return Gi.PLAYREADY;case Hi.WIDEVINE:return Gi.WIDEVINE;case Hi.CLEARKEY:return Gi.CLEARKEY}}function gd(e){switch(e){case Gi.FAIRPLAY:return Hi.FAIRPLAY;case Gi.PLAYREADY:return Hi.PLAYREADY;case Gi.WIDEVINE:return Hi.WIDEVINE;case Gi.CLEARKEY:return Hi.CLEARKEY}}function md(e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?[Gi.FAIRPLAY,Gi.WIDEVINE,Gi.PLAYREADY,Gi.CLEARKEY].filter(e=>!!t[e]):[];return!i[Gi.WIDEVINE]&&s&&i.push(Gi.WIDEVINE),i}function pd(e){const t=Dl(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),s=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=Pl(e).subarray(0,16);return cd(t),t}}return null}function vd(e){const t=null==e?void 0:e[Hi.PLAYREADY];if(t){const e=ud(t.uri);if(e)return pd(e)}return null}function yd(e,t,s,i,r,n){var a;if(void 0===t)return null;const o=td(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Ji.resolve(o,s)},h=e.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),wd(e.CODECS,l);const d=e["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},wd(d,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function Sd(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const i=t.fragments[t.fragments.length-1];e.push(i),s++}}const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=s;i--;){var a;if((null==(a=e[i])?void 0:a.sn)<t.startSN)break;const s=Ed(t,h,e,i,r);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function Ed(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;var a;if(t>=o||0===i)if(t<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>s.length)for(let a=(s[i+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}return r}}return-1}function bd(e,t,s){var i,r;const n=new Bi(e,s),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&Gs.error(`Invalid IV: ${n.IV}`);const c=o?Ji.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ki(a,c,d,u,l,n.KEYID)}function Td(e){const t=new Bi(e).decimalFloatingPoint("TIME-OFFSET");return Ss(t)?t:null}function wd(e,t){let s=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text","image"].forEach(e=>{const i=s.filter(t=>dh(t,e));i.length&&(t[`${e}Codec`]=i.map(e=>e.split("/")[0]).join(","),s=s.filter(e=>-1===i.indexOf(e)))}),t.unknownCodecs=s}function Id(e,t,s){const i=t[s];i&&(e[s]=i)}function Ld(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Ad(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function kd(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||i.push(e)}function Rd(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function Cd(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function Pd(e,t){const s=t.startPTS;if(Ss(s)){let i,r=0;t.sn>e.sn?(r=s-e.start,i=e):(r=e.start-s,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Dd(e,t,s,i,r,n,a,o){i-s<=0&&(o.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let l=s,h=i;const d=t.startPTS,c=t.endPTS;if(Ss(d)){const a=Math.abs(d-s);e&&a>e.totalduration?o.warn(`media timestamps and playlist times differ by ${a}s for level ${t.level} ${e.url}`):Ss(t.deltaPTS)?t.deltaPTS=Math.max(a,t.deltaPTS):t.deltaPTS=a,l=Math.max(s,d),s=Math.min(s,d),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,h=Math.min(i,c),i=Math.max(i,c),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const u=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=l,t.startDTS=r,t.endPTS=i,t.minEndPTS=h,t.endDTS=n;const f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let g;const m=f-e.startSN,p=e.fragments;for(p[m]=t,g=m;g>0;g--)Pd(p[g],p[g-1]);for(g=m;g<p.length-1;g++)Pd(p[g],p[g+1]);return e.fragmentHint&&Pd(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function Md(e,t,s,i,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function _d(e,t,s=!0,i){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==i||i.log(`Aligning playlists based on SN ${t.startSN} (diff: ${o})`);else if(a&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==i||i.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${o})`);else if(a&&s)o=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==i||i.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${o})`)}return function(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function Od(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments,r=4;if(i.length&&s*r>t){const e=1e3*i[i.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function xd(e,t,s){var i;if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,(null==(i=r)?void 0:i.sn)===t?r:s&&t<e.startSN&&s.sn===t?s:null)}function Fd(e,t,s){return e?Bd(e.partList,t,s):null}function Bd(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Ud(e){e.forEach((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Nd(e,t){return!(e===t||!t)&&$d(e)!==$d(t)}function $d(e){return e.replace(/\?[^?]*$/,"")}function Gd(e,t){for(let i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function Hd(e,t){const s=e.start+t;e.setStart(s)}function Wd(e,t){const s=t.fragments;for(let t=0,i=s.length;t<i;t++)Hd(s[t],e);t.fragmentHint&&Hd(t.fragmentHint,e),t.alignedSliding=!0}function qd(e,t,s){e&&(function(e,t,s){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),r=Gd(t.fragments,i),n=Gd(e.fragments,i);if(!r||!n)return;const a=r.start-n.start;s.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Wd(a,e)}(t,e,s),t.alignedSliding||function(e,t,s){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,r=t.fragments;if(!i.length||!r.length)return;let n,a;const o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(n=Gd(r,o),a=Gd(i,o)),n&&a||(n=r[Math.floor(r.length/2)]||r.filter(e=>!!e)[0],a=Gd(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,h=a.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,e.totalduration))return void s.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${e.totalduration})`);const c=d-(a.start-n.start);s.log(`Aligning playlists using PDT (diff: ${c})`),Wd(c,e)}(t,e,s),t.alignedSliding||t.skippedSegments||_d(e,t,!1,s))}function jd(e,t,s){Kd(e,t,s),e.addEventListener(t,s)}function Kd(e,t,s){e.removeEventListener(t,s)}function Vd(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t}function Yd(e,t,s){if(t)for(let i=t.length;i--;){const r=t[i].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(e.start>=n&&e.end<=a)return!0;if(s>e.start&&e.end>n&&e.start<a)return!0}}return!1}function zd(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}function Qd(e,t){return 255===e[t]&&240==(246&e[t+1])}function Xd(e,t){return 1&e[t+1]?7:9}function Jd(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Zd(e,t){return t+1<e.length&&Qd(e,t)}function ec(e,t){if(Zd(e,t)){const s=Xd(e,t);if(t+s>=e.length)return!1;const i=Jd(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||Zd(e,r)}return!1}function tc(e,t,s,i,r){if(!e.samplerate){const n=function(e,t,s,i){const r=t[s+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[s+3]>>6&3|(1&r)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h,d=n;5!==a&&29!==a||(d-=3);const c=(14&d)>>1,u=(1&d)<<7|o<<3;let f=0;if(1===a&&n>=6){f=5;const e=n-3;h=[f<<3|c,u|(14&e)>>1,(1&e)<<7|8,0]}else h=[a<<3|c,u];const g="mp4a.40."+(f||a);return Gs.log(`manifest codec:${i}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${n} esds config:[${h.join(",")}])`),{config:h,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:i}}(t,s,i,r);if(!n)return;zo(e,n)}}function sc(e){return 9216e4/e}function ic(e,t,s,i,r){const n=i+r*sc(e.samplerate),a=function(e,t){const s=Xd(e,t);if(t+s<=e.length){const i=Jd(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}(t,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-t.length);h?(o=new Uint8Array(l-r),o.set(t.subarray(s+r,t.length),0)):o=t.subarray(s+r,s+l);const d={unit:o,pts:n};return h||e.samples.push(d),{sample:d,length:l,missing:h}}const l=t.length-s;return o=new Uint8Array(l),o.set(t.subarray(s,t.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function rc(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}function nc(e,t,s,i,r){if(s+24>t.length)return;const n=ac(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function ac(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*dr[14*(3===s?3-i:3===i?3:4)+r-1],h=cr[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=ur[s][i],u=fr[i],f=8*c*u,g=Math.floor(c*l/h+a)*u,m=lh();return!!m&&m<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function oc(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function lc(e,t){return t+1<e.length&&oc(e,t)}function hc(e,t){if(t+1<e.length&&oc(e,t)){const s=4,i=ac(e,t);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||lc(e,n)}return!1}function dc(e,t,s,i,r){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const h=t[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(t[s+6]<<8|t[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}function cc(e,t){return Ss(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}function uc(e,t){return((31&e[t+1])<<8)+e[t+2]}function fc(e,t){return(31&e[t+10])<<8|e[t+11]}function gc(e,t,s,i,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<h;){const h=uc(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){pc("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=h);break;case 21:-1===l.id3Pid&&(l.id3Pid=h);break;case 219:if(!i){pc("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=h);break;case 3:case 4:s.mpeg||s.mp3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){pc("AC-3",n);break}case 129:s.ac3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0){let i=t+5,r=d;for(;r>2;){switch(e[i]){case 106:-1===l.audioPid&&(!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=h,n.log(`KLV metadata PID found: ${h}`))}const t=e[i+1]+2;i+=t,r-=t}}break;case 194:case 135:return mc(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=h,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=d+5}return l}function mc(e,t,s,i,r){r.warn(`parsing error: ${t.message}`),e.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:s,error:t,reason:t.message})}function pc(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function vc(e,t){let s,i,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=eh(l[0],l[1]),l.splice(1,1);if(s=l[0],1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(d){if(d>t){d-=t;continue}s=s.subarray(d),t-=d,d=0}c.set(s,o),o+=t}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}function yc(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}function Sc(e,t=!1){return yc(e,1e3,1/$r,t)}function Ec(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}function bc(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}function Tc(e,t){let s;if(null===t)return e;for(s=t<e?-Gr:Gr;Math.abs(e-t)>4294967296;)e+=s;return e}function wc(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=Tc(r.pts-s.baseTime*n/s.timescale,t*n)/n,r.dts=Tc(r.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function Ic(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let n=0;n<i;n++){const i=e.samples[n];i.pts=Tc(i.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function Lc(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function Ac(e,t,s){const i=e.codec;return i&&i.length>4?i:t===Ds.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?ph(i,!1):(s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):"mjpg"===i?i:(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}function kc(e){return"then"in e&&e.then instanceof Function}function Rc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!Cc(e[s].attrs,t[s].attrs))return!1;return!0}function Cc(e,t,s){const i=e["STABLE-RENDITION-ID"];return i&&!s?i===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>e[s]!==t[s])}function Pc(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Dc(e){return"audio"===e?1:0}function Mc(e,t){return`${e?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function _c(e){return`${e.type}_${e.sn}_${e.level}`}function Oc(e,t){const{start:s,end:i}=t;let r=0;for(let t=0;t<e.length;t++){const n=e[t];if(n.start>=i)break;const a=Math.max(s,n.start),o=Math.min(i,n.end);o>a&&(r+=o-a)}return r}function xc(e,t){return t.duration-e<=nn}function Fc(e,t,s){return function(e,t,s,i){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}("serialize",e,t,s)}function Bc(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Fc(e,mn);return e.toString()}function Uc(e){const t=fl(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Fc(e,gn);const s=t.toString();return s.includes(".")?s:`${s}.0`}function Nc(e){const t=(s=e).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Fc(t,Sn);return t}function $c(e){switch(typeof e){case"number":if(!Ss(e))throw Fc(e,cn);return Number.isInteger(e)?Bc(e):Uc(e);case"string":return function(e){if(vn.test(e))throw Fc(e,pn);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Nc(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fc(e,un);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Bc(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw Fc(e,fn);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}(e);if(e instanceof yn)return Nc(e);default:throw Fc(e,cn)}}function Gc(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fc(e,En);return e}function Hc(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${Gc(e)}`:`;${Gc(e)}=${$c(t)}`).join("")}function Wc(e){return e instanceof hn?`${$c(e.value)}${Hc(e.params)}`:$c(e)}function qc(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Fc(e,dn);const s=e instanceof Map?e.entries():Object.entries(e),i=null!=t&&t.whitespace?" ":"";return Array.from(s).map(([e,t])=>{t instanceof hn==0&&(t=new hn(t));let s=Gc(e);var i;return!0===t.value?s+=Hc(t.params):(s+="=",Array.isArray(t.value)?s+=`(${(i=t).value.map(Wc).join(" ")})${Hc(i.params)}`:s+=Wc(t)),s}).join(`,${i}`)}(e,t)}function jc(e){return Gn.test(e)}function Kc(e){return Hn.has(e)||jc(e)}function Vc(e){return qn.has(e)}function Yc(e){return Kc(e)||Vc(e)||jn.has(e)}function zc(e){return Yn.has(e)||jc(e)}function Qc(e){return zn.has(e)}function Xc(e){return"number"==typeof e?Ss(e):null!=e&&""!==e&&!1!==e}function Jc(e,t){if(Array.isArray(e)){let s;return t&&(s=e.find(e=>{var s;return(null==(s=e.params)?void 0:s.ot)===t})),s||(s=e[0]),Jc(s)}return e instanceof hn?e.value:e}function Zc(e,t={}){const s={};if(null==e||"object"!=typeof e)return s;const i=t.version||e.v||Pn,r=t.reportingMode||Un,n=1===i?function(e){const t={};for(const[i,r]of Object.entries(e))if(null!=r)if("nor"===i){const e=(Array.isArray(r)?r:[r])[0];var s;e instanceof hn?(t.nor=e.value,null!=(s=e.params)&&s.r&&(t.nrr=e.params.r)):t.nor=e}else Kn.has(i)?t[i]=Jc(r,e.ot):t[i]=r;else t[i]=r;return t}(e):e,a=1===i?zc:Qn[r];let o=Object.keys(n).filter(a);n.e&&n.e!==_n&&(o=o.filter(e=>!Vc(e)));const l=t.filter;"function"==typeof l&&(o=o.filter(l));const h=r===Bn;if(h){const e=n.e;o.includes("e")||null==e||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==n.cen||e!==On||o.push("cen");const t=e?Fn.get(e):void 0;t&&null!=n[t]&&!o.includes(t)&&o.push(t)}if(0===o.length)return s;i>1&&!o.includes("v")&&o.push("v");const d={version:i,reportingMode:r,baseUrl:t.baseUrl};o.sort();for(const e of o){var c,u;let r=n[e];const a=null!=(c=null==(u=t.formatters)?void 0:u[e])?c:Cn[e];if("function"==typeof a&&(r=a(r,d)),"v"===e){if(1===i)continue;r=i}if("pr"===e&&1===r&&(!h||n.e!==Dn))continue;h&&"ts"===e&&!Ss(r)&&(r=Date.now());const o=h&&!1===r&&"bg"===e&&n.e===Mn;(Xc(r)||o)&&(Qc(e)&&"string"==typeof r&&(r=new yn(r)),s[e]=r)}return s}function eu(e){return qc(e,{whitespace:!1})}function tu(e,t,s){var i;const r=new Set(null!=(i=t.enabledKeys)?i:[]);return{version:t.version||Pn,reportingMode:e,filter:e=>r.has(e),baseUrl:s}}function su(e){const{url:t}=e,s=Jo(e,bn);return fetch(t,s)}function iu(e){return Object.keys(e).every(jc)}function ru(e,t,s,i){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=zo({},e);return n.details=void 0,n.attrs=new Bi(n.attrs),n.url=n.attrs.URI=nu(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=i,n});e.push(...n)})}function nu(e,t,s,i){if(t){const{[s]:e}=i;if(e){const s=e[t];if(s)return s}}const{HOST:r,PARAMS:n}=i,a=new self.URL(e);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(e=>{e&&kh(a,e,n[e])}),a.href}function au(e,t){const s=e.keyId,i=t.mediaKeysSession;if(s&&i){const e=t.mediaKeysSession.keyStatuses;if(e.size)return e.has(s)?e.get(s):t.keyStatuses[Rl(s)]}}function ou(e,t){const s="output-restricted"===e,i=s?ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Sa({type:Ts.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}function lu(e){return new Promise((t,s)=>e.resolved?t():e.errored?s(e.errored):(e.on("error",s),void e.on("resolved",t)))}function hu(e){function t(e,t,s,i){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(i||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}function du(e,t,s,i){const r=i?e.split(i):[e];for(const e in r){if("string"!=typeof r[e])continue;const i=r[e].split(s);2===i.length&&t(i[0],i[1])}}function cu(e,t,s){const i=e;function r(){const t=hu(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const i=new Ia;du(e,function(e,t){let r;switch(e){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===t){i.set(e,s[r].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),i.integer(e,r[0]),i.percent(e,r[0])&&i.set("snapToLines",!1),i.alt(e,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Aa,"end"]);break;case"position":r=t.split(","),i.percent(e,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Aa,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",Aa,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===La.line&&(r=-1),t.line=r,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",Aa);let n=i.get("position","auto");"auto"===n&&50===La.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function uu(e){return e.replace(/<br(?: \/)?>/gi,"\n")}function fu(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}function gu(e,t,s){return fu(e.toString())+fu(t.toString())+fu(s)}function mu(e,t,s,i){const r=Gl(new Uint8Array(e),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>bl(e)),a=function(e,t,s=1,i=!1){return yc(e,t,1/s,i)}(t.baseTime,1,t.timescale);try{n.forEach(e=>s(function(e,t){const s=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(i).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||i[t],e),{}),n="preserve"!==s.getAttribute("xml:space"),a=vu(pu(s,"styling","style")),o=vu(pu(s,"layout","region")),l=pu(s,"body","[begin]");return[].map.call(l,e=>{const s=yu(e,n);if(!s||!e.hasAttribute("begin"))return null;const i=bu(e.getAttribute("begin"),r),l=bu(e.getAttribute("dur"),r);let h=bu(e.getAttribute("end"),r);if(null===i)throw Eu(e);if(null===h){if(null===l)throw Eu(e);h=i+l}const d=new Ta(i-t,h-t,s);d.id=gu(d.startTime,d.endTime,d.text);const c=function(e,t,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&s.hasOwnProperty(n)&&(r=s[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((s,n)=>{const a=Su(t,i,n)||Su(e,i,n)||Su(r,i,n);return a&&(s[n]=a),s},{})}(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:u}=c;if(u){const e=Oa[u];e&&(d.lineAlign=e),d.align=u}return zo(d,c),d}).filter(e=>null!==e)}(e,a)))}catch(e){i(e)}}function pu(e,t,s){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function vu(e){return e.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function yu(e,t){return[].slice.call(e.childNodes).reduce((e,s,i)=>{var r;return"br"===s.nodeName&&i?e+"\n":null!=(r=s.childNodes)&&r.length?yu(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent},"")}function Su(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function Eu(e){return new Error(`Could not parse ttml timestamp ${e}`)}function bu(e,t){if(!e)return null;let s=hu(e);return null===s&&(Ma.test(e)?s=function(e,t){const s=Ma.exec(e),i=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/t.frameRate}(e,t):_a.test(e)&&(s=function(e,t){const s=_a.exec(e),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),s}function Tu(e,t,s,i="",r="disabled"){const n=e.ownerDocument.createElement("track");return n.kind=t,n.label=s,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=r,e.appendChild(n),n}function wu(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){Gs.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(e){Gs.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===s&&(e.mode=s)}function Iu(e,t,s,i){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,s){const i=[],r=function(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),t<e[i].startTime)n=i-1;else{if(!(t>e[i].startTime&&r<s))return i;r=i+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(e.cues,t,s);for(let t=0;t<r.length;t++)i&&!i(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function Lu(e,t){const s=Au(e.main);if(s&&s.start<=t)return s;const i=Au(e.audio);return i&&i.start<=t?i:null}function Au(e){if(!e)return null;switch(e.state){case Zi.IDLE:case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:return null}return e.frag}function ku(e,t){return t.getAppendedFrag(e,Ps.MAIN)||t.getPartialFragment(e)}function Ru(e,t,s,i){const r=i.latestLevelDetails,n=ku(t,s);if(zd(i.config)&&!e.nextStart&&r&&n&&i.interstitialsManager){const s="type"in n?n:n.fragment,a=qh(r,s.sn,!0);(null==a?void 0:a.level)===s.level&&Yd(a,i.interstitialsManager.playerQueue,t)&&(e.nextStart=a.start)}}function Cu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Pu(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new e(t,s,gi(r?Xo({type:r},i):i))}return n}function Du(){return self.SourceBuffer||self.WebKitSourceBuffer}function Mu(){if(!dl())return!1;const e=Du();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function _u(){if(!Mu())return!1;const e=dl();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(fh(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(fh(t,"audio"))))}function Ou(e,t,s){return`${e.identifier}-${s+1}-${fu(t)}`}function xu(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Va)?t.start:t.start+t.duration}function Fu(e,t,s){const i=new self.URL(e,s);return"data:"!==i.protocol&&kh(i,"_HLS_primary_id",t),i}function Bu(e,t){for(;null!=(s=e.assetList[++t])&&s.error;)var s;return t}function Uu(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}function Nu(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}function $u(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function Gu(e,t){return`[${e}] Advancing timeline position to ${t}`}function Hu(e,t,s){s.a=e,s.b=t}function Wu(e,t,s){return s.a===e&&s.b===t}function qu(e,t,s,i){return Math.min(t,i)-Math.max(e,s)}function ju(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}function Ku(e,t){return new self.Request(e.url,t)}function Vu(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Vu):Object.keys(e).reduce((t,s)=>(t[s]=Vu(e[s]),t),{}):e}function Yu(e,t){return ch(e,"audio",t)}function zu(e,t){return ch(e,"video",t)}function Qu(e,t){let{audioCodec:s,videoCodec:i}=e;s&&(e.audioCodec=s=ph(s,t)||void 0),i&&(i=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&"avc1"===s[0]&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}(i));const{unknownCodecs:r}=e;return!((null==r?void 0:r.length)||s&&!Yu(s,t)||i&&!zu(i,t))}function Xu(e){const t={};e.forEach(e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++})}function Ju(e,t=ws.KEY_LOAD_ERROR,s,i,r){return new Ci({type:Ts.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i||null})}function Zu(e){const{type:t}=e;switch(t){case Cs.AUDIO_TRACK:return Ps.AUDIO;case Cs.SUBTITLE_TRACK:return Ps.SUBTITLE;default:return Ps.MAIN}}function ef(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}h(Go,{AbrController:()=>mi,AttrList:()=>Bi,AudioStreamController:()=>Jr,AudioTrackController:()=>en,BaseLoader:()=>ko,BasePlaylistController:()=>Zr,BaseSegment:()=>Ms,BaseStreamController:()=>er,BufferController:()=>on,CMCDController:()=>va,CapLevelController:()=>ln,ChunkMetadata:()=>Di,ContentSteeringController:()=>ya,Cues:()=>Ao,DateRange:()=>Ui,EMEController:()=>Ea,ErrorActionFlags:()=>yi,ErrorController:()=>Si,ErrorDetails:()=>ws,ErrorTypes:()=>Ts,Events:()=>Is,FPSController:()=>ba,FetchLoader:()=>Co,Fragment:()=>_s,Hls:()=>No,HlsSkip:()=>di,HlsUrlParameters:()=>ci,KeySystemFormats:()=>Hi,KeySystems:()=>Gi,Level:()=>ui,LevelDetails:()=>Ni,LevelKey:()=>Ki,LoadStats:()=>Rs,LoaderContextType:()=>Cs,M3U8Parser:()=>Ji,MetadataSchema:()=>or,NetworkErrorAction:()=>vi,Part:()=>Os,PlaylistLevelType:()=>Ps,SubtitleStreamController:()=>so,SubtitleTrackController:()=>xa,TimelineController:()=>Io,XhrLoader:()=>_o,default:()=>No,fetchSupported:()=>ju,getMediaSource:()=>dl,isMSESupported:()=>Mu,isSupported:()=>_u,requestMediaKeySystemAccess:()=>qi});var tf=o({"../../node_modules/hls.js/dist/hls.mjs"(){var e,t,s,i,r,n;Ss=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Es=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=bs},bs=Number.MAX_SAFE_INTEGER||9007199254740991,Ts=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ws=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),Is=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),Ls={exports:{}},As||(As=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,t=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,r={buildAbsoluteURL:function(e,s,i){if(i=i||{},e=e.trim(),!(s=s.trim())){if(!i.alwaysNormalize)return e;var n=r.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=r.normalizePath(n.path),r.buildURLFromParts(n)}var a=r.parseURL(s);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=r.normalizePath(a.path),r.buildURLFromParts(a)):s;var o=r.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=t.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=r.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?r.normalizePath(a.path):a.path),r.buildURLFromParts(h)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},Ls.exports=r),ks=Ls.exports,Rs=class{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}}},Cs={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},Ps={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Ds={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Ms=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,Vo(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Ds.AUDIO]:null,[Ds.VIDEO]:null,[Ds.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Rs),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=ks.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Ds.AUDIO]=null,e[Ds.VIDEO]=null,e[Ds.AUDIOVIDEO]=null,this.url=null}},_s=class extends Ms{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Ss(e)&&Ss(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=Ss(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){Ss(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Wo(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];!i||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n}}},Os=class extends Ms{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===Ps.SUBTITLE&&this.stats.loaded)}},xs=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Fs=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new xs(e),this.fast_=new xs(t),this.defaultTTFB_=i,this.ttfb_=new xs(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new xs(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new xs(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new xs(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;const s=Math.min(this.minDelayMs_,t/1e5),i=8*t,r=Math.max(e,s)/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Bs=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Us,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},Ns={trace:Us=function(){},debug:Us,log:Us,warn:Us,info:Us,error:Us},$s=ll(),Gs=$s,Hs="utf-16",Ws="utf-16be",qs="utf-16le",js="utf-8",Ks=10,Vs=10,Ys=Math.pow(2,32)-1,zs={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Qs={video:1,audio:2,id3:3,text:4},Js=oh("userAgent"),Zs=oh("vendor"),ii={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}},ri={},ni=/flac|opus|mp4a\.40\.34/i,ai={supported:!1,smooth:!1,powerEfficient:!1},oi={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},li=["NONE","TYPE-0","TYPE-1",null],hi=["SDR","PQ","HLG"],di={No:"",Yes:"YES",v2:"v2"},ci=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&kh(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&kh(t,"_HLS_part",this.part.toString()),this.skip&&kh(t,"_HLS_skip",this.skip),t.href}},ui=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Ch(this._audioGroups,e)}hasSubtitleGroup(e){return Ch(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}},fi=e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}},gi=(e,t)=>JSON.stringify(e,fi(t)),mi=class extends Bs{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:i,hls:r}=this;if(!r)return;const{autoLevelEnabled:n,media:a}=r;if(!s||!a)return;const o=performance.now(),l=i?i.stats:s.stats,h=i?i.duration:s.duration,d=o-l.loading.start,c=r.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!e||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=r.mainForwardBufferInfo;if(!m&&null===p)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(d<=Math.max(v,h/(2*y)*1e3))return;const S=p?p.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,b=l.loaded&&E>-1,T=this.getBwEstimate(),w=r.levels,I=w[u],L=Math.max(l.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8));let A=b?d-E:d;A<1&&b&&(A=Math.min(d,8*l.loaded/T));const k=b?1e3*l.loaded/A:0,R=v/1e3,C=k?(L-l.loaded)/k:8*L/T+R;if(C<=S)return;const P=k?8*k:T,D=!0===(null==(t=(null==e?void 0:e.details)||r.latestLevelDetails)?void 0:t.live),M=r.config.abrBandWidthUpFactor;let _,O=Number.POSITIVE_INFINITY;for(_=u-1;_>c;_--){const e=w[_].maxBitrate,t=!w[_].details||D;if(O=this.getTimeToLoadFrag(R,P,h*e,t),O<Math.min(S,h+R))break}if(O>=C)return;if(O>10*h)return;b?this.bwEstimator.sample(d-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(d);const x=w[_].maxBitrate;this.getBwEstimate()*M>x&&(this.firstAutoFloor=Math.min(_,r.firstLevel),this.resetEstimator(x));const F=this.findBestLevel(x,c,_,0,S,1,1);F>-1&&(_=F),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${O.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${Ss(T)?0|T:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|x} bps`),r.nextLoadLevel=r.nextAutoLevel=_,this.clearTimer();const B=()=>{this.clearTimer();const e=this.hls;if(this.fragCurrent===s&&e.loadLevel===_&&_>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${_>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,_>c){let s=this.findBestLevel(e.levels[c].bitrate,c,_,0,t,1,1);-1===s&&(s=c),e.nextLoadLevel=e.nextAutoLevel=s,this.firstAutoFloor=Math.min(s,e.firstLevel),this.resetEstimator(e.levels[s].bitrate)}}};g||C>2*O?B():this.timer=self.setInterval(B,1e3*O),r.trigger(Is.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new Fs(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Is.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;var i;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ws.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:i}=this;if(e&&jo(e,s)){const t=performance.now(),s=i?i.stats:e.stats,r=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;Ss(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;const{frag:i,part:r}=t,n=r?r.stats:i.stats;if(i.type===Ps.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(s=this.hls)&&s.config.abrMaxWithRealBitrate){const e=r?r.duration:i.duration,t=this.hls.levels[i.level],s=(t.loaded?t.loaded.bytes:0)+n.loaded,a=(t.loaded?t.loaded.duration:0)+e;t.loaded={bytes:s,duration:a},t.realBitrate=Math.round(8*s/a)}if(i.bitrateTest){const e={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(Is.FRAG_BUFFERED,e),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==Ps.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:t,minAutoLevel:s}=e,i=this.getBwEstimate(),r=this.getStarvationDelay(),n=e.config.maxStarvationDelay,a=this.findBestLevel(i,s,t,r/2,n,1,1);if(a>-1)return a;const o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,h=Math.min(Math.max(o,s),t,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;e&&(c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1)}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,i,r,n,a){const{hls:o,lastLoadedFragLevel:l,fragCurrent:h,partCurrent:d}=this;if(!o)return-1;const c=i+r,u=-1===l?o.firstLevel:l,{levels:f,allAudioTracks:g,loadLevel:m,latestLevelDetails:p,config:v}=o;if(1===f.length)return 0;const y=f[u],S=!(null==p||!p.live),E=-1===m||-1===l;let b,T="SDR",w=(null==y?void 0:y.frameRate)||0;const{audioPreference:I,videoPreference:L}=v,A=this.audioTracksByGroup||(this.audioTracksByGroup=Dh(g));let k=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(e,t,s,i){return e.slice(s,i+1).reduce((e,s,i)=>{if(!s.codecSet)return e;const r=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]}))}),e},{})}(f,A,t,s)),r=function(e,t,s,i,r){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let d=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[];const{preferHDR:y,allowedVideoRanges:S}=function(e,t){let s=!1,i=[];if(e&&(s="SDR"!==e,i=[e]),t){i=t.allowedVideoRanges||hi.slice(0);const e="SDR"!==i.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}(t,r);for(let t=n.length;t--;){const s=e[n[t]];d||(d=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate),S.filter(e=>s.videoRanges[e]>0).length>0&&(c=!0)}u=Ss(u)?u:0,f=Ss(f)?f:0;const E=Math.max(1080,u),b=Math.max(30,f);g=Ss(g)?g:s,s=Math.max(g,s),c||(t=void 0);const T=n.length>1;return{codecSet:n.reduce((t,i)=>{const r=e[i];if(i===t)return t;if(v=c?S.filter(e=>r.videoRanges[e]>0):[],T){if(r.minBitrate>s)return Ph(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),t;if(!r.hasDefaultAudio)return Ph(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Ph(i,`audio codec preference "${o}" not found`),t;if(a&&!h){if(!r.channels[a])return Ph(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||h)&&d&&0===r.channels[2])return Ph(i,"no renditions with stereo sound found"),t;if(r.minHeight>E)return Ph(i,`min resolution of ${r.minHeight} > maximum of ${E}`),t;if(r.minFramerate>b)return Ph(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),t;if(!v.some(e=>r.videoRanges[e]>0))return Ph(i,`no variants with VIDEO-RANGE of ${gi(v)} found`),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Ph(i,`video codec preference "${l}" not found`),t;if(r.maxScore<p)return Ph(i,`max score of ${r.maxScore} < selected max of ${p}`),t}return t&&(mh(i)>=mh(t)||r.fragmentError>e[t].fragmentError)?t:(m=r.minIndex,p=r.maxScore,i)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}(i,T,e,I,L),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:d}=r;k=h,b=n,T=d?a[a.length-1]:a[0],w=o,e=Math.max(e,l),this.log(`picked start tier ${gi(r)}`)}else b=null==y?void 0:y.codecSet,T=null==y?void 0:y.videoRange;const R=d?d.duration:h?h.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=t;o--){var D;const t=f[o],h=o>u;if(!t)continue;if(v.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&wh(t,A,T,w,e,I)?(t.supportedPromise=Ih(t,A,s,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,i=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${gi(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${gi(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${gi(e)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=oi}if((b&&t.codecSet!==b||T&&t.videoRange!==T||h&&w>t.frameRate||!h&&w>0&&w<t.frameRate||null!=(D=t.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(e=>!1===e.smooth))&&(!E||o!==k)){P.push(o);continue}const g=t.details,p=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||R||1;let y;y=h?a*e:n*e;const L=R&&i>=2*R&&0===r?t.averageBitrate:t.maxBitrate,M=this.getTimeToLoadFrag(C,y,L*p,!g||g.live);if(y>=L&&(o===l||0===t.loadError&&0===t.fragmentError||ol(t,v.errorPenaltyExpireMs))&&(M<=C||!Ss(M)||S&&!this.bitrateTestDelay||M<c)){const e=this.forcedAutoLevel;return o===m||-1!==e&&e===m||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${b}" ${T}`),this.info(`switch candidate:${u}->${o} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-L)} ttfb:${C.toFixed(1)} avgDuration:${p.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${E} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},pi={search:function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null}},vi={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},yi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},Si=class extends Bs{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Is.ERROR,this.onError,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Is.ERROR,this.onError,this),e.off(Is.ERROR,this.onErrorOut,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Ps.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(e=>i.indexOf(e.groupId)>=0).some(e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ws.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=Vh());case ws.FRAG_GAP:case ws.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=vi.SendAlternateToPenaltyBox);case ws.PLAYLIST_UNCHANGED_ERROR:case ws.LEVEL_EMPTY_ERROR:case ws.LEVEL_PARSING_ERROR:{var n;const e=t.parent===Ps.MAIN?t.level:i.loadLevel;t.details===ws.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ws.LEVEL_LOAD_ERROR:case ws.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case ws.AUDIO_TRACK_LOAD_ERROR:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.SUBTITLE_LOAD_ERROR:case ws.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=i.loadLevelObj;if(e&&(r.type===Cs.AUDIO_TRACK&&e.hasAudioGroup(r.groupId)||r.type===Cs.SUBTITLE_TRACK&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=vi.SendAlternateToPenaltyBox,void(t.errorAction.flags=yi.MoveAllAlternatesMatchingHost)}return;case ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingHDCP});case ws.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ws.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingKey});case ws.BUFFER_ADD_CODEC_ERROR:case ws.REMUX_ALLOC_ERROR:case ws.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case ws.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=yi.ResetMediaSource|yi.SwitchToSDR);case ws.INTERNAL_EXCEPTION:case ws.BUFFER_APPENDING_ERROR:case ws.BUFFER_APPEND_NO_PROGRESS:case ws.BUFFER_FULL_ERROR:case ws.LEVEL_SWITCH_ERROR:case ws.BUFFER_STALLED_ERROR:case ws.BUFFER_SEEK_OVER_HOLE:case ws.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Vh())}t.type===Ts.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Vh())}getPlaylistRetryOrSwitchAction(e,t){const s=sl(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(nl(s,i,Zo(e),e.response))return{action:vi.RetryRequest,flags:yi.None,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(e,t);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=sl(el(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(i&&(e.details!==ws.FRAG_GAP&&i.fragmentError++,!tl(e))&&nl(a,o,Zo(e),e.response))return{action:vi.RetryRequest,flags:yi.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const t=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),t===ws.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===Ps.AUDIO&&t===ws.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&jh(e))&&h.some(({audioCodec:e})=>i.audioCodec!==e),m="video"===e.sourceBufferName&&jh(e)&&h.some(({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let r=h.length;r--;){const n=(r+d)%h.length;if(n!==d&&n>=c&&n<=u&&(0===h[n].loadError||ol(h[n],s.config.errorPenaltyExpireMs))){var a,o;const s=h[n];if(t===ws.FRAG_GAP&&f===Ps.MAIN&&e.frag){const t=h[n].details;if(t){const s=$h(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===Cs.AUDIO_TRACK&&s.hasAudioGroup(v)||p===Cs.SUBTITLE_TRACK&&s.hasSubtitleGroup(v))continue;if(f===Ps.AUDIO&&null!=(a=i.audioGroups)&&a.some(e=>s.hasAudioGroup(e))||f===Ps.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some(e=>s.hasSubtitleGroup(e))||g&&i.audioCodec===s.audioCodec||m&&i.codecSet===s.codecSet||!g&&i.audioCodec!==s.audioCodec)continue}l=n;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:vi.SendAlternateToPenaltyBox,flags:yi.None,nextAutoLevel:l}}return{action:vi.SendAlternateToPenaltyBox,flags:yi.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,i;switch(null==(s=t.errorAction)?void 0:s.action){case vi.DoNothing:break;case vi.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ws.FRAG_GAP||t.details===ws.PLAYLIST_UNCHANGED_ERROR||Kh(t)||(t.fatal=!0);case vi.RetryRequest:}((null==(i=t.errorAction)?void 0:i.flags)||0)&yi.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===yi.None)this.switchLevel(e,i);else if(s.flags&yi.SwitchToSDR){const e=this.hls.levels;for(let t=e.length;t--;)"SDR"!==e[t].videoRange?(e[t].fragmentError++,e[t].loadError++):void 0===i&&(i=t)}else if(s.flags&yi.MoveAllAlternatesMatchingHDCP){const i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=null==r?void 0:r.attrs["HDCP-LEVEL"];s.hdcpLevel=n;const a="NONE"===n;n&&!a?(t.maxHdcpLevel=li[li.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=yi.MoveAllAlternatesMatchingKey)}if(s.flags&yi.MoveAllAlternatesMatchingKey){const t=e.decryptdata;if(t){const i=this.hls.levels,a=i.length;for(let s=a;s--;){var r,n;this.variantHasKey(i[s],t)&&(this.log(`Banned key found in level ${s} (${i[s].bitrate}bps) or audio group "${null==(r=i[s].audioGroups)?void 0:r.join(",")}" (${null==(n=e.frag)?void 0:n.type} fragment) ${Rl(t.keyId||[])}`),i[s].fragmentError++,i[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s))}const o=e.frag;if(this.hls.levels.length<a)s.resolved=!0;else if(o&&o.type!==Ps.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ws.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=bh(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${i} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(i))}}},Ei={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},bi=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const i=s[t];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);const a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o||!this.hls)return;const l=o.body;if(a>=l.sn)return;if(!o.buffered&&(!o.loaded||n))return void(l.type===s&&this.removeFragment(l));const h=o.range[e];if(h)if(0!==h.time.length){if(h.time.some(e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(l),s}),i&&i!==l&&lh()){const e=i.endPTS,t=l.startPTS;if(e&&t&&o.range.video){const s=t-e;s<0&&s>-.1&&(this.removeFragment(l),this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:e+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(l)})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i,id:r}=e;if(!t||!Wo(s))return;const n=zh(s),a=this.fragments[n];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(e=>{const n=s.elementaryStreams[e];if(!n)return;const l=t[e],h=o||!0===n.partial;a.range[e]=this.getBufferedTimes(s,i,h,l),this.detectEvictedFragments(e,l,r,s,i)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,s),Yh(a)||this.removeParts(s.sn-1,s.type),!i){const e=Math.min(.004,s.duration);l.some(t=>{var i;const r=null==(i=a.range[t])?void 0:i.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<e;return n&&this.addAsGap(s),n})}}else this.removeFragment(s)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Qh(s,t=>t.fragment.sn>=e))}fragBuffered(e,t){const s=zh(e);let i=this.fragments[s];return!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<i.length;e++){const t=i.start(e)-this.bufferPadding,s=i.end(e)+this.bufferPadding;if(l>=t&&o<=s){r.time.push({startPTS:Math.max(n,i.start(e)),endPTS:Math.min(a,i.end(e))});break}if(n<s&&a>t){const t=Math.max(n,i.start(e)),s=Math.min(a,i.end(e));s>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return r}getPartialFragment(e){let t,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Yh(h)&&(s=h.body.start-a,i=h.body.end+a,e>=s&&e<=i&&(t=Math.min(e-s,i-e),n<=t&&(r=h.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||Yh(t))}getState(e){const t=zh(e),s=this.fragments[t];return s?s.buffered?Yh(s)?Ei.PARTIAL:Ei.OK:Ei.APPENDING:Ei.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Wo(t.frag)||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=zh(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(!Wo(s))return;const n=s.type;if(i){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(i)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=zh(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}getBackBufferEvictionEnd(e,t,s){const{fragments:i}=this;let r=0,n=0;const a=Object.keys(i);for(let o=0;o<a.length;o++){const l=i[a[o]];if(!l||!l.buffered||l.body.type!==t)continue;const h=l.body;if(h.gap)return 0;const d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=e&&d&&(r+=d,n=Math.max(n,h.end),r>=s))return n}return n>0?n:0}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=zh(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=Qh(s,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}},Ti={cbc:0,ctr:1},wi=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Ti.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ti.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Ii=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),v=new Int32Array(p.length);let y,S,E,b,T,w,I,L,A,k,R,C,P,D;const M=this.networkToHostOrderSwap;for(;t<p.length;){for(A=M(p[t]),k=M(p[t+1]),R=M(p[t+2]),C=M(p[t+3]),T=A^r[0],w=C^r[1],I=R^r[2],L=k^r[3],P=4,D=1;D<i;D++)y=o[T>>>24]^l[w>>16&255]^h[I>>8&255]^d[255&L]^r[P],S=o[w>>>24]^l[I>>16&255]^h[L>>8&255]^d[255&T]^r[P+1],E=o[I>>>24]^l[L>>16&255]^h[T>>8&255]^d[255&w]^r[P+2],b=o[L>>>24]^l[T>>16&255]^h[w>>8&255]^d[255&I]^r[P+3],T=y,w=S,I=E,L=b,P+=4;y=n[T>>>24]<<24^n[w>>16&255]<<16^n[I>>8&255]<<8^n[255&L]^r[P],S=n[w>>>24]<<24^n[I>>16&255]<<16^n[L>>8&255]<<8^n[255&T]^r[P+1],E=n[I>>>24]<<24^n[L>>16&255]<<16^n[T>>8&255]<<8^n[255&w]^r[P+2],b=n[L>>>24]<<24^n[T>>16&255]<<16^n[w>>8&255]<<8^n[255&I]^r[P+3],v[t]=M(y^u),v[t+1]=M(b^f),v[t+2]=M(E^g),v[t+3]=M(S^m),u=A,f=k,g=R,m=C,t+=4}return v.buffer}},Li=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(e){switch(e){case Ti.cbc:return"AES-CBC";case Ti.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}},Ai=class{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,!0!==t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);this.reset();const i=this.decryptRange;return i?0===i.start&&i.end>=s.length?s:s.slice(i.start,i.end):function(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==Ti.cbc||16!==t.byteLength)return Gs.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=eh(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ii),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Li(this.subtle,t,i)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new wi(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(Gs.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Gs.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},ki=Math.pow(2,17),Ri=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,s,i){const r=e.url;if(!r)return Promise.reject(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,a=n.fLoader,o=n.loader;return new Promise((l,h)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void h(Zh(e));e.gap=!1}const d=this.loader=a?new a(n):new o(n),c=Xh(e,null,t);e.loader=d;const u=rl(n.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ki};d.stats.retry=e.stats.retry,e.stats=d.stats;const g={onSuccess:(t,s,i,r)=>{this.resetLoader(e,d);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,i,n)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Xo({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:n}))},onAbort:(t,s,i)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,s,i)=>{this.resetLoader(e,d),h(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:t}))}};if(s){const t=this.gateProgress(s,i);g.onProgress=(s,i,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})}d.load(c,f,g)})}gateProgress(e,t){let s=e;if(t){const i=[];let r=!1;t.then(()=>{r=!0,i.forEach(t=>e(t)),i.length=0}).catch(()=>{}),s=t=>{r?e(t):i.push(t)}}return s}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Zh(e,t));const l=this.loader=r?new r(i):new n(i),h=Xh(e,t);e.loader=l;const d=rl(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ki};t.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Xo({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(e,l),o(new Ci({type:Ts.NETWORK_ERROR,details:ws.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}},Ci=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Pi=class extends Bs{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Di=class{constructor(e,t,s,i=0,r=-1,n=!1,a,o,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}},Mi={length:0,start:()=>0,end:()=>0},_i=class e{static isBuffered(t,s){if(t){const i=e.getBuffered(t);for(let e=i.length;e--;)if(s>=i.start(e)&&s<=i.end(e))return!0}return!1}static bufferedRanges(t){if(t){const s=e.getBuffered(t);return e.timeRangesToArray(s)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(t,s,i){if(t){const r=e.bufferedRanges(t);if(r.length)return e.bufferedInfo(r,s,i)}return{len:0,start:s,end:s,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let i=-1,r=[];if(s)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<s?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const h=r[e].start,d=r[e].end;if(-1===i&&t>=h&&t<=d&&(i=e),t+s>=h&&t<d)o=h,l=d,a=l-t;else if(t+s<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Mi}catch(e){return Gs.log("failed to get media.buffered",e),Mi}}},Oi=/\{\$([a-zA-Z0-9-_]+)\}/g,xi=/^(\d+)x(\d+)$/,Fi=/(.+?)=(".*?"|.*?)(?:,|$)/g,Bi=class e{constructor(t,s){"string"==typeof t&&(t=e.parseAttrList(t,s)),zo(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=xi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={};for(Fi.lastIndex=0;null!==(s=Fi.exec(e));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=td(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Gs.warn(`${e}: attribute ${r} is missing quotes`)}i[r]=n}return i}},Ui=class{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){Gs.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=zo(new Bi({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const s=(null==t?void 0:t.endDate)||new Date(e["END-DATE"]);Ss(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(Gs.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ss(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Ss(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:Ss(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}},Ni=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&Ss(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}},$i="undefined"!=typeof self?self:void 0,Gi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Wi={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"},qi=null!=$i&&null!=(n=$i.navigator)&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,ji={},Ki=class e{static clearKeyUriToKeyIdMap(){ji={}}static setKeyIdForUri(e,t){ji[e]=t}static addKeyIdForUri(e){const t=Object.keys(ji).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),ji[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ld(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Cl(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ad(e.keyFormatVersions,this.keyFormatVersions)&&od(e.iv,this.iv)&&od(e.keyId,this.keyId)}isSupported(){if(this.method){if(ld(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Hi.FAIRPLAY:case Hi.WIDEVINE:case Hi.PLAYREADY:case Hi.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,s){var i;if(!this.encrypted||!this.uri)return null;if(ld(this.method)){let s=this.iv;return s||("number"!=typeof t&&(Gs.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),s=function(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const t=ji[this.uri];if(t&&!ad(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=ud(this.uri);if(r)switch(this.keyFormat){case Hi.WIDEVINE:if(this.pssh=r,!this.keyId){const e=nh(r.buffer).filter(e=>e.systemId===Wi.WIDEVINE);if(e.length){var n;const t=e[0];this.keyId=null!=(n=t.kids)&&n.length?t.kids[0]:null}}this.keyId||(this.keyId=vd(s));break;case Hi.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let i,r,n;i=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(e,...t){const s=t.length;let i=8,r=s;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,s)}(e,0,r),this.keyId=pd(r);break}default:{let e=r.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(16!==(null==(i=this.keyId)?void 0:i.byteLength)){let t;t=function(e){const t=null==e?void 0:e[Hi.WIDEVINE];return t?t.keyId:null}(s),t||(t=vd(s),t||(t=ji[this.uri])),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}},Vi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Yi=/#EXT-X-MEDIA:(.*)/g,zi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Xi=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Ji=class e{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return ks.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return zi.test(e)}static parseMasterPlaylist(t,s){const i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:ed(t)},r=[];if(Vi.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;null!=(n=Vi.exec(t));)if(n[1]){const e=yd(new Bi(n[1],i),n[2],s,i,r);e&&i.levels.push(e)}else if(n[3]){const t=n[3],a=n[4];switch(t){case"I-FRAME-STREAM-INF":{const e=new Bi(a,i),t=yd(e,e.URI,s,i,r,!0);t&&i.iframeVariants.push(t)}break;case"SESSION-DATA":{const e=new Bi(a,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=bd(a,s,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):Gs.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${a}"`);break}case"DEFINE":sd(i,new Bi(a,i),s);break;case"CONTENT-STEERING":{const t=new Bi(a,i);i.contentSteering={uri:e.resolve(t["SERVER-URI"],s),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Td(a)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,s,i){let r;const n={},a=i.levels,o={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Yi.lastIndex=0;null!==(r=Yi.exec(t));){const t=new Bi(r[1],i),a=t.TYPE;if(a){const i=o[a],r=n[a]||[];n[a]=r;const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:l++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:a,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?e.resolve(t.URI,s):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const t=e.findGroup(i,g.groupId)||i[0];Id(g,t,"audioCodec"),Id(g,t,"textCodec")}r.push(g)}}return n}static parseLevelPlaylist(e,t,s,i,r,n){var a;const o={url:t},l=new Ni(t),h=l.fragments,d=[];let c,u,f,g,m=null,p=0,v=0,y=0,S=0,E=0,b=null,T=new _s(i,o),w=-1,I=!1,L=null;if(Qi.lastIndex=0,l.m3u8=e,l.hasVariableRefs=ed(e),"#EXTM3U"!==(null==(a=Qi.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=Qi.exec(e));){I&&(I=!1,T=new _s(i,o),T.playlistOffset=y,T.setStart(y),T.sn=p,T.cc=S,E&&(T.bitrate=E),T.level=s,m&&(T.initSegment=m,m.rawProgramDateTime&&(T.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),L&&(T.setByteRange(L),L=null)));const e=c[1];if(e){T.duration=parseFloat(e);const t=(" "+c[2]).slice(1);T.title=t||null,T.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(Ss(T.duration)){var A;T.playlistOffset=y,T.setStart(y),f&&kd(T,f,l),T.sn=p,T.level=s,T.cc=S;const e=(" "+c[3]).slice(1);T.relurl=td(l,e),Ld(T,b,d),b=T,y+=T.duration,p++,v=0;const t=T.byteRange;if(2===t.length&&(T.bitrate=8*(t[1]-t[0])/T.duration|0),l.iframesOnly&&t[0]&&(null==(A=m)?void 0:A.cc)!==S){const e=new _s(i,o);e.relurl=T.relurl,e.setByteRange(`${Math.min(t[0],1316)}@0`),e.level=s,e.sn="initSegment",f&&(e.levelkeys=f,f.identity&&(e._decryptdata=f.identity.getDecryptData(0))),m=e,T.initSegment=m}h.push(T),I=!0}}else{if(c=c[0].match(Xi),!c){Gs.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),r=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":b?T.setByteRange(r,b):T.setByteRange(r);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=r,T.tagList.push(["PROGRAM-DATE-TIME",r]),-1===w&&(w=h.length);break;case"PLAYLIST-TYPE":l.type&&Rd(l,e,c),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Rd(l,e,c):null!==b&&Cd(l,e,c),l.startSN=parseInt(r),p=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&Rd(l,e,c);const t=new Bi(r,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(Ss(s)){l.skippedSegments+=s;for(let e=s;e--;)h.push(null);p+=s}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(i.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Rd(l,e,c),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Rd(l,e,c),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||Rd(l,e,c),l.live=!1;break;case"#":(r||a)&&T.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":S++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([e]);break;case"BITRATE":T.tagList.push([e,r]),E=1e3*parseInt(r),Ss(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const e=new Bi(r,l),t=new Ui(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Gs.log(`Ignoring invalid DATERANGE tag: ${t.invalidReason}: ${r}`),T.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new Bi(r,l);"IMPORT"in e?id(l,e,n):sd(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC&&Rd(l,e,c),l.startCC=S=parseInt(r),h.forEach(e=>e&&(e.cc=S));break;case"KEY":{const e=bd(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=zo({},f)),f[e.keyFormat]=e)}else Gs.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Td(r);break;case"MAP":{const e=new Bi(r,l);if(T.duration){const t=new _s(i,o);Ad(t,e,s,f),m=t,T.initSegment=m,m.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=m.rawProgramDateTime)}else{const t=T.byteRangeEndOffset;if(t){const e=T.byteRangeStartOffset;L=`${t-e}@${e}`}else L=null;Ad(T,e,s,f),m=T,I=!0}m.cc=S;break}case"SERVER-CONTROL":g&&Rd(l,e,c),g=new Bi(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Rd(l,e,c);const t=new Bi(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,s=v++,i=new Bi(r,l),n=new Os(i,T,o,s,t);e.push(n),T.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new Bi(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Bi(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Gs.warn(`line parsed but not handled: ${c}`)}}}b&&!b.relurl?(h.pop(),y-=b.duration,l.partList&&(l.fragmentHint=b)):l.partList&&(Ld(T,b,d),T.cc=S,l.fragmentHint=T,f&&kd(T,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=h.length,R=h[0],C=h[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&C){l.averagetargetduration=y/k;const e=C.sn;l.endSN="initSegment"!==e?e:0,l.live||(C.endList=!0),w>0&&(function(e,t,s){if(s||(s=e[t]),s)for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}(h,w,w>k-1?T:null),R&&d.unshift(R))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&R&&Sd(d,l),l.endCC=S,l}},Zi={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"},er=class extends Pi{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Zi.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=_i.bufferInfo(i||s,n,e.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Zi.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,i=t.start-s,r=t.start+t.duration+s;if(!o||r<a.start||i>a.end){const e=n<i,s=n>r;(e||s)&&(!t.loader||!s&&this.isFragmentNearlyDownloaded(t)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${t.sn}) - ${e?"backward":"forward"} seek`),t.abortRequests(),this.resetLoadingState()))}}if(s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${e}`),this.loadingParts=t)}const l=!_i.isBuffered(s,n);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,l&&(this.startPosition=n)),o<1&&this.state===Zi.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Ri(e.config),this.initFragmentLoader=new Ri(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ai(e.config)}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Zi.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Zi.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;if(-1===t&&e){const t=this.getLevelDetails();return null!=t&&t.live?(this.hls.liveSyncPosition||t.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=_i.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return _i.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;jd(s,"seeking",this.onMediaSeeking),jd(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Zi.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;const s=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Kd(i,"seeking",this.onMediaSeeking),Kd(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Zi.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(t);const s=++t.stats.chunkCount;this.log(`load progress ${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} chunk: ${s}`),this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===Zi.FRAG_LOADING||!this.fragCurrent&&t===Zi.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=Zi.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level} (bytes ${s.stats.loaded})`),this.hls.trigger(Is.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Zi.STOPPED&&this.state!==Zi.ERROR&&(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===Ei.APPENDING){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Ei.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){const e=t.getPartialFragment(s.end);e&&(t.removeFragment(e),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(Is.BUFFER_FLUSHING,i)}_loadInitSegment(e){const{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(Is.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(e=>{var t;const s=e.frag;if(!this.levels||!jo(s,null==(t=this.fragCurrent)?void 0:t.initSegment))throw new Ci({type:Ts.NETWORK_ERROR,details:ws.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:s,networkDetails:null});return e}).then(e=>{const{frag:s,payload:i}=e,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ld(r.method)){const n=self.performance.now(),{decryptRange:a}=Jh(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,hd(r.method),a).catch(e=>{throw t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),this.fragmentLoader.abort(),e}).then(i=>{const r=self.performance.now();return t.trigger(Is.FRAG_DECRYPTED,{frag:s,part:null,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)})}completeInitSegmentLoad(e){const t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:t}=e;var s;if(!this.bitrateTest&&Wo(e)&&t&&!t.data)return(!t.encrypted||null!=(s=t.decryptdata)&&s.key?this._loadInitSegment(t):this.keyLoader.load(t).then(()=>this._loadInitSegment(t))).catch(t=>{if(this.state===Zi.STOPPED||this.state===Zi.ERROR)throw t;throw"data"in t&&(t.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(t)),this.resetFragmentLoading(e),t})}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&(null!=(s=r.audio)&&s.encrypted||null!=(i=r.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(s.message),!(!e||e.mediaKeys)&&(this.hls.trigger(Is.ERROR,{type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!jo(e,t)}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Vd(_i.getBuffered(s)):"(detached)"})`),Wo(e)){var i;if(e.type!==Ps.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Zi.IDLE)}const s=null==(i=this.levels)?void 0:i[e.level];null!=s&&s.fragmentError&&(t||this.fragmentTracker.getState(e)!==Ei.PARTIAL)&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0,e.stats.retry=0)}this.state=Zi.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const s=e.frag,{part:i,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),{decryptRange:a}=Jh(s,i),o=new Di(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n,s.duration,this.iframesOnly,a);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),t.flush(o)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){var i;let r=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)):(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Zi.KEY_LOADING,r=this.keyLoader.load(e,s).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Is.KEY_LOADED,e),this.state===Zi.KEY_LOADING&&(this.state=Zi.IDLE),e}),this.hls.trigger(Is.KEY_LOADING,{frag:e})),r}_doFragLoad(e,t,s=null,i){this.fragCurrent=e;const r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const n=this.fragPrevious;if(!qo(e,n)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==n?void 0:n.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts){const a=r.partList;if(a&&i){s>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);const o=this.getNextPart(a,e,s);if(o>-1){const l=a[o];if(!qo(e=this.fragCurrent=l.fragment,n)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,l)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(l,t.details))return Promise.resolve(null);const h=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);let d;this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${a.length-1}) of ${this.fragInfo(e,!1,l)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${s}${l.byteRange.length?` range:${l.byteRange.join("-")}`:""}`),this.nextLoadPosition=l.start+l.duration,this.state=Zi.FRAG_LOADING;const c=this.loadInitSegmentIfNeeded(e);if(h||c){const s=!!h;d=Promise.all([h,c]).then(([r])=>!s||r&&!this.fragContextChanged(r.frag)?this.doFragPartsLoad(e,l,t,i):null).catch(e=>this.handleFragLoadError(e))}else d=this.doFragPartsLoad(e,l,t,i).catch(e=>this.handleFragLoadError(e));return this.hls.trigger(Is.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(a,s))return Promise.resolve(null)}}var a;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${e.sn} loaded parts: ${null==(a=r.partList)?void 0:a.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);const o=this.loadInitSegmentIfNeeded(e),l=this.loadKeyFor(e,r,o);var h;if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${null==(h=this.fragCurrent)?void 0:h.relurl}`),null==o||o.catch(()=>null),null==l||l.catch(()=>null),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),Ss(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Zi.FRAG_LOADING;const d=this.config.progressive&&e.type!==Ps.SUBTITLE;let c;return c=d&&l?l.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,o)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,d?i:void 0,d?o:void 0),l,o]).then(([e])=>(!d&&i&&i(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Is.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([c,o]).then(([e])=>e)}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,i).then(i=>{o[t.index]=i;const n=i.part;this.hls.trigger(Is.FRAG_LOADED,i);const a=Fd(s.details,e.sn,t.index+1)||Bd(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});h(a)}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ws.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ts.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(Is.ERROR,t)}else this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Zi.PARSING)return void(this.fragCurrent||this.state===Zi.STOPPED||this.state===Zi.ERROR||(this.state=Zi.IDLE));const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;const i=e.partList[0];if(t>=i.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Fd(o,r,n):null,h=l?l.fragment:xd(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==Zi.PARSING)return;Wo(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);const{data1:n,data2:a}=e;let o=n;if(a&&(o=eh(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(Is.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!_i.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=_i.bufferInfo(t,s,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.playhead,r=this.lastCurrentTime>i||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=_i.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-t,i);return _i.bufferInfo(e,t,s)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){const i=e.nextStart;if(i&&s.start>i){const i=e.buffered;if(i){let r=e.len;const n=e.bufferedIndex;for(let e=i.length-1;e>n;e--)i[e].start<s.start&&(r+=i[e].end-i[e].start);return r>=t}}return!1}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t/2),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e){const t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=r.initialLiveManifestSize;if(i<s)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${s})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;o=this.getInitialLiveFragment(t);const s=this.config.startPosition,i=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let h,d;if(-1!==i&&i>=n?(h=i,d=i===s?"config":"next load start"):r?(h=r,d="live edge"):(h=e,d="buffer pos"),h<a&&(h=a,d="live frag start"),h<n&&(h=n,d="playlist start"),this.startPosition!=h||this.nextLoadPosition!=h){const l=t.live&&!this.filterReplacedPrimary(o,t)?-1:h;this.log(`Setting startPosition to ${l} next load ${h} ${-1===i?"":`(from ${s}) `}based on ${d}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${e}`),this.startPosition=l,this.nextLoadPosition=h}}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let h=this.filterReplacedPrimary(o,t);return!h&&o&&(h=qh(t,o.sn,this.loadingParts),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const s=this.fragmentTracker.getState(e);if(s===Ei.OK)return!0;if(s===Ei.PARTIAL){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==e&&s.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){var e;if(zd(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}filterReplacedPrimary(e,t){if(!e)return e;if(zd(this.config)&&("type"in e?e:e.fragment).type!==Ps.SUBTITLE){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(!s.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(Yd(e,null==s?void 0:s.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded||o.gap;l?i=-1:(r||(o.independent||n)&&o.fragment===t)&&(i=a),r=l&&!o.gap}const a=e[i];return a&&a.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${a.start} (sn: ${t.sn} -> ${a.fragment.sn})`),i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(i=function(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!Ss(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(Hh(t,s,r))return r}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Wh(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;var u;(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===Ei.NOT_LOADED&&(r=null),e<t)?c=$h(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l):c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===Ei.OK||t===Ei.PARTIAL&&c.gap)&&(r=c),qo(c,r)&&(!d||h[0].fragment.sn>c.sn||!s.live)){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Ei.OK?t:null}}return c}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&Ss(r);if(n||!a&&!r){qd(s,e,this);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;if(null!==n&&Ss(n))s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){const e=this.hls.liveSyncPosition;s=e||t,this.log(`Setting startPosition to -1 to start at ${e?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t;const e=null==(t=this.media)?void 0:t.currentTime;return Ss(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==Ps.MAIN)return!1;const t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Wo(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Zi.FRAG_LOADING_WAITING_RETRY)||(this.state=Zi.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const{frag:s,part:i}=t;if(!s||!this.levels||s.type!==e)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const n=t.details===ws.FRAG_GAP;n&&this.fragmentTracker.addAsGap(s);const a=t.errorAction;if(!a)return void(this.state=Zi.ERROR);const{action:o,flags:l,retryCount:h=0,retryConfig:d}=a,c=!!d,u=c&&o===vi.RetryRequest,f=c&&!a.resolved&&l&yi.MoveAllAlternatesMatchingHost,g=this.hls.latestLevelDetails,m=null==g?void 0:g.live;if(!u&&f&&Wo(s)&&m&&s.sn<g.endSN&&!tl(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(s),a.resolved=!0;else if((u||f)&&h<d.maxNumRetry){var p;const i=al(null==(p=t.response)?void 0:p.code),r=il(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Zi.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${r}ms`)}else if(d){if(this.resetFragmentErrors(e),!(h<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${h})`);n||o===vi.RemoveAlternatePermanently||(a.resolved=!0)}else o===vi.SendAlternateToPenaltyBox?this.state=Zi.WAITING_LEVEL:this.state=Zi.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!al(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Zi.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Zi.PARSING||this.state===Zi.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===Ps.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===Ps.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Zi.STOPPED&&(this.state=Zi.IDLE)}afterBufferFlushed(e,t){if(!e)return;const s=_i.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===Zi.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Zi.STOPPED&&(this.state=Zi.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(r){if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=i.partial?0:Dd(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this.iframesOnly,this);return this.hls.trigger(Is.LEVEL_PTS_UPDATED,{details:r,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var n,a,o,l;const i=null===(null==(n=this.transmuxer)?void 0:n.error),r=null!=(null==(a=this.transmuxer)?void 0:a.error),h=(null!=(o=null==(l=this.levels)?void 0:l.length)?o:0)>1;if((0===s.fragmentError||i&&(s.fragmentError<2||e.endList)||r&&h)&&this.treatAsGap(e,s),i){const i=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(i.message),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,error:i,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Zi.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(Is.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${null!=(i=t&&!s?e.startPTS:(s||e).start)?i:NaN}-${null!=(r=t&&!s?e.endPTS:(s||e).end)?r:NaN}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}isFragmentNearlyDownloaded(e){var t;const s=null==(t=e.loader)?void 0:t.stats;if(!s)return!1;const i=s.loading.first>0,r=(s.total-s.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&r<=.15}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let s=0;const{hls:i,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var h;const t=o===Ps.AUDIO?Lh(e.audioCodec,128e3):e.maxBitrate,r=1+i.ttfbEstimate/1e3,a=i.bandwidthEstimate*n.abrBandWidthUpFactor;s=r+t*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/a,e.details||(s+=r)}const d=this.playhead;return{fetchdelay:s,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-d>1.5*s}}scheduleTrackSwitch(e,t,s){const{media:i,playlistType:r}=this;if(!i||!e)return;const n=s?this.getBufferedFrag(this.playhead+t):null;if(n){const e=this.followingBufferedFrag(n);if(e){var a;this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,i=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>i)return;const o=r===Ps.MAIN?null:"audio";this.flushMainBuffer(i,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:t}=this;if(!e)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const e=t===Ps.AUDIO;this.flushMainBuffer(0,s.start-(e?0:1),e?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Zi.KEY_LOADING:case Zi.FRAG_LOADING:case Zi.FRAG_LOADING_WAITING_RETRY:case Zi.PARSING:case Zi.PARSED:this.state=Zi.IDLE}this.nextLoadPosition=this.playhead}checkFragPlaying(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(_i.isBuffered(e,s)?t=this.getAppendedFrag(s):_i.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!qo(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:t,hls:s,config:i,playlistType:r}=this;if(null!=t&&t.readyState&&e&&s&&i){const t=this.getBufferOutput(),i=this.getFwdBufferInfo(t,r);if(!i)return;const n=e[r===Ps.AUDIO?s.nextAudioTrack:s.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,i);this.scheduleTrackSwitch(i,a,o)}this.tickImmediate()}},tr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function(e,t){const s=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}},sr={exports:{}},ir||(ir=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}function r(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=s?s+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,r,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,n),!0;case 6:return d.fn.call(d.context,t,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,i);break;case 4:d[h].fn.call(d[h].context,t,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,i,r){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(sr)),rr=Ho(sr.exports),nr="1.7.0",ar={},or=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({}),lr=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=eh(this.cachedData,e),this.cachedData=null);let s,i=Sl(e,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?kl(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Ss(o))&&(this.basePTS=hr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:or.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=l}else vl(e,r)?(i=Sl(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:or.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=eh(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:rc(),id3Track:a,textTrack:rc()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:rc(),id3Track:this._id3Track,textTrack:rc()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},hr=(e,t,s)=>Ss(e)?90*e:9e4*t+(s?9e4*s.baseTime/s.timescale:0),dr=[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],cr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ur=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fr=[0,1,1,4],gr=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ai(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ti.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,s),this.decrypter.isSync())))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)s.set(e.subarray(t,t+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let t=32;t<e.length-16;t+=160,i+=16)e.set(s.subarray(i,i+16),t);return e}decryptAvcSample(e,t,s,i,r){const n=rh(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,i,n),this.decrypter.isSync())))return}}}},mr=class extends lr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Sl(e,0);let i=(null==s?void 0:s.length)||0;if(hc(e,i))return!1;for(let s=e.length;i<s;i++)if(ec(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Qd(e,t)&&Jd(e,t)<=e.length-t}(e,t)}appendFrame(e,t,s){tc(e,this.observer,t,s,e.manifestCodec);const i=ic(e,t,s,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}demuxSampleAes(e,t,s){const i=this.demux(e,s),r=this.sampleAes=new gr(this.observer,this.config,t);return new Promise(e=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{e(i)})})}},pr=(e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s},vr=class extends lr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=dc(e,t,s,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Sl(e,0);if(!t)return!1;const s=t.length;if(11===e[s]&&119===e[s+1]&&void 0!==kl(t)){if(pr(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}},yr=class extends lr{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Sl(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==kl(t)&&pr(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(hc(e,s))return Gs.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return oc(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return nc(e,t,s,this.basePTS,this.frameIndex)}},Sr=/\/emsg[-/]ID3/i,Er=class{constructor(e,t,s,i=Gs){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=i}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=rc("video",1),n=this.audioTrack=rc("audio",1),a=this.txtTrack=rc("text",1);if(this.id3Track=rc("id3",1),this.initData=void 0,this.timeOffset=0,null==e||!e.byteLength)return;const o=this.initData=ql(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:i}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=s,r.supplemental=i}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=Qs.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let s=0;s<t;){const i=_l(e,s);if(i>8&&_l(e,s+4)===zs.moof)return!0;s=i>1?s+i:t}return!1}(e)}demux(e,t,s){this.timeOffset=t;let i=e;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=eh(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},s=Gl(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const a=this.extractID3Track(r,t),o=this.parseFragment(r,n,t,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(e,t){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(i,this.timeOffset),a=this.parseFragment(i,r,s,t);return{videoTrack:i,audioTrack:rc(),id3Track:n,textTrack:rc(),initData:this.initData,sampleData:a}}parseFragment(e,t,s,i){const r=this.initData;if(r&&i){const{samples:n,sampleData:a}=function(e,t,s,i,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:Zl(t.samples,s,i,r,{isHEVCFlavor:th(t.codec),samples:n,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(s,e,r,this.logger,i.iframe);return t.samples=n,a}t.samples=function(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return Gl(i,["moof"]).map(o=>{const l=o.byteOffset-8;Gl(o,["traf"]).map(o=>{const h=Gl(o,["tfdt"]).map(e=>{const t=e[0];let s=_l(e,4);return 1===t&&(s*=Math.pow(2,32),s+=_l(e,8)),s/r})[0];return void 0!==h&&(e=h),Gl(o,["tfhd"]).map(h=>{const d=_l(h,4),c=16777215&_l(h,0),u=!!(1&c);let f=0;const g=!!(2&c),m=!!(8&c);let p=0;const v=!!(16&c);let y=0;const S=!!(32&c),E=!u&&!!(131072&c);let b=8;d===n&&(u?(f=_l(h,b),b+=4,f*=Math.pow(2,32),f+=_l(h,b),b+=4):E&&(f=l),g&&(b+=4),m&&(p=_l(h,b),b+=4),v&&(y=_l(h,b),b+=4),S&&(b+=4),"video"===t.type&&(a=th(t.codec)),Gl(o,["trun"]).map(n=>{const o=n[0],l=16777215&_l(n,0),h=!!(1&l);let d=0;const c=!!(4&l),u=!!(256&l);let g=0;const m=!!(512&l);let v=0;const S=!!(1024&l),E=!!(2048&l);let b=0;const T=_l(n,4);let w=8;h&&(d=_l(n,w),w+=4),c&&(w+=4);let I=f+d;for(let l=0;l<T;l++){if(u?(g=_l(n,w),w+=4):g=p,m?(v=_l(n,w),w+=4):v=y,S&&(w+=4),E&&(b=0===o?_l(n,w):Fl(n,w),w+=4),t.type===Ds.VIDEO){let t=0;for(;t<v;){const n=_l(i,I);I+=4,sh(a,i[I])&&ih(i.subarray(I,I+n),a?2:1,e+b/r,s),I+=n,t+=n+4}}e+=g/r}}))})})}),s}(s,e)}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Gl(e.samples,["emsg"]);i&&i.forEach(e=>{const i=function(e){const t=e[0];let s,i="",r="",n=0,a=0,o=0,l=0,h=4;if(0===t){const t=xl(e,h),s=null!==t?xl(e,h+t.length):null;null!==t&&null!==s?(i=t,r=s,h+=t.length+s.length,n=_l(e,h),h+=4,a=_l(e,h),h+=4,o=_l(e,h),h+=4,l=_l(e,h),h+=4):(Gs.warn(`Unterminated ${null===t?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=e.length)}else if(1===t){n=_l(e,h),h+=4;const t=_l(e,h);h+=4;const a=_l(e,h);h+=4,s=2**32*t+a,Es(s)||(s=Number.MAX_SAFE_INTEGER,Gs.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=_l(e,h),h+=4,l=_l(e,h),h+=4;const d=xl(e,h),c=null!==d?xl(e,h+d.length):null;null!==d&&(i=d,h+=d.length),null!==c?(r=c,h+=c.length):(Gs.warn(`Unterminated ${null===d?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===d?"strings and payload":"value and payload"}`),h=e.length)}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Sr.test(i.schemeIdUri)){const e=cc(i,t);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:or.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata){const e=this.config.emsgKLVSchemaUri||or.misbklv;if(i.schemeIdUri.startsWith(e)){const e=cc(i,t);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:e,pts:e,type:or.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},br=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const t=s[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;if(0===i)return[];const r=e.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,h=-1,d=0;for(-1===r&&(h=0,d=this.getNALuType(t,0),l=1);l<i;){const s=t.indexOf(1,l);if(-1===s)break;l=s+1;let r=s;for(;r>0&&0===t[r-1];)r--;if(!(s-r+(0===r?n:0)<2)){if(h>=0)a.push({data:t.subarray(h,r),type:d});else{const s=this.getLastNalUnit(e.samples);s&&(r>0?s.data=eh(s.data,t.subarray(0,r)):n>0&&(s.data=s.data.subarray(0,s.data.byteLength-n)),s.state=0)}if(!(l<i)){o=-1,h=-1;break}h=l,d=this.getNALuType(t,l)}}if(-1!==o){let e=i;for(;e>0&&0===t[e-1];)e--;o=i-e+(0===e?n:0)}if(h>=0)a.push({data:t.subarray(h),type:d,state:o});else if(0===a.length&&-1!==o){const s=this.getLastNalUnit(e.samples);s&&(s.data=eh(s.data,t),s.state=o)}return e.naluState=o,a}},Tr=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&Gs.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}},wr=class extends br{parsePES(e,t,s,i,r){const n=r.iframe,a=this.parseNALu(e,s.data,i);let o,l=this.VideoSample,h=!1;s.data=null,l&&a.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.forEach(i=>{var r,a;switch(i.type){case 1:{if(n)break;let t=!1;o=!0;const r=i.data;if(h&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;t&&null!=(d=l)&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=t;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,ih(i.data,1,s.pts,t.samples);break;case 7:{var c,u;o=!0,h=!0;const t=i.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(c=e.pixelRatio)?void 0:c[0])!==s.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const i=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:o=!0,e.pps=[i.data];break;case 9:o=!0,e.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1}l&&o&&l.units.push(i)}),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Tr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,i=8,r=8;for(let n=0;n<e;n++)0!==r&&(s=t.readEG(),r=(i+s+256)%256),i=0===r?i:r}readSPS(e){const t=new Tr(e);let s,i,r,n=0,a=0,o=0,l=0;const h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(i=3!==e?8:12,r=0;r<i;r++)u()&&p(r<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),r=0;r<s;r++)g();m(),f(1);const S=c(),E=c(),b=d(1);0===b&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let T=[1,1];if(u()&&u())switch(h()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*n-2*a),height:(2-b)*(E+1)*16-(b?2:4)*(o+l),pixelRatio:T}}},Ir=class extends br{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null;const l=e=>(a=this.VideoSample=this.createVideoSample(e,s.pts,s.dts),a);r.forEach((i,r)=>{var h,d;if(this.startsNewAccessUnit(a,e,i,r)){this.pushAccessUnit(a,e);const t=i.type>=16&&i.type<=23;a=l(t),o=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;n=!0,o&&null!=(c=a)&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,ih(i.data,2,s.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=zo(e.params,this.readVPS(i.data)),this.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],i.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(i.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const s in t.params)e.params[s]=t.params[s]}this.pushParameterSet(e.sps,i.data,e.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(i.data);for(const s in t)e.params[s]=t[s]}this.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(d=a)&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=l(!1));break;default:n=!1}a&&n&&a.units.push(i)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;const{type:r,data:n}=s;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Tr(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Tr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=[],y=[];for(let e=0;e<s;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let e=s;e<8;e++)t.readBits(2);for(let e=0;e<s;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const S=t.readUEG();3==S&&t.skipBits(1);const E=t.readUEG(),b=t.readUEG(),T=t.readBoolean();let w=0,I=0,L=0,A=0;T&&(w+=t.readUEG(),I+=t.readUEG(),L+=t.readUEG(),A+=t.readUEG());const k=t.readUEG(),R=t.readUEG(),C=t.readUEG();for(let e=t.readBoolean()?0:s;e<=s;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++)if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let D=0;for(let e=0;e<P;e++){let s=!1;if(0!==e&&(s=t.readBoolean()),s){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let s=0;for(let e=0;e<=D;e++){const e=t.readBoolean();let i=!1;e||(i=t.readBoolean()),(e||i)&&s++}D=s}else{const e=t.readUEG(),s=t.readUEG();D=e+s;for(let s=0;s<e;s++)t.readUEG(),t.readBoolean();for(let e=0;e<s;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<C+4;e++)t.readBits(1);t.readBits(1)}}let M=0,_=1,O=1,x=!0,F=1,B=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),O=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(F=t.readBits(32),B=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const e=t.readBoolean(),i=t.readBoolean();let r=!1;(e||i)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){x=t.readBoolean();let s=!1;x||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(i)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let N=E,$=b;if(T){let e=1,t=1;1===S?e=t=2:2==S&&(e=2),N=E-e*I-e*w,$=b-t*A-t*L}const G=i?["A","B","C"][i]:"",H=a<<24|o<<16|l<<8|h;let W=0;for(let e=0;e<32;e++)W=(W|(H>>e&1)<<31-e)>>>0;let q=W.toString(16);return 1===n&&"2"===q&&(q="6"),{codecString:`hvc1.${G}${n}.${q}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:R,min_spatial_segmentation_idc:M,chroma_format_idc:S,frame_rate:{fixed:x,fps:B/F}},width:N,height:$,pixelRatio:[_,O]}}readPPS(e){const t=new Tr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),i=t.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return Dl(e).substring(3)===Dl(t).substring(3)}},Lr=188,Ar=class e{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,s){const i=e.syncOffset(t);return i>0&&s.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let s=Math.min(940,t-Lr)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<t;o+=Lr){if(71!==e[o]||t-o!==Lr&&71!==e[o+Lr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-Lr)+1)),r||(r=0===uc(e,o)),r&&a>1&&(0===n&&a>2||o+Lr>s))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qs[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(t,s,i,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new kr(this.logger):null,this._audioTrack=e.createTrack("audio",r),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=i,t&&this.demux(t,0,a,"SAMPLE-AES"===(null==n?void 0:n.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,s,i,r=!1,n=!1){let a;r||(this.sampleAes=null);const o=this._videoTrack,l=this.videoIntegrityChecker,h=this._audioTrack,d=this._id3Track,c=this._txtTrack,u=i.iframe;let f=o.pid,g=o.pesData,m=h.pid,p=d.pid,v=this._klvPid,y=h.pesData,S=d.pesData,E=null,b=null,T=this.pmtParsed,w=this._pmtId,I=t.length;if(this.remainderData&&(I=(t=eh(this.remainderData,t)).length,this.remainderData=null),I<Lr&&!n)return this.remainderData=t,{audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};const L=Math.max(0,e.syncOffset(t));I-=(I-L)%Lr,I<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,I,t.buffer.byteLength-I));let A=0;for(let e=L;e<I;e+=Lr)if(71===t[e]){const s=!!(64&t[e+1]),n=uc(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+Lr)continue}else I=e+4;switch(n){case f:s&&(!g||null!=l&&l.isCorrupted||!(a=vc(g,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,c,a,!1,i)),g={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(e)),g&&(g.data.push(t.subarray(I,e+Lr)),g.size+=e+Lr-I);break;case m:if(u)break;if(s){if(y&&(a=vc(y,this.logger)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,a,i);break;case"mp3":this.parseMPEGPES(h,a);break;case"ac3":this.parseAC3PES(h,a)}y={data:[],size:0}}y&&(y.data.push(t.subarray(I,e+Lr)),y.size+=e+Lr-I);break;case p:if(u)break;s&&(S&&(a=vc(S,this.logger))&&this.parseID3PES(d,a),S={data:[],size:0}),S&&(S.data.push(t.subarray(I,e+Lr)),S.size+=e+Lr-I);break;case v:if(u)break;s&&(E&&(a=vc(E,this.logger))&&this.parseKlvPES(d,a),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+Lr)),E.size+=e+Lr-I);break;case 0:s&&(I+=t[I]+1),w=this._pmtId=fc(t,I);break;case w:{s&&(I+=t[I]+1);const n=gc(t,I,this.typeSupported,r,this.observer,this.logger,this.config,i);f=n.videoPid,f>0&&(o.pid=f,o.segmentCodec=n.segmentVideoCodec),m=n.audioPid,m>0&&(h.pid=m,h.segmentCodec=n.segmentAudioCodec),p=n.id3Pid,p>0&&(d.pid=p),v=n.klvPid,v>0&&(this._klvPid=v),null===b||T||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${b}'. Backtracking to sync byte @${L} to parse all TS packets.`),b=null,e=L-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=n}}else A++;A>0&&mc(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=g,h.pesData=y,d.pesData=S;const k={audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};return n&&this.extractRemainingSamples(k,i),k}flush(e,t){const{remainderData:s}=this;let i;return this.remainderData=null,i=s?this.demux(s,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=s.pesData,l=r.pesData,h=this.videoIntegrityChecker;let d;if(!a||null!=h&&h.isCorrupted||!(d=vc(a,this.logger))?i.pesData=a:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,n,d,!0,t),i.pesData=null)),o&&(d=vc(o,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,d,t);break;case"mp3":this.parseMPEGPES(s,d);break;case"ac3":this.parseAC3PES(s,d)}s.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=o;l&&(d=vc(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s,i){const r=this.demux(e,s,i,!0,!this.config.progressive),n=this.sampleAes=new gr(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new wr:"hevc"===e&&(this.videoParser=new Ir))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){let i=0;const r=this.aacOverFlow;let n,a,o,l=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)l=eh(r.sample.unit,l);else{const n=s-t;r.sample.unit.set(l.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(n=i,a=l.length;n<a-1&&!Zd(l,n);n++);if(n!==i){let e;const t=n<a-1;if(e=t?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",mc(this.observer,new Error(e),s,t,this.logger),!t)return}if(tc(e,this.observer,l,n,this.audioCodec),void 0!==t.pts)o=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=sc(e.samplerate);o=r.sample.pts+t}}let h,d=0;for(;n<a;){if(h=ic(e,l,n,o,d),n+=h.length,h.missing){this.aacOverFlow=h;break}for(d++;n<a-1&&!Zd(l,n);n++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(lc(s,n)){const t=nc(e,s,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=dc(e,s,o,i,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=zo({},t,{type:this._videoTrack?or.emsg:or.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;const i=null!=(s=t.pts)?s:t.dts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=t.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const s=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const e=127&o;if(0===e||e>4||n+e>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let t=0;t<e;t++)l=l<<8|r[n+t];n+=e}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=n+l,d=r.subarray(s,h),c={data:d,len:d.byteLength,pts:i,dts:null!=(a=t.dts)?a:i,type:or.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(c),n=h}}},kr=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return"ok"!==this.integrityState}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const t=uc(e,0);if(t!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);const s=(48&e[3])>>4;if(0===s)return;const i=15&e[3],r=this.lastContinuityCounter;this.lastContinuityCounter=i;const n=!!(1&s);if(2&s&&0!=e[4]&&128&e[5])return;if(r<0)return;const a=n?r+1&15:r;return i!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${i}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),void(this.integrityState="tei-bit")):void 0}},Rr=class{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}},Pr={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Dr=new Uint8Array([0,0,0,0,0,0,0,0]),Mr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_r=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Or=new Uint8Array([0,0,0,0,0,0,0,0]),xr=new Uint8Array([0,0,0,0,0,0,0,1]),Fr=new Uint8Array([105,115,111,109]),Br=new Uint8Array([97,118,99,49]),Ur=new Uint8Array([0,0,0,1]),Cr=Nr=class e{static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(Bl(n,0,s),Bl(n,4,e),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(t){return e.box(zs.hdlr,Pr[t])}static mdat(t){return e.box(zs.mdat,t)}static mdhd(t,s){s*=t;const i=Math.floor(s/(Ys+1)),r=Math.floor(s%(Ys+1));return e.box(zs.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return e.box(zs.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(zs.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?e.box(zs.minf,e.box(zs.smhd,Or),e.DINF,e.stbl(t)):e.box(zs.minf,e.box(zs.vmhd,_r),e.DINF,e.stbl(t))}static moof(t,s,i){return e.box(zs.moof,e.mfhd(t),e.traf(i,s))}static moov(t){let s=t.length;const i=[];for(;s--;)i[s]=e.trak(t[s]);return e.box.apply(null,[zs.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}static mvex(t){let s=t.length;const i=[];for(;s--;)i[s]=e.trex(t[s]);return e.box.apply(null,[zs.mvex,...i])}static mvhd(t,s){s*=t;const i=Math.floor(s/(Ys+1)),r=Math.floor(s%(Ys+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 e.box(zs.mvhd,n)}static sdtp(t){const s=t.samples||[],i=new Uint8Array(4+s.length);let r,n;for(r=0;r<s.length;r++)n=s[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return e.box(zs.sdtp,i)}static stbl(t){return e.box(zs.stbl,e.stsd(t),e.box(zs.stts,Dr),e.box(zs.stsc,Dr),e.box(zs.stsz,Mr),e.box(zs.stco,Dr))}static avc1(t){let s,i,r,n=[],a=[];for(s=0;s<t.sps.length;s++)i=t.sps[s],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));for(s=0;s<t.pps.length;s++)i=t.pps[s],r=i.byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));const o=e.box(zs.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return e.box(zs.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,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(zs.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(zs.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(t){return e.box(zs.mp4a,e.audioStsd(t),e.box(zs.esds,e.esds(t)))}static mp3(t){return e.box(zs[".mp3"],e.audioStsd(t))}static ac3(t){return e.box(zs["ac-3"],e.audioStsd(t),e.box(zs.dac3,t.config))}static stsd(t){const{segmentCodec:s}=t;if("audio"===t.type){if("aac"===s)return e.box(zs.stsd,xr,e.mp4a(t));if("ac3"===s&&t.config)return e.box(zs.stsd,xr,e.ac3(t));if("mp3"===s&&"mp3"===t.codec)return e.box(zs.stsd,xr,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===s)return e.box(zs.stsd,xr,e.avc1(t));if("hevc"===s&&t.vps)return e.box(zs.stsd,xr,e.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${s}/${t.codec})`)}static tkhd(t){const s=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,n=t.height||0,a=Math.floor(i/(Ys+1)),o=Math.floor(i%(Ys+1));return e.box(zs.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,255&s,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,r>>8&255,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(t,s){const i=e.sdtp(t),r=t.id,n=Math.floor(s/(Ys+1)),a=Math.floor(s%(Ys+1));return e.box(zs.traf,e.box(zs.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),e.box(zs.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,e.box(zs.trak,e.tkhd(t),e.mdia(t))}static trex(t){const s=t.id;return e.box(zs.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,s){const i=t.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,h,d,c,u;for(s+=8+n,a.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s],0),o=0;o<r;o++)l=i[o],h=l.duration,d=l.size,c=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,255&h,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*o);return e.box(zs.trun,a)}static initSegment(t){const s=e.moov(t);return eh(e.FTYP,s)}static hvc1(t){const s=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,s.general_profile_space<<6|(s.general_tier_flag?32:0)|s.general_profile_idc,s.general_profile_compatibility_flags[0],s.general_profile_compatibility_flags[1],s.general_profile_compatibility_flags[2],s.general_profile_compatibility_flags[3],s.general_constraint_indicator_flags[0],s.general_constraint_indicator_flags[1],s.general_constraint_indicator_flags[2],s.general_constraint_indicator_flags[3],s.general_constraint_indicator_flags[4],s.general_constraint_indicator_flags[5],s.general_level_idc,240|s.min_spatial_segmentation_idc>>8,255&s.min_spatial_segmentation_idc,252|s.parallelismType,252|s.chroma_format_idc,248|s.bit_depth_luma_minus8,248|s.bit_depth_chroma_minus8,0,parseInt(s.frame_rate.fps),3|s.temporal_id_nested<<2|s.num_temporal_layers<<3|(s.frame_rate.fixed?64:0),i.length]);let n=r.length;for(let e=0;e<i.length;e+=1){n+=3;for(let t=0;t<i[e].length;t+=1)n+=2+i[e][t].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=i.length-1;for(let e=0;e<i.length;e+=1){a.set(new Uint8Array([32+e|(e===o?128:0),0,i[e].length]),n),n+=3;for(let t=0;t<i[e].length;t+=1)a.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),n),n+=2,a.set(i[e][t],n),n+=i[e][t].length}const l=e.box(zs.hvcC,a),h=t.width,d=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return e.box(zs.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,255&h,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,e.box(zs.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(zs.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}},Nr.FTYP=Cr.box(zs.ftyp,Fr,Ur,Fr,Br),Nr.DINF=Cr.box(zs.dinf,Cr.box(zs.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]))),$r=9e4,Gr=8589934592,Hr=class extends Bs{constructor(e,t,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?Ec(t):t} > ${e?Ec(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((e,i)=>{let r=i.pts,n=r-e;return n<-4294967296&&(t=!0,r=Tc(r,s),n=r-e),n>0?e:r},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o,l){let h,d,c,u,f,g,m=r,p=r;const v=!l.iframe&&e.pid>-1,y=t.pid>-1,S=t.samples.length,E=e.samples.length>0,b=a&&S>0||S>1;if((!v||E)&&(!y||b)||this.ISGenerated||a){if(this.ISGenerated){var T,w,I,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(w=e.pixelRatio)?void 0:w[0])||(null==(I=t.pixelRatio)?void 0:I[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&b||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const s=this.isVideoContiguous;let i,a=-1;if(b&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,a>0){this.warn(`Dropped ${a} out of ${S} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(E&&b&&r){const s=this.getVideoStartPts(t.samples),i=(Tc(e.samples[0].pts,s)-s)/t.inputTimeScale;m+=Math.max(0,i),p+=Math.max(0,-i)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,m,this.isAudioContiguous,n,y||b||o===Ps.AUDIO?p:void 0,l),b){const i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),h=this.remuxVideo(t,p,s,i,l)}}else b&&(h=this.remuxVideo(t,p,s,0,l));h&&(h.firstKeyFrame=a,h.independent=-1!==a,h.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=wc(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=Ic(i,r,this._initPTS))),{audio:d,video:h,initSegment:c,independent:g,text:u,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Tc(e,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r;)n+=Gr;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS,h=!l||i;let d,c,u,f="audio/mp4",g=-1;if(h&&(d=c=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Nr.initSegment([e]),metadata:{channelCount:e.channelCount}},h){g=e.id,u=e.inputTimeScale;const t=this.computeInitPts(r[0].pts,u,s,"audio");(!l||u!==l.timescale||0===s&&t<l.baseTime)&&(d=c=t)}}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Nr.initSegment([t]),metadata:{width:t.width,height:t.height}},h){g=t.id,u=t.inputTimeScale;const e=this.getVideoStartPts(n),i=Tc(n[0].dts,e),r=this.computeInitPts(i,u,s,"video"),a=this.computeInitPts(e,u,s,"video");(!l||u!==l.timescale||Ss(d)||0===s&&a<l.baseTime)&&(c=Math.min(c,r),d=Math.min(d,r))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h&&Ss(d)?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/u} (${d}/${u}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:u,trackId:g},this._initDTS={baseTime:c,timescale:u,trackId:g}):d=u=void 0,{tracks:o,initPTS:d,timescale:u,trackId:g}}remuxVideo(e,t,s,i,r){const n=e.inputTimeScale,a=e.samples,o=[],l=a.length,h=this._initPTS,d=h.baseTime*n/h.timescale;let c,u,f=this.nextVideoTs,g=8,m=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!s||null===f){const e=d+t*n,i=a[0].pts-Tc(a[0].dts,a[0].pts);lh()&&null!==f&&Math.abs(e-i-(f+d))<15e3?s=!0:f=e-i-d}const S=f+d;for(let e=0;e<l;e++){const t=a[e];t.pts=Tc(t.pts,S),t.dts=Tc(t.dts,S),t.dts<a[e>0?e-1:e].dts&&(y=!0)}y&&a.sort(function(e,t){const s=e.dts-t.dts,i=e.pts-t.pts;return s||i}),c=a[0].dts,u=a[a.length-1].dts;const E=u-c,b=E?Math.round(E/(l-1)):m||e.inputTimeScale/30;if(s){const s=c-S,i=s>b,r=s<-1;if((i||r)&&(i?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Sc(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Sc(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||S>=a[0].pts||lh())){c=S;const e=a[0].pts-s;if(i)a[0].dts=c,a[0].pts=e;else{let t=!0;for(let i=0;i<a.length&&!(a[i].dts>e&&t);i++){const e=a[i].pts;if(a[i].dts-=s,a[i].pts-=s,i<a.length-1){const s=a[i+1].pts;t=s<=a[i].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${Sc(e,!0)}/${Sc(c,!0)}, delta: ${Sc(s,!0)} ms`)}}c=Math.max(0,c);let T=0,w=0,I=c;for(let e=0;e<l;e++){const t=a[e],s=t.units,i=s.length;let r=0;for(let e=0;e<i;e++)r+=s[e].data.length;w+=r,T+=i,t.length=r,t.dts<I?(t.dts=I,I+=b/4|0||1):I=t.dts,p=Math.min(t.pts,p),v=Math.max(t.pts,v)}u=a[l-1].dts;const L=w+4*T+8;let A;try{A=new Uint8Array(L)}catch(e){return void this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MUX_ERROR,details:ws.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:e,bytes:L,reason:`fail allocating video mdat ${L}`})}Bl(A,0,L),Bl(A,4,zs.mdat);let k=!1,R=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let e=0;e<l;e++){const t=a[e],h=t.units;let c,u=0;for(let e=0,t=h.length;e<t;e++){const t=h[e],s=t.data,i=t.data.byteLength;Bl(A,g,i),g+=4,A.set(s,g),g+=i,u+=4+i}if(e<l-1)m=a[e+1].dts-t.dts,c=a[e+1].pts-t.pts;else{const s=this.config,r=e>0?t.dts-a[e-1].dts:b;if(c=e>0?t.pts-a[e-1].pts:b,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(s.maxBufferHole*n),a=(i?p+i*n:this.nextAudioTs+d)-t.pts;a>e?(m=a-r,m<0?m=r:k=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=r}else m=r}let f=Math.round(t.pts-t.dts);if(R=Math.min(R,m),P=Math.max(P,m),C=Math.min(C,c),D=Math.max(D,c),!s&&0===e&&f>m){const e=Math.round(f/b)*b;e-f===1&&(this.log(`pad first CTS ${f} -> ${e} of sn: ${r.sn}`),f=e)}o.push(bc(t.key,m,u,f))}if(o.length){const e=lh();if(e){if(e<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(function(){if(void 0===si){const e=Js.match(/Safari\/(\d+)/i);si=e?parseInt(e[1]):0}return si}()&&D-C<P-R&&b/P<.025&&0===o[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,s=o.length;t<s;t++){const i=e+o[t].duration,r=e+o[t].cts;if(t<s-1){const e=i+o[t+1].cts;o[t].duration=e-r}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=i}}}m=k||!m?b:m;const M=u+m;this.nextVideoTs=f=M-d,this.videoSampleDuration=m,this.isVideoContiguous=!0,r.iframe&&(1===o.length?(o[0].duration=m=r.duration*n,this.nextVideoTs=f=c+m-d):this.warn(`Not adjusting IFrame duration (sample count ${o.length})`));const _={data1:Nr.moof(r.sn,c,zo(e,{samples:o})),data2:A,startPTS:(p-d)/n,endPTS:(v+m-d)/n,startDTS:(c-d)/n,endDTS:f/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,_}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r,n){const a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),l=this.getSamplesPerFrame(e),h=l*o,d=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],f=void 0!==r;let g=e.samples,m=c?0:8,p=this.nextAudioTs||-1;const v=d.baseTime*a/d.timescale,y=v+t*a;if(this.isAudioContiguous=s=s||g.length&&p>0&&(i&&Math.abs(y-(p+v))<9e3||Math.abs(Tc(g[0].pts,y)-(p+v))<20*h),g.forEach(function(e){e.pts=Tc(e.pts,y)}),!s||p<0){const e=g.length;if(g=g.filter(e=>e.pts>=0),e!==g.length&&this.warn(`Removed ${g.length-e} of ${e} samples (initPTS ${v} / ${a})`),!g.length)return;p=0===r?0:i&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,i=p+v;s<g.length;s++){const r=g[s],n=r.pts,o=n-i,l=Math.abs(1e3*o/a);if(o<=-t*h&&f)0===s&&(this.warn(`Audio frame @ ${(n/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/a)} ms.`),this.nextAudioTs=p=n-v,i=n);else if(o>=t*h&&l<1e4&&f){let t=Math.round(o/h);for(i=n-t*h;i<0&&t&&h;)t--,i+=h;0===s&&(this.nextAudioTs=p=i-v),this.warn(`Injecting ${t} audio frames @ ${((i-v)/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);for(let n=0;n<t;n++){let t=Rr.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),g.splice(s,0,{unit:t,pts:i}),i+=h,s++}}r.pts=i,i+=h}}let S,E=null,b=null,T=0,w=g.length;for(;w--;)T+=g[w].unit.byteLength;for(let t=0,i=g.length;t<i;t++){const i=g[t],r=i.unit;let a=i.pts;if(null!==b)u[t-1].duration=Math.round((a-b)/o);else{if(s&&"aac"===e.segmentCodec&&(a=p+v),E=a,!(T>0))return;T+=m;try{S=new Uint8Array(T)}catch(e){return void this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MUX_ERROR,details:ws.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}c||(Bl(S,0,T),Bl(S,4,zs.mdat))}S&&S.set(r,m);const h=r.byteLength;m+=h,u.push(bc(!0,l,h,0)),b=a}const I=u.length;if(!I)return;const L=u[u.length-1];p=b-v,this.nextAudioTs=p+o*L.duration;const A=c?new Uint8Array(0):Nr.moof(e.sequenceNumber++,E/o,zo({},e,{samples:u}));e.samples=[];const k=(E-v)/a,R=this.nextAudioTs/a,C={data1:A,data2:S,startPTS:k,endPTS:R,startDTS:k,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}},Wr=class extends Bs{constructor(e,t,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=s||ql(e);if(t)!function(e,t){if(!e||!t)return;const s=t.keyId;16===(null==s?void 0:s.byteLength)&&t.isCommonEncryption&&Ql(e,(e,t)=>{const i=e.subarray(8,24);i.some(e=>0!==e)||(Gs.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Rl(i)} -> ${Rl(s)}`),e.set(s,8))})}(e,t);else{const e=n||a;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}n&&(i=Ac(n,Ds.AUDIO,this)),a&&(r=Ac(a,Ds.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n,a,o,l,h,d){var c,u;let{initPTS:f,lastEndTime:g}=this;const m={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};Ss(g)||(g=this.lastEndTime=r||0);const p=t.samples;if(!p.length)return m;const v=this.pendingInitSegment;v&&(this.pendingInitSegment=void 0,this.generateInitSegment(v,this.decryptdata,h));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let S=this.initData;if(null!=(c=S)&&c.length||(this.generateInitSegment(p),S=this.initData),null==(u=S)||!u.length)return this.warn("Failed to generate initSegment."),m;if(l.iframe&&S.audio&&S.video){var E;const e=null==(E=this.initTracks)||null==(E=E.audiovideo)?void 0:E.initSegment,t=e?function(e){const t=Gl(e,["moov"]);if(1!==t.length||Gl(e,["moof"]).length)return null;const s=e.byteOffset,i=[],r=[];let n=!1;const a=Gl(t[0],["trak"]);for(let e=0;e<a.length;e++){const t=a[e],o=Gl(t,["mdia","hdlr"])[0];if("vide"===(o?Dl(o.subarray(8,12)):"")){n=!0;continue}const l=Gl(t,["tkhd"])[0];if(!l)return null;const h=l[0];r.push(_l(l,0===h?12:20)),i.push(Nl(t,s))}if(!n||!i.length)return null;const o=Gl(t[0],["mvex"])[0];let l=0;if(o){const e=Gl(o,["trex"]);for(let t=0;t<e.length;t++){const n=e[t];-1!==r.indexOf(_l(n,4))&&(i.push(Nl(n,s)),l+=n.byteLength+8)}}const{result:h,dropped:d,droppedBefore:c}=$l(e,i);if(Bl(h,t[0].byteOffset-s-8,t[0].byteLength+8-d),o&&l){const e=o.byteOffset-s-8;Bl(h,e-c(e),o.byteLength+8-l)}return h}(e):null;var b;t&&(this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(t,this.decryptdata),null!=(b=this.initData)&&b.length&&(S=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0))}this.emitInitSegment&&(y.tracks=this.initTracks,m.initSegment=y,this.emitInitSegment=!1);const T=l.iframe,w=!d||T&&!d.includeSampleDetails?function(e,t,s,i,r=!0){return Zl(e,t,i,r)}(p,S,0,this,T):d.tracks,I=S.audio?w[S.audio.id]:null,L=S.video?w[S.video.id]:null,A=!!S.audio,k=!!S.video;let R="";A&&(R+="audio"),k&&(R+="video");const C=Lc(L,1/0),P=Lc(I,1/0),D=Lc(L,0,!0),M=Lc(I,0,!0);let _=r,O=0;L&&I&&S.audio&&(P>D||C>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${C}-${D} a: ${P}-${M}}`,L,I);const x=!!I&&(!L||!f&&P<C||!!f&&f.trackId===S.audio.id),F=x?I:L;if(!F)return this.log(`No media samples found in ${o} ${l.level} ${-1===l.part?"":`part: ${l.part} of`} sn: ${l.sn} at playlist time: ${r}`),m;let B,U=p;if(L&&L.sampleCount>=1&&S.video&&l.iframe){const{trun:e,start:t}=L,s=1===e.length,i=e.length?s?e[0].samples:e[0].samples.concat(...e.slice(1).map(e=>e.samples)):[];if(i.length){const r=e[0];let n=r;for(let t=e.length;t--;)if(e[t].samples.length){n=e[t];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,h=Math.abs(l.duration-(D-C))>.05,d=i.length<L.sampleCount;if(h||d||this.videoOnlyRemux||!s){const e=d?n.sampleOffset+n.samples.reduce((e,t)=>e+t.size,0):void 0,s=h?l.duration:D-C,r=function(e,t,s,i){if(void 0!==s){const i=e[e.length-1];let r=t;for(let t=0;t<e.length-1;t++)r-=e[t].duration;return r<=0&&(r=i.duration),i.duration=r,{durationOffset:s,value:r}}if(void 0===i)return;const r=Math.round(t/e.length);for(let t=0;t<e.length;t++)e[t].duration=r;return{durationOffset:i,value:r}}(i,s*S.video.timescale,a,o),c=function(e,t,s,i,r){if(s<1)return null;const n=Gl(e,["moof"]);if(1!==n.length)return null;const a=n[0],o=e.byteOffset,l=[],h=[],d=Gl(a,["traf"]);let c=!0;for(let e=0;e<d.length;e++){const s=d[e],i=Gl(s,["tfhd"])[0];if(!i)return null;_l(i,4)===t?(l.push(s),131072&_l(i,0)||(c=!1)):h.push(Nl(s,o))}if(!l.length)return null;if(h.length&&!c)return null;if(void 0!==i){let t=s;for(let s=0;s<l.length;s++){const i=l[s];let r=0;const n=Gl(i,["trun"]);for(let s=0;s<n.length;s++){const i=n[s],a=Math.min(t,_l(i,4));if(a){Bl(e,i.byteOffset-o+4,a);const t=16777215&_l(i,0);Ul(e,i,8+(1&t?4:0)+(4&t?4:0)+a*((256&t?4:0)+(512&t?4:0)+(1024&t?4:0)+(2048&t?4:0)))}else Bl(e,i.byteOffset-o-4,zs.free);t-=a,r+=a}const a=Gl(i,["senc"])[0];a&&Bl(e,a.byteOffset-o+4,r);const h=Gl(i,["saiz"])[0];if(h){let t=4;1&(h[1]<<16|h[2]<<8|h[3])&&(t+=8);const s=h[t];t+=1,Bl(e,h.byteOffset-o+t,r),Ul(e,h,t+4+(0===s?r:0))}}const r=Gl(e,["mdat"]);if(1===r.length){const t=r[0].byteOffset-o-8;Bl(e,t,i-t)}}let u=e,f=0,g=()=>0;if(h.length){({result:u,dropped:f,droppedBefore:g}=$l(e,h)),Bl(u,a.byteOffset-o-8,a.byteLength+8-f);for(let e=0;e<l.length;e++){const t=l[e],s=g(t.byteOffset-o),i=Gl(t,["trun"]);for(let e=0;e<i.length;e++){const t=i[e];1&_l(t,0)&&Bl(u,t.byteOffset-o-s+8,_l(t,8)-f)}if(s){const e=Gl(t,["saio"]);for(let t=0;t<e.length;t++){const i=e[t],r=0===i[0]?4:8;let n=1&_l(i,0)?12:4,a=_l(i,n);for(n+=4;a--;n+=r){const e=n+r-4;Bl(u,i.byteOffset-o-s+e,_l(i,e)-s)}}}}}if(r){const{durationOffset:e,value:t}=r;Bl(u,e-g(e),t)}return void 0!==i?u.subarray(0,i-f):u}(p,S.video.id,i.length,e,r);c?(U=c,B=function(e,t){let s=e,i=e;for(let e=0;e<t.length;e++){const{cts:r,duration:n}=t[e];i=Math.max(i,s+(r||0)+n),s+=n}return i}(t,i)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),O=c&&r?s:D-C}else O=D-C}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${e.length})`),O=D-C}else O=x?M-P:D-C;if(this.videoOnlyRemux&&U===p)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),m;const N=F.timescale,$=F.start-r*N,G=x?S.audio.id:S.video.id;if(_=F.start/N,(n||!f)&&(function(e,t,s,i){if(null===e)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>=r}(f,_,r,O)||N!==f.timescale)){let e=!1;const t=x?"audio":"video";if(f){const s=0!==r?_/r:1+_/1;e=_>=0&&Math.abs(1-s)<.001,this.log(`${t} timestamps in track ${G} at playlist time: ${n?"":"~"}${r} maps to ${_} with initPTS: ${f.baseTime/f.timescale} (${$/N-f.baseTime/f.timescale}s diff) (${R}) drift estimate: ${s} ${e?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}e||(this.log(`Found initPTS in ${t} track ${G} at playlist time: ${r} offset: ${_-r} (${$}/${N})`),f=null,y.initPTS=$,y.timescale=N,y.trackId=G)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=_,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const H=_-f.baseTime/f.timescale,W=H+O,q=k&&void 0!==(null==F?void 0:F.ptsMin)?F.ptsMin/F.timescale-f.baseTime/f.timescale:H,j=void 0!==B&&L?B/L.timescale-f.baseTime/f.timescale:k&&null!=F&&F.ptsMax?F.ptsMax/F.timescale-f.baseTime/f.timescale:W;O>0?this.lastEndTime=W:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K={data1:U,data2:void 0,startPTS:q,startDTS:H,endPTS:j,endDTS:W,type:R,hasAudio:A,hasVideo:k,nb:1,dropped:0,encrypted:!!S.audio&&S.audio.encrypted||!!S.video&&S.video.encrypted};m.audio=A&&!k?K:void 0,m.video=k?K:void 0;const V=this.isVideoContiguous,Y=null==L?void 0:L.sampleCount;if(Y){const e=L.keyFrameIndex,t=-1!==e;K.nb=Y,K.dropped=0===e||V?0:t?e:Y,K.independent=t,K.firstKeyFrame=e,t&&L.keyFrameStart&&(K.firstKeyFramePTS=(L.keyFrameStart-f.baseTime)/f.timescale),V||(m.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),K.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${Y} dropped: ${K.dropped} start: ${K.firstKeyFramePTS||"NA"}`)}return m.initSegment=y,m.id3=wc(s,r,f,f),i.samples.length&&(m.text=Ic(i,r,f)),m}};try{qr=self.performance.now.bind(self.performance)}catch(e){qr=Date.now}(jr=[{demux:Er,remux:Wr},{demux:Ar,remux:Hr},{demux:mr,remux:Hr},{demux:yr,remux:Hr}]).splice(2,0,{demux:vr,remux:Hr}),Kr=class{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){if(!this.observer)return Vr(s);const r=s.transmuxing;r.executeStart=qr();const n=new Uint8Array(e),{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,S=function(e,t){let s=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t),s}(n,t);if(S&&ld(S.method)){const e=this.getDecrypter(),t=hd(S.method);return this.asyncResult=!0,this.decryptionPromise=e.decrypt(n,S.key.buffer,S.iv.buffer,t,s.decryptRange).then(e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t}),this.decryptionPromise}const E=this.needsProbing(h,d);if(E){const e=s.iframe&&y&&Ar.probe(y,this.logger)?y:n,t=this.configureTransmuxer(e);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(Is.ERROR,Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=qr(),Vr(s)}(h||d||f||E)&&this.resetInitSegment(y,g,m,v,t,s),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const b=this.transmux(n,S,u,c,s);this.asyncResult=kc(b);const T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,r.executeEnd=qr(),b}flush(e){const t=e.transmuxing;t.executeStart=qr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=qr();const s=[Vr(e)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a,e);return kc(h)?(this.asyncResult=!0,h.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=qr()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(e,t,s,i,r,n),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,s,i,r){let n;return n="SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Vr(i);const a=r.demux(e,t,i,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:h,textTrack:d}=a;return{remuxResult:n.remux(o,l,h,d,t,s,!1,this.id,i,a.initData,a.sampleData),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,r).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,i,!1,this.id,r,e.initData,e.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let t=0,s=jr.length;t<s;t++){var n;if(null!=(n=jr[t].demux)&&n.probe(e,this.logger)){r=jr[t];break}}}catch(e){return e}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,h=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(s,t,i,this.logger),this.probe=l.probe),o&&o instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(s,t,i,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ai(this.config)),e}},Vr=e=>({remuxResult:{},chunkMeta:e}),Yr=class{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},zr=class{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}},Qr=0,Xr=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Qr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Is.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new rr,this.observer.on(Is.FRAG_DECRYPTED,n),this.observer.on(Is.ERROR,n);const a=Eh(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=ar[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return ar[e]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=ar[nr];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return ar[nr]=i,i}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:gi(r)})}catch(i){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Kr(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Kr(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Qr++;const t=this.hls.config,s=Eh(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:gi(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=ar[e||nr];if(t&&1===t.clientCount--){const{worker:s,objectURL:i}=t;delete ar[e||nr],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!p||r.cc!==p.cc,y=!p||l.level!==p.level,S=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,b=0===S&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),T=!y&&(1===S||0===S&&(1===E||b&&E<=0)),w=self.performance.now();(y||S||0===r.stats.parsing.start)&&(r.stats.parsing.start=w),!n||!E&&T||(n.stats.parsing.start=w);const I=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),L=new zr(v,T,o,y,g,I);if(!T||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${T}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const e=new Yr(s,i,t,a,h);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,L);kc(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);kc(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Jr=class extends er{constructor(e,t,s){super(e,t,s,"audio-stream-controller",Ps.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Is.BUFFER_RESET,this.onBufferReset,this),e.on(Is.BUFFER_CREATED,this.onBufferCreated,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Is.BUFFER_RESET,this.onBufferReset,this),e.off(Is.BUFFER_CREATED,this.onBufferCreated,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){const{frag:s,id:i,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=t;if(i===Ps.MAIN){const e=s.cc,t=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${e} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=s,this.state===Zi.WAITING_INIT_PTS){const t=this.waitingData;(!t&&!this.loadingParts||t&&t.frag.cc!==e)&&this.syncWithAnchor(s,null==t?void 0:t.frag)}else!this.hls.hasEnoughToStart&&t&&t.cc!==e?(t.abortRequests(),this.syncWithAnchor(s,t)):this.state===Zi.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(e=this.switchingTrack)?void 0:e.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(t&&(null==i?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=Wh(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===Zi.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Zi.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=Zi.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case Zi.IDLE:this.doTickIdle();break;case Zi.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Zi.WAITING_INIT_PTS}break}case Zi.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Zi.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Zi.FRAG_LOADING;const e={frag:t,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=Zi.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Zi.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ds.AUDIO));const h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(Is.BUFFER_EOS,{type:"audio"}),void(this.state=Zi.ENDED);const d=h.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:h.end;if(this.switchingTrack&&i){const e=g;o.PTSKnown&&e<f&&e>=this.timelineOffset&&(h.end>f||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${e} -> ${f} + 0.05`),i.currentTime=f+.05)}if(d>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,h,Ps.MAIN,c)),!p)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,c,p))return;let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Wo(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ei.OK&&(this.mainFragLoading=v=null),v&&Wo(v))){if(p.start>v.end){const e=this.fragmentTracker.getFragAtPos(m,Ps.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>v.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new ui(e))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Zi.STOPPED&&(this.setInterval(100),this.state=Zi.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Is.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=t;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Zi.STOPPED&&(this.state=Zi.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||null!=(s=h.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var c;h.details&&(d=this.alignPlaylists(r,h.details,null==(c=this.levelLastLoaded)?void 0:c.details)),r.alignedSliding||(qd(l,r,this),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(Is.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==Zi.WAITING_TRACK||this.waitForCdnTuneIn(r)||(this.state=Zi.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Xr(this.hls,Ps.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=i?i.index:-1,n=-1!==t,a=new Di(s.level,s.sn,s.stats.chunkCount,r.byteLength,t,n,s.duration);c.push(r,f,d,"",s,i,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new tr,complete:!1};e.push(new Uint8Array(r)),this.state!==Zi.STOPPED&&(this.state=Zi.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Ps.MAIN&&Wo(t.frag)&&(this.mainFragLoading=t,this.state===Zi.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type===Ps.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Wo(s)){const e=this.switchingTrack;e&&(this.bufferedTrack=e)}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==Ps.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,Ps.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const t=this.fragPlaying,s=null==e?void 0:e.level;return t&&t.level===s||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var s;if(t.fatal)this.state=Zi.ERROR;else switch(t.details){case ws.FRAG_GAP:case ws.FRAG_PARSING_ERROR:case ws.FRAG_DECRYPT_ERROR:case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ps.AUDIO,t);break;case ws.AUDIO_TRACK_LOAD_ERROR:case ws.AUDIO_TRACK_LOAD_TIMEOUT:case ws.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Zi.WAITING_TRACK||(null==(s=t.context)?void 0:s.type)!==Cs.AUDIO_TRACK||(this.state=Zi.IDLE);break;case ws.BUFFER_APPEND_NO_PROGRESS:if("audio"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ws.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ws.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==Ds.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Ds.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Zi.ENDED&&(this.state=Zi.IDLE);const e=this.getBufferOutput();e&&(this.afterBufferFlushed(e,t),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(this.fragContextChanged(o)||!d)return this.fragmentTracker.removeFragment(o),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=Zi.PARSING,c&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:e}=this,t=e.nextAudioTrackBufferFlushForwardOffset,s=Math.max(this.getLoadPosition()+t,o.start);super.flushMainBuffer(s,Number.POSITIVE_INFINITY,Ps.AUDIO)}if(null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,e,n),i.trigger(Is.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[Ds.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(Ds.AUDIO,e,t,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=zo({id:s,frag:o,details:d},f);i.trigger(Is.FRAG_PARSING_METADATA,e)}if(u){const e=zo({id:s,frag:o,details:d},u);i.trigger(Is.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,s,i){if(this.state!==Zi.PARSING)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=Ps.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(Is.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(Is.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||i===Ei.NOT_LOADED||i===Ei.PARTIAL)if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Zi.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&qd(s,t.details,this)}else super.loadFragment(e,t,s);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Oh({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},e,xh)||(Bh(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Is.AUDIO_TRACK_SWITCHED,Xo({},e))}get nextAudioTrack(){return this.nextTrackId}},Zr=class extends Bs{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=null==t?void 0:t.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){const e=i[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&Rh(s);return new ci(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=i.fragments,a=self.performance.now(),o=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;i.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const e=Math.max(l||0,0);i.appliedTimelineOffset=e,n.forEach(t=>{null==t||t.setStart(t.playlistOffset+e)})}if(i.live||null!=s&&s.live){var h;const l="levelInfo"in t?t.levelInfo:t.track;i.reloaded(s);const d=null==(h=n[n.length-1])?void 0:h.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const e=new Error(`${d} playlist ${l.id} hit max allowed unchanged reloads.`);this.warn(e);const{networkDetails:s,context:n}=t;return void this.hls.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level,parent:d,context:n,networkDetails:s,stats:r})}if(s){!function(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){i=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,s){var i;const r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let i=n;i<=a;i++){const n=h[o+i];let a=l[i];if(r&&!a&&n&&(a=t.fragments[i]=n),n&&a){s(n,a,i,l);const r=n.relurl,o=a.relurl;if(r&&Nd(r,o))return void(t.playlistParsingError=Md(`media sequence mismatch ${a.sn}:`,e,t,0,a));if(n.cc!==a.cc)return void(t.playlistParsingError=Md(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,e,t,0,a))}}}(e,t,(e,s,r,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const i=e.cc-s.cc;for(let e=r;e<a.length;e++)a[e].cc+=i;t.endCC=a[a.length-1].cc}Ss(e.startPTS)&&Ss(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=zo({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;return a?(Object.keys(i).forEach(e=>{const t=n[e],r=new Ui(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${gi(i[e].attr)}"`)}),n):i}(e.dateRanges,t,s));const i=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&Ld(o[e],o[e-1],i);Sd(i,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=xd(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}(function(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<n;r++){const n=e[r],a=t[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}})(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),n?(t.iframesOnly&&(n.type,Ps.MAIN),Dd(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,0,s)):_d(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(s,i,this);const e=i.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){const{networkDetails:n}=t;return void s.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:e,reason:e.message,level:t.level,parent:d,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,f=Od(i,1e3*(i.edge-u));i.requestScheduled+f<a?i.requestScheduled=a:i.requestScheduled<=a&&(i.requestScheduled+=f);const g=t.deliveryDirectives;if(this.log(`live playlist ${e} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${g?` | requested ${g.msn} - ${g.part}`:""})`}`),!this.canLoad||!i.live)return;let m,p,v;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,o=i.lastPartIndex,h=r===n;-1!==o?h?(p=n+1,v=e?0:o):(p=r,v=e?o+1:i.maxPartIndex):p=n+1;const d=i.age,c=d+i.ageHeader;let u=Math.min(c-i.partTarget,1.5*i.targetduration);if(u>0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${u} with playlist age: ${i.age}`),u=0;else{const e=Math.floor(u/i.targetduration);p+=e,void 0!==v&&(v+=Math.round(u%i.targetduration/i.partTarget)),this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${u} skip sn ${e} to part ${v}`)}i.tuneInGoal=u}if(m=this.getDeliveryDirectives(i,t.deliveryDirectives,p,v),e||!h)return i.requestScheduled=a,void this.loadingPlaylist(l,m)}else(i.canBlockReload||i.canSkipUntil)&&(m=this.getDeliveryDirectives(i,t.deliveryDirectives,p,v));m&&void 0!==p&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(l,m,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,i){let r=Rh(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=di.No),new ci(s,i,r)}checkRetry(e){const t=e.details,s=Zo(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===vi.RetryRequest||!i.resolved&&r===vi.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;const s=al(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),s)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const e=il(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),e)}}e.levelRetry=!0,i.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),al(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}},en=class extends Zr{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(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Is.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>Uh(e.groupId,s));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const s=_h(t,e,xh);if(s>-1)r=e[s];else{const e=_h(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(Is.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.AUDIO_TRACK&&t.context.id===this.trackId&&Uh(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Oh(e,i,xh))return i;const r=_h(e,this.tracksInGroup,xh);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),t}if(i){let i=t.loadLevel;-1===i&&(i=t.firstAutoLevel);const r=function(e,t,s,i,r){const n=t[i],a=t.reduce((e,t,s)=>{const i=t.uri;return(e[i]||(e[i]=[])).push(s),e},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Fh(t,i,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const i=t.audioGroups,n=s.filter(e=>Uh(e.groupId,i));return _h(e,n,r)>-1});return d>-1?d:Fh(t,i,t=>{const i=t.audioGroups,n=s.filter(e=>Uh(e.groupId,i));return _h(e,n,r)>-1})}(e,t.levels,s,i,xh);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=_h(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e,t=!0){const s=this.tracksInGroup;if(e<0||e>=s.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Is.AUDIO_TRACK_SWITCHING,Xo(Xo({},r),{},{flushImmediate:t})),n)return;const a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||Oh(e,i,xh)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++)if(Oh({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],xh))return e;for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Bh(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(Is.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},tn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[t];i.push(e),1!==i.length||s||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"===s||"async-blocker-prepend"===s?(e[0].execute(),e.splice(0,1)):"block-audio"===s&&e.splice(0,1)})}insertNext(e,t){null!==this.queues&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(e=>"block-audio"===e.label)}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){var s;if(i.onError(t),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[e])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}},sn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rn="HlsJsTrackRemovedError",nn=.001,an=class extends Error{constructor(e){super(e),this.name=rn}},on=class extends Bs{constructor(e,t){var s;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(Kd(s,"sourceopen",this._onMediaSourceOpen),Kd(t,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Is.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const e=this.media.error,{appendError:t,appendErrors:s}=this;let i=!1;!t&&e&&(i=Math.max(++s.audio,++s.video,++s.audiovideo)>=this.hls.config.appendErrorMaxRetry);const r=new Error(`MediaSource closed while media attached${Mc(i,e)}`);this.warn(r),this.hls.trigger(Is.ERROR,zo({fatal:i},t,{type:Ts.MEDIA_ERROR,details:ws.MEDIA_SOURCE_REQUIRES_RESET,error:r}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this._onMediaError=()=>{const{media:e}=this;var t,s;e&&this.log(`Media error (code: ${null==(t=e.error)?void 0:t.code}): ${null==(s=e.error)?void 0:s.message}`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(s=dl(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.BUFFER_RESET,this.onBufferReset,this),e.on(Is.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Is.BUFFER_EOS,this.onBufferEos,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.FRAG_PARSED,this.onFragParsed,this),e.on(Is.FRAG_CHANGED,this.onFragChanged,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.BUFFER_RESET,this.onBufferReset,this),e.off(Is.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.BUFFER_EOS,this.onBufferEos,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.FRAG_PARSED,this.onFragParsed,this),e.off(Is.FRAG_CHANGED,this.onFragChanged,this),e.off(Is.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===t?zo(s,i.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(s[t]=zo({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=dl(this.appendSource);if(i){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(r),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&r instanceof t,Pc(s),function(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e}jd(s,"emptied",this._onMediaEmptied),jd(s,"error",this._onMediaError)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),jd(e,"sourceopen",this._onMediaSourceOpen),jd(e,"sourceended",this._onMediaSourceEnded),jd(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(jd(e,"startstreaming",this._onStartStreaming),jd(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${gi(s,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${gi(i,(e,t)=>"initSegment"===e?void 0:t)}}`),!cl(i,s)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(Is.MEDIA_DETACHING,{}),this.onMediaAttaching(Is.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,s=i[t];if(s){const e=s.buffer;if(e){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=_i.getBuffered(e);i.detectEvictedFragments(t,s,r,null,null,!0)}const n=Dc(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),r.removeSourceBuffer(t[s]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Kd(r,"sourceopen",this._onMediaSourceOpen),Kd(r,"sourceended",this._onMediaSourceEnded),Kd(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Kd(r,"startstreaming",this._onStartStreaming),Kd(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Kd(i,"emptied",this._onMediaEmptied),Kd(i,"error",this._onMediaError),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Pc(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Dc(e)]=[null,null];const t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new tn(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!i[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var s,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=i[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=i[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=vh(m,p),y=null==v?void 0:v.replace(sn,"$1");let S=vh(o,l);const E=null==(r=S)?void 0:r.replace(sn,"$1");S&&v&&y!==E&&("audio"===e.slice(0,5)&&(S=ph(S,this.appendSource)),this.log(`switching codec ${m} to ${S}`),S!==(u.pendingCodec||u.codec)&&(u.pendingCodec=S),u.container=h,this.appendChangeType(e,h,S))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,Ps.MAIN))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e,t;(this.lastVideoAppendEnd>i||_i.isBuffered(null==(e=this.tracks.video)?void 0:e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,Ps.MAIN))?void 0:t.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,d=l.buffering[r],c=Wo(a)&&!o&&!a.gap&&!l.partial&&!l.iframe;let u=null,f=!1;const{sn:g,cc:m}=a,p=self.performance.now();d.start=p;const v=a.stats.buffering,y=o?o.stats.buffering:null;0===v.start&&(v.start=p),0===(null==y?void 0:y.start)&&(y.start=p);const S=s.audio;let E=!1;"audio"===r&&"audio/mpeg"===(null==S?void 0:S.container)&&(E=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const b=s.video,T=null==b?void 0:b.buffer;if(T&&"initSegment"!==g&&void 0!==h){const e=null==S?void 0:S.buffer,t=o||a;if("audio"===r&&"main"!==n&&!b.ending&&!b.ended&&e&&_i.getBuffered(e).length){const e=t.start+.05*t.duration,s=_i.getBuffered(T),i=this.currentOp("video");s.length||i?!_i.isBuffered(T,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}else if("video"===r){const e=t.end,s=this.lastVideoAppendEnd-e;this.lastVideoAppendEnd=e,s<0||s>t.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const w=(o||a).start,I={label:`append-${r}`,execute:()=>{var e;d.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(c&&(u=_i.timeRangesToArray(_i.getBuffered(t)),f=xc(Oc(u,a),a)),E?this.updateTimestampOffset(t,w,.1,r,g,m):void 0!==h&&Ss(h)&&this.updateTimestampOffset(t,h,1e-6,r,g,m)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const e=self.performance.now();d.executeEnd=d.end=e,0===v.first&&(v.first=e),0===(null==y?void 0:y.first)&&(y.first=e);const t={};if(this.sourceBuffers.forEach(([e,s])=>{e&&(t[e]=_i.getBuffered(s))}),c){const e=this.getFragmentAppendProgress(a),s=t[r];if(s&&u){const t=Oc(_i.timeRangesToArray(s),a);e.progressed||(e.progressed=t-Oc(u,a)>nn);const i=f&&xc(t,a);e.fullyBuffered[r]=(void 0===e.fullyBuffered[r]||e.fullyBuffered[r])&&i}}this.hls.trigger(Is.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:n,timeRanges:t})},onError:e=>{var t;this.clearBufferAppendTimeoutId(this.tracks[r]);const s=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(s&&!this._quotaEvictionPending[r]){const e=this.getBackBufferEvictionTarget(r,i.byteLength,a.type);if(e>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${e.toFixed(3)}s and retrying`);const t=this.getFlushOp(r,0,e),s=this.getClearEvictionPendingOp(r);return void this.insertNext([t,I,s],r)}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}c&&(this.getFragmentAppendProgress(a).errored=!0);const h={type:Ts.MEDIA_ERROR,parent:n,details:ws.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},d=null==(t=this.media)?void 0:t.error;if(e.name!==rn||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var u;s&&(h.details=ws.BUFFER_FULL_ERROR);const t=++this.appendErrors[r],i=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${t}/${i+1} times to append segment in "${r}" sourceBuffer with error: ${e.message}`),t>=i&&(h.fatal=!s);const n=null==(u=this.mediaSource)?void 0:u.readyState;("ended"===n||"closed"===n||d)&&(this.warn(`MediaSource readyState "${n}" during SourceBuffer${Mc(h.fatal,d)}`),h.details=ws.MEDIA_SOURCE_REQUIRES_RESET)}else h.errorAction=Vh(!0);this.appendError=h,this.hls.trigger(Is.ERROR,h),s&&this.hls&&this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${o?" p: "+o.index:""} of ${n} playlist ${a.level} cc: ${m} offset: ${h} bytes: ${i.byteLength}`),this.append(I,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var i;const r=null==(i=this.tracks[e])?void 0:i.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${r?Vd(_i.getBuffered(r)):"(detached)"}`),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s&&"audio"!==s||this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,i,r),e)})}onFragParsed(e,t){const{frag:s,part:i,chunkMeta:r}=t,n=[],a=i?i.elementaryStreams:s.elementaryStreams;a[Ds.AUDIOVIDEO]?n.push("audiovideo"):(a[Ds.AUDIO]&&n.push("audio"),a[Ds.VIDEO]&&n.push("video")),0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(()=>{const e=self.performance.now();s.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,n),this.hls&&(this.hls.trigger(Is.FRAG_BUFFERED,{frag:s,part:i,stats:t,id:s.type,chunkMeta:r}),!i&&s.gap&&t.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${t.retry}`))},n).catch(e=>{this.warn(`Fragment buffered callback ${e.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,t.frag,t.previousFrag);const o=t.frag.elementaryStreams,{appendErrors:l}=this,h=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(o).forEach(e=>{o[e]&&(l[e]=0,e===h&&(this.appendError=void 0),"audio"===e||"video"===e?(l.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}});const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;"open"===(null==e?void 0:e.readyState)?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Is.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(Is.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===ws.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;Ss(e)&&e!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,t):0}getFragmentAppendProgress(e){var t;const s=_c(e);let i=this.fragmentAppendProgress[s];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(e,t,s,i){if(t||!Wo(e)||e.gap||s.iframe||s.partial)return;const r=_c(e),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const a=(null==n?void 0:n.stats)===e.stats?n:void 0;if(null!=a&&a.errored)return;const o=i.length>0&&i.every(e=>!0===(null==a?void 0:a.fullyBuffered[e]));if(null!=a&&a.progressed||o)return void delete this.appendsWithoutProgress[r];if(!a&&0===i.length)return;const l=(this.appendsWithoutProgress[r]||0)+1,h=this.hls;l>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=l,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${l} time${l>1?"s":""} without buffered range growth`),h.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:l,error:new Error(`Fragment append did not increase buffered coverage (${l})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,s,i){const{hls:r,details:n,media:a}=this;if(!a||null===n)return;if(!this.sourceBufferCount)return;const o=r.config,l=a.currentTime,h=n.levelTargetDuration;t=n.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;let d=-1/0;if(Ss(t)&&t>=0){const e=Math.max(t,h);d=Math.floor(l/h)*h-e}if(s){const e=this.getLoopBackBufferFlushEnd(s,null!=i?i:null);e>0&&(d=Math.max(d,e))}if(d>0&&this.flushBackBuffer(l,h,d),Ss(e)&&e>0){const t=Math.max(o.maxBufferLength,e),s=Math.max(t,h),i=Math.floor(l/h)*h+s;this.flushFrontBuffer(l,h,i)}}getLoopBackBufferFlushEnd(e,t){var s;const{media:i}=this;if(!1===(null==(s=this.hls)?void 0:s.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;const{video:r,audiovideo:n}=e.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(e)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(e){const{audio:t,video:s,audiovideo:i}=e.elementaryStreams;let r=e.start;return i?r=Math.min(r,i.startDTS):(t&&(r=Math.min(r,t.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([e,t])=>{if(t){const a=_i.getBuffered(t);if(a.length>0&&s>a.start(0)){var i,r,n;this.hls.trigger(Is.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(i=this.details)&&i.live)this.hls.trigger(Is.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([t,i])=>{if(i){const r=_i.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,i)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return Ss(r)?{duration:r}:null;const n=this.media.duration;return i>(Ss(s.duration)?s.duration:0)&&i>n||!Ss(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==e&&(Ss(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${gi(s)}`),this.tracksReady){var i;const e=null==(i=this.transferData)?void 0:i.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(Is.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${gi(a)}`);try{const e=s.addSourceBuffer(r),i=Dc(n),o=[n,e];t[i]=o,a.buffer=e}catch(e){var i;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&("video"===t||"audiovideo"===t)&&ch(s,"video")&&(i=function(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)dh(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}(i,s));const r=vh(i,e.levelCodec);return r?"audio"===t.slice(0,5)?ph(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const s=t.removedRanges;null!=s&&s.length&&(this.log(`${e} buffer removed ${Vd(s)}`),this.hls.trigger(Is.BUFFER_FLUSHED,{type:e,start:s.start(0),end:s.end(s.length-1)}))})}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);if(i){if(i.onComplete(),null==(s=this.tracks[e])||null==(s=s.buffer)?void 0:s.updating)return this.log(`${e} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}onSBUpdateError(e,t){var s;const i=null==(s=this.mediaSource)?void 0:s.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);this.error(`${r.message}`,t),this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!r||!a)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const o=Ss(i.duration)?i.duration:1/0,l=Ss(r.duration)?r.duration:1/0,h=Math.max(0,t);var d;if(h>=l)return null==(d=this.currentOp(e))||d.onComplete(),void this.shiftAndExecuteNext(e);const c=Math.min(s,o,l);if(!(c>h)||n.ending&&!n.ended)throw new Error(`Cannot remove ${c<=h?`invalid range (${h} >= ${c}) `:""}from the ${e} SourceBuffer${n.ending?" while track ending":""}`);n.ended=!1,this.log(`Removing [${h},${c}] from the ${e} SourceBuffer`),a.remove(h,c)}appendExecutor(e,t){const s=this.tracks[t],i=null==s?void 0:s.buffer;if(!i)throw new an(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const e=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,i,e),e)}i.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch(t){this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=10;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(null===this.media)return s;const i=_i.bufferInfo(e,this.media.currentTime,0);return i.len?(s=Math.max(1e3*i.len,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=2===t.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(e=>this.appendBlocker(e));return Promise.all(i).then(t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;!s||s.updating||"audio"===e&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),jd(r,t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(e=>{Kd(s,e.event,e.listener)}),t.listeners.length=0)}},ln=class e{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:e}=this;e&&(e.on(Is.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:e}=this;e&&(e.off(Is.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){const s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping()}onLevelsUpdated(e,{levels:t}){(this.timer||this.observer)&&Ss(this.autoLevelCapping)?this.detectPlayerSize():void 0===this.observer&&void 0===this.timer&&t.length>1&&t.some(e=>!!e.videoCodec)&&this.startCapping()}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const e=this.hls.levels;if(e.length>1){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const s=this.hls.levels;if(!s.length)return-1;const i=s.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(e=>{var t;const s=null==(t=e[0])?void 0:t.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;const i=(e,t)=>!t||e.width!==t.width||e.height!==t.height;let r=e.length-1;const n=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=n||s.height>=n)&&i(s,e[t+1])){r=t;break}}return r}},hn=class e{constructor(t,s){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=s}},dn="Dict",cn="Bare Item",un="Boolean",fn="Byte Sequence",gn="Decimal",mn="Integer",pn="String",vn=/[\x00-\x1f\x7f]+/,yn=class{constructor(e){this.description=e}},Sn="Token",En="Key",bn=["url"],Tn=["version","eventTargets","sid","transmissionMode"],wn=["customData","headers"],In=e=>e instanceof hn?new hn(Math.round(e.value),e.params):Math.round(e),An=(e,t)=>Array.isArray(e)?e.map(e=>An(e,t)):e instanceof hn&&"string"==typeof e.value?new hn(An(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let s;try{s=new URL(e)}catch(t){return e}const i=new URL(t);if(s.origin!==i.origin)return e;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let e=0;e<a&&r[e]===n[e];e++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}(e,function(e){const t="string"==typeof e?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}(t.baseUrl))),1===t.version?encodeURIComponent(e):e),kn=e=>e instanceof hn?new hn(100*Math.round(e.value/100),e.params):100*Math.round(e/100),Cn={br:Ln=e=>Array.isArray(e)?e.map(In):In(e),d:Ln,bl:Rn=e=>Array.isArray(e)?e.map(kn):kn(e),dl:Rn,mtp:Rn,nor:(e,t)=>{let s=e;return t.version>=2&&(e instanceof hn&&"string"==typeof e.value?s=new hn([e]):"string"==typeof e&&(s=[e])),An(s,t)},rtp:Rn,tb:Ln},Pn=2,Dn="pr",Mn="b",xn={BITRATE_CHANGE:"bc",ERROR:"e",RESPONSE_RECEIVED:_n="rr",CUSTOM_EVENT:On="ce"},Fn=new Map([["ps","sta"],[Dn,"pr"],["c","cid"],[Mn,"bg"],["bc","br"]]),Bn="event",Un="request",Nn=["cen","e","h","ts"],$n=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Gn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,Hn=new Set($n),Wn=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],qn=new Set(Wn),jn=new Set(Nn),Kn=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Vn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Yn=new Set(Vn),zn=new Set(["ot","sf","st","e","sta"]),Qn={[Bn]:Yc,[Un]:Kc},ta={REQUEST:Jn="CMCD-Request"},sa={ab:Xn="CMCD-Object",br:Xn,d:Xn,lab:Xn,lb:Xn,ot:Xn,tab:Xn,tb:Xn,tpb:Xn,bl:Jn,cs:Jn,dfa:Jn,dl:Jn,ltc:Jn,mtp:Jn,nor:Jn,nrr:Jn,pb:Jn,sn:Jn,sta:Jn,su:Jn,tbl:Jn,cid:Zn="CMCD-Session",msd:Zn,sf:Zn,sid:Zn,st:Zn,v:Zn,bg:ea="CMCD-Status",bs:ea,bsa:ea,bsd:ea,bsda:ea,cdn:ea,ec:ea,nr:ea,pr:ea,pt:ea,rtp:ea},ia="CMCD",ra=[...Vn,...$n,...Wn,...Nn].filter((e,t,s)=>s.indexOf(e)===t),na={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},aa={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},oa="query",la="headers",ha=Object.is,da=e=>e,ca=Array.from(Fn,([e,t])=>"br"===t?{event:e,field:t,equal:(e,t)=>void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++){const i=e[s],r=t[s];if(i===r)continue;if("number"==typeof i||"number"==typeof r)return!1;if(i.value!==r.value)return!1;const n=i.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(e,t),snapshot:e=>e.slice()}:{event:e,field:t,equal:ha,snapshot:da}),ua=new Map(ca.map(e=>[e.event,e])),fa=class{constructor(e,t=su){var s;this.timeOrigin=performance.timeOrigin||(null==(s=performance.timing)?void 0:s.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){const{version:t=Pn,eventTargets:s=[],sid:i=gl(),transmissionMode:r=oa}=e;return Xo(Xo({},Jo(e,Tn)),{},{version:t,transmissionMode:r,sid:i,eventTargets:s.reduce((e,t)=>{var s,i,r;return null!=t&&t.url&&null!=(s=t.events)&&s.length&&e.push({version:t.version||Pn,enabledKeys:(null==(i=t.enabledKeys)?void 0:i.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(r=t.interval)?r:30,batchSize:t.batchSize||1}),e},[])})}(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(const e of this.config.eventTargets)this.eventTargets.set(e,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),0===t.interval||!t.events.includes("t"))return;const s=()=>{this.recordTargetEvent(e,t,"t"),this.processEventTargets()};e.intervalId=setInterval(s,1e3*t.interval),s()})}stop(e=!1){e&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=Xo(Xo(Xo({},this.data),e),{},{msd:void 0});for(const t of ca)t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(e,t={}){const s=ua.get(e);if(s){const e=s.field,i=t[e];void 0!==i&&zo(this.data,{[e]:i});const r=this.data[e];if(void 0===r)return;if(s.equal(r,this.lastEmitted[e]))return;zo(this.lastEmitted,{[e]:s.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,s,i={}){var r;if(!t.events.includes(s))return;const n=Xo(Xo(Xo({},this.data),i),{},{e:s,ts:null!=(r=i.ts)?r:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(n.msd=this.msd,e.msdSent=!0),e.queue.push(n)}recordResponseReceived(e,t={}){var s,i,r;const{request:n}=e,a=null!=(s=t.url)?s:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(ia);const l={url:o.toString(),rc:e.status},h=e.resourceTiming;h&&(null!=h.startTime&&(l.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(l.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(l.ttlb=Math.round(h.duration)));const d=null!=(i=null==(r=n.customData)?void 0:r.cmcd)?i:{};this.recordEvent(_n,Xo(Xo(Xo({},d),l),t))}applyRequestReport(e){var t;return null!=(t=this.createRequestReport(e))?t:e}isRequestReportingEnabled(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}createRequestReport(e,t){var s;const{customData:i={},headers:r={}}=e,n=Xo(Xo({},Jo(e,wn)),{},{headers:Xo({},r),customData:Xo(Xo({},i),{},{cmcd:{}})});if(null==(s=this.config.enabledKeys)||!s.length||!n.url)return n;const a=new URL(n.url),o=Xo(Xo(Xo({},this.data),t),{},{sn:this.requestTarget.sn++}),l=tu(Un,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const h=n.customData.cmcd=Zc(o,l);switch(this.config.transmissionMode){case oa:const e=eu(h);e&&(a.searchParams.set(ia,e),n.url=a.toString());break;case la:zo(n.headers,function(e,t){const s={},i=function(e,t){const s={};if(!e)return s;const i=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var s;return null==(s=n[t])||s.forEach(s=>e[s]=t),e},{})):{};var n;for(const t of i){var a;const i=sa[t]||r[t]||ta.REQUEST;(null!=(a=s[i])?a:s[i]={})[t]=e[t]}return s}(e,t);for(const[e,t]of Object.entries(i)){const i=qc(t,{whitespace:!1});i&&(s[e]=i)}return s}(h,l.customHeaderMap))}return n}processEventTargets(e=!1){let t=!1;this.eventTargets.forEach((s,i)=>{const{queue:r}=s;if(!r.length)return;if(r.length<i.batchSize&&!e)return;const n=e?r.length:i.batchSize,a=r.splice(0,n);this.sendEventReport(i,a).catch(()=>{s.queue.unshift(...a)}),t||(t=r.length>0)}),t&&this.processEventTargets()}async sendEventReport(e,t){const s=tu(Bn,e),{status:i}=await this.requester({url:e.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:t.map(e=>function(e,t={}){return e?eu(Zc(e,t)):""}(e,s)).join("\n")+"\n"});if(410===i)this.disposeEventTarget(e);else if(429===i||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){const t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}resetSession(){this.eventTargets.forEach(e=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},ga={HLS:"h"},ma={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"},new Set(Vn),new Set(ra),pa=["includeKeys"],va=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(aa.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(aa.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(aa.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(aa.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(aa.SEEKING)},this.onSeeked=()=>{var e;this.initialized&&null!=(e=this.media)&&e.paused&&this.setPlayerState(aa.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=e=>{try{this.apply(e,{ot:na.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:n,part:a}=e,o=this.hls.levels[n.level],l=this.getObjectType(n,o),h={d:1e3*(a||n).duration,ot:l};if(l===na.VIDEO||l===na.AUDIO||l===na.MUXED||null==l&&("main"===n.type||"audio"===n.type)){var t;const e=o.bitrate/1e3;h.br=[e];const{cmcd:i}=this.config,r=null!=(t=null==i?void 0:i.rtpSafetyFactor)?t:5;if(h.rtp=100*Math.round(e*r/100),l===na.MUXED||null==l&&"main"===n.type){const e=this.getTopBandwidth()/1e3;Ss(e)&&(h.tb=[e]);const t=this.getLowestBandwidth()/1e3;Ss(t)&&(h.lb=[t])}const a=this.getBufferLength(n);if(Ss(a)){var s;h.bl=[a];const e=(null==(s=this.media)?void 0:s.playbackRate)||1;h.dl=100*Math.round(a/e/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const d=this.hls.maxAutoLevel;if(d>=0){const e=this.hls.levels[d];e&&(h.tpb=[e.bitrate/1e3])}}const d=a?this.getNextPart(a):this.getNextFrag(n);null!=d&&d.url&&d.url!==n.url&&(d.byteRange.length>0?h.nor=[(i=d.url,r={r:`${d.byteRange[0]}-${d.byteRange[1]}`},new hn(i,r))]:h.nor=[d.url]),this.apply(e,h)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}var i,r},this.recordFragmentResponse=(e,t,s)=>{var i;const{cmcd:r}=this.config,n=null==r||null==(i=r.eventTargets)?void 0:i.some(e=>{var t;return null==(t=e.events)?void 0:t.includes(xn.RESPONSE_RECEIVED)});if(this.reporter&&s.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:s.loading.start,responseStart:s.loading.first,duration:s.loading.end-s.loading.start,encodedBodySize:s.total}})}catch(e){this.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;const{cmcd:s}=this.config;if(null==s)return;const i=s.version||1;if(this.reporter=new fa({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:!0===s.useHeaders?la:oa,enabledKeys:null!=(e=s.includeKeys)?e:[...i>=Pn?ra:Vn],eventTargets:(null!=(t=s.eventTargets)?t:[]).map(e=>{let{includeKeys:t}=e;return Xo(Xo({},Jo(e,pa)),{},{enabledKeys:null!=t?t:ra})})},s.loader),this.reporter.update({sf:ga.HLS,sta:this.playerState}),s.reporterCallback){const e=this.reporter,t={updateCustomData:t=>{iu(t)&&e.update(t)},recordCustomEvent:(t,s={})=>{iu(s)&&e.recordEvent(xn.CUSTOM_EVENT,Xo({cen:t},s))}};s.reporterCallback(t)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Is.MEDIA_ENDED,this.onMediaEnded,this),e.on(Is.ERROR,this.onError,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(Is.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(Is.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Is.MEDIA_ENDED,this.onMediaEnded,this),e.off(Is.ERROR,this.onError,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(Is.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(Is.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){const s=this.media=t.media;this.setPlayerState(this.media.autoplay?aa.STARTING:aa.PRELOADING),jd(s,"waiting",this.onWaiting),jd(s,"play",this.onPlay),jd(s,"playing",this.onPlaying),jd(s,"pause",this.onPause),jd(s,"seeking",this.onSeeking),jd(s,"seeked",this.onSeeked),jd(s,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(Kd(e,"waiting",this.onWaiting),Kd(e,"play",this.onPlay),Kd(e,"playing",this.onPlaying),Kd(e,"pause",this.onPause),Kd(e,"seeking",this.onSeeking),Kd(e,"seeked",this.onSeeked),Kd(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(aa.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(aa.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(aa.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(xn.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;const i={br:[t.bitrate/1e3]},r=null==(s=t.details)?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,t)),this.reporter.recordEvent(xn.BITRATE_CHANGE,i)}onLevelSwitched(e,t){const s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?ma.LOW_LATENCY:ma.LIVE:ma.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(s=this.media)?void 0:s.playbackRate,st:this.getStreamType()});const i=t.ot===na.INIT||t.ot===na.VIDEO||t.ot===na.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=i;for(let t=r.length-1;t>=0;t--){const i=r[t];if(i.index===s&&i.fragment.sn===e)return r[t+1]}}}getObjectType(e,t){const{type:s}=e;if("subtitle"===s)return na.TIMED_TEXT;if("initSegment"===e.sn)return na.INIT;if("audio"===s)return na.AUDIO;if("main"===s){if(e.hasStreams){const t=e.elementaryStreams;if(t.audiovideo)return na.MUXED;if(t.video)return na.VIDEO;if(t.audio)return na.AUDIO}if(t){const{audioCodec:e,videoCodec:s}=t;if(!this.hls.audioTracks.length){if(e&&s)return na.MUXED;if(e)return na.AUDIO}if(s)return na.VIDEO}}}getTopBandwidth(){let e=0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(t=>{t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(t=>{t.bitrate<e&&(e=t.bitrate)}),Ss(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;const t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);const s=e||t;return s?1e3*s.len:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;const s=this.getEventBufferLength();Ss(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,i){t(e),this.loader.load(e,s,i)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=this.recordFragmentResponse,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e);const{onSuccess:n}=r;this.loader.load(e,i,Xo(Xo({},r),{},{onSuccess:(t,i,r,a)=>{n(t,i,r,a),s(e.url,t,i)}}))}}}},ya=class extends Bs{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===vi.SendAlternateToPenaltyBox&&s.flags&yi.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:s,pathwayId:i,type:n}=t.context;s&&e?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&e&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r,s.resolved||t.details===ws.BUFFER_APPEND_ERROR&&!t.fatal||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${gi(i)} penalized: ${gi(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(e=>{i-s[e]>3e5&&delete s[e]});for(let i=0;i<e.length;i++){const r=e[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ud(t),this.hls.trigger(Is.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===Cs.AUDIO_TRACK&&i[s].hasAudioGroup(e)||t===Cs.SUBTITLE_TRACK&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new Bi(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=nu(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new ui({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return h});t.push(...o),ru(this.audioTracks,s,a,r),ru(this.subtitleTracks,i,a,r)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);kh(i,"_HLS_pathway",this.pathwayId),kh(i,"_HLS_throughput",""+e)}const r={type:Cs.STEERING_MANIFEST,responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(Is.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,s,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},Sa=class 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}},(Ea=class e extends Bs{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,i=`"${e.type}" event: init data type: "${t}"`;if(this.log(i),null!==s){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=md(this.config));const t=e.map(gd).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{let n;const a=fd(r),o=this.activeLevelKeys();if(a===Gi.FAIRPLAY&&"sinf"===t)try{const e=Dl(new Uint8Array(s)),t=Xl(Pl(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${i} Failed to parse sinf: ${e}`)}else if(a===Gi.PLAYREADY)n=pd(new Uint8Array(s));else if(a===Gi.WIDEVINE){const e=nh(s).filter(e=>e.systemId===Wi.WIDEVINE);if(e.length){var l;const t=e[0];n=null!=(l=t.kids)&&l.length?t.kids[0]:null}}let h;if(n){const e=Rl(n);for(let i=0;i<o.length;i++){const r=o[i];if(r.keyId&&(ad(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(e))){r.pssh||(r.scheme=t,r.pssh=new Uint8Array(s),r.keyId=n,Ki.setKeyIdForUri(r.uri,n)),h=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!h){var d,c;if(o.length)return(d=o[0]).scheme||(d.scheme=t),(c=o[0]).pssh||(c.pssh=new Uint8Array(s)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${Rl(n)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return h}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,i=t.map(e=>e.audioCodec).filter(s),r=t.map(e=>e.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,i,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):s(t instanceof Sa?t:new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===qi&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=function(e,t,s,i){let r;switch(e){case Gi.FAIRPLAY:r=["cenc","sinf"];break;case Gi.WIDEVINE:case Gi.PLAYREADY:r=["cenc"];break;case Gi.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,s,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}(r,t,s,i)}(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(i=n)?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${gi(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(s=>{this.throwIfDestroyed(),this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=s.createMediaKeys().then(s=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,i.then(t=>t?this.setMediaKeysServerCertificate(s,e,t):s)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(e,t,s,i){const{mediaKeySessions:r}=this,n=` key-session "${e}" keyId: ${Rl(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let e=0;e<r.length;e++){const t=r[e];if(!t.initialized&&t.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${n}`),t}this.log(`Creating${n}`);const a=t.createSession(),o={keySystem:e,mediaKeys:t,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(o),o}resetMediaKeys(){var e;const t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,s.hasMediaKeys=!1,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Rl(t.keyId||[])}\n } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>gd(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const t=gd(e);if(!t)throw new Error(`Unable to find format for key-system "${e}"`);return 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){const t=md(this.config),s=e.map(fd).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(s)}loadClear(e,t,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!Wo(e)||!Wo(n)||e.sn<n.sn)||!s&&i==r-1)return this.selectKeySystemFormat(n).then(e=>{if(!this.hls)return;n.setKeyFormat(e);const t=fd(e);return t?this.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=md(this.config);if(e.length)return this.getKeySystemAccess(e)}}return null}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=au(e,t[s]);if(i)return i}}loadKey(e){const t=e.decryptdata,s=this.getKeyStatus(t);if("internal-error"===s){const i=ou(s,t);return i.data.frag=e,this.error(`${i.message} (${Rl(t.keyId||[])})`),Promise.reject(i)}const i=e.type,r=this.activeKeys,n=r[i];n&&!t.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[i]),r[i]||(r[i]=e);for(let e=this.mediaKeySessions.length;e--;){const s=this.mediaKeySessions[e];if(t.keyId&&"expired"===s.keyStatuses[Rl(t.keyId)])return this.renewKeySession(t,s)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,s){const i=this.getSessionForKey(e,t);return i.catch(e=>this.handleError(e,s)),i.then(t=>e)}getSessionForKey(e,t){const s=this.findContextForKey(e);if(void 0!==s)return Promise.resolve(s);const i=e.uri,r=this.sessionSetupByUri[i];let n;n=void 0===r?this.resolveSessionForKey(e,t):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[i]=n;const a=()=>{this.sessionSetupByUri[i]===n&&delete this.sessionSetupByUri[i]};return n.then(a,a),n}findContextForKey(e){const{mediaKeySessions:t}=this;for(let s=t.length;s--;){const i=t[s];if(au(e,i))return i}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let s=this.mediaKeySessions.length;s--;){const i=this.mediaKeySessions[s];if(au(e,i))return i;const r=this.getUsableKeyPromise(i,e,t);if(r)return r}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,e,t))).then(s=>{this.throwIfDestroyed();const i=e.scheme||"cenc",r=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(s,e,i,r,t)})})}getUsableKeyPromise(e,t,s){const i=e.keyRequests[t.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${function(e){if(e.keyFormat===Hi.FAIRPLAY)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return Rl(e.keyId)}(t)} format: "${t.keyFormat}" URI: ${t.uri})`),lu(i).then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Sa){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Rl(s.keyId||[])})`:""}`),this.hls.trigger(Is.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Is.ERROR,{type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=fd(e.keyFormat),s=t?[t]:md(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=md(this.config)),0===e.length)throw new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${gi({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,t=(e.previous||[]).map(e=>e.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,s)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return s(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(s)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===s.indexOf(e))})}filterInitData(e,t,s,i,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[e.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,s,i,zo({},e,{decryptdata:t,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");t.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return t.pssh=o?new Uint8Array(o):null,n}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(e,t,s,i,r){const n=this.getUsableKeyPromise(e,t,r);if(n)return n;const a=this.filterInitData(e,t,s,i,r);if(a&&(i=a.initData?a.initData:null,s=a.initDataType),null===i)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));const o=t.uri,l=new rr;l.status="initialized",l.requestErrors=[],e.keyRequests[o]=l;const h=s=>{const i=e.mediaKeysSession;if(!i){const e=new Error("invalid state");return l.errored=e,void l.emit("error",e)}const{messageType:r,message:n}=s;l.status=r,this.log(`"${r}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,t,n).catch(t=>{l.errored=t,l.eventNames().length?l.emit("error",t):this.handleError(t),this.removeSession(e)}):"license-release"===r?e.keySystem===Gi.FAIRPLAY&&this.updateKeySession(e,t,dd("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)};return l.onmessage=h,jd(e.mediaKeysSession,"message",h),this.generateRequest(e,t,s,i,r,!1)}generateRequest(e,t,s,i,r,n){if(n){const n=this.filterInitData(e,t,s,i,r);n&&(i=n.initData?n.initData:i,s=n.initDataType)}const a=t.uri,o=e.keyRequests[a],l=Rl(t.keyId||[]),h=e=>{let s;e.startsWith("usable")?(o.resolved=!0,o.emit("resolved")):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?s=ou(e,t):"expired"===e?s=new Error(`key expired (keyId: ${l})`):"released"===e?s=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${l})`),s&&(o.errored=s,o.eventNames().length?o.emit("error",s):this.handleError(s))},d=s=>{if(!e.mediaKeysSession){const e=new Error("invalid state");return o.errored=e,void o.emit("error",e)}const i=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;const r=this.activeLevelKeys();for(let s=0;s<r.length;s++){const a=Rl(r[s].keyId||[]);if("expired"===i[a]){var n;this.log(`Expired key ${gi(i)} in key-session "${null==(n=e.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(t,e).catch(e=>this.handleError(e));break}}let a=i[l];if(a)h(a);else{var d;const s=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(d=e.keyStatusTimeouts)[l]||(d[l]=self.setTimeout(()=>{var i;if(!e.mediaKeysSession)return;const r=this.getKeyStatus(t);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${l} in key-session "${null==(n=e.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),h(r);this.log(`key status for ${l} in key-session "${null==(i=e.mediaKeysSession)?void 0:i.sessionId}" timed out after ${s}ms`),a="internal-error",h(a)},s)),this.log(`No status for keyId ${l} (${gi(i)}).`)}};o.onkeystatuseschange=d,jd(e.mediaKeysSession,"keystatuseschange",d);const c=lu(o);return this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${a} (init data type: ${s} length: ${i.byteLength})`),o.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,i).then(()=>{var t;o.status="generated",this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l} URI: ${a}`)}).catch(e=>{throw this.log(`mediaKeysSession.generateRequest failed: ${e}`),new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>c).catch(t=>{var s;this.log(`mediaKeysSession.generateRequest failed: ${t}`);const i=null==(s=t.data)?void 0:s.details;return i!==ws.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==ws.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(t=>"usable"===e.keyStatuses[t])?(o.removeAllListeners(),this.removeSession(e).then(()=>{throw t})):(this.handleError(t),e)}).then(()=>e)}getKeyStatuses(e){const t={},s=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){const e=r;r=i,i=e}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===Gi.PLAYREADY&&16===n.length){const e=Rl(n);t[e]=i,cd(n)}const a=Rl(n);this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${s}"`),t[a]=i}),t}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),i=function(e,t){const{drmSystems:s}=t,i=null==s?void 0:s[e];if(i)return i.serverCertificateUrl}(e,t);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={type:Cs.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,s,i)=>{r(e.data)},onError:(t,s,r,o)=>{n(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Xo({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,r)=>{n(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,h)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(e=>{r(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(e=>{throw new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(e,t){const s=Dl(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let s=0,i=r.length;s<i;s++){var n,a;t=r[s];const i=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;i&&o&&e.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return dd(atob(l))}setupLicenseXHR(e,t,s,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,e,t,Xo(Xo({},s),{},{decryptdata:i}),r))).catch(a=>{if(!s.mediaKeysSession)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,Xo(Xo({},s),{},{decryptdata:i}),r)}).then(s=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:s||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,s){return new Promise((i,r)=>{const n=function(e,t){const{drmSystems:s,widevineLicenseUrl:i}=t,r=null==s?void 0:s[e];return r?r.licenseUrl:e===Gi.WIDEVINE&&i?i:void 0}(e.keySystem,this.config);if(!n)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const a=e.keyRequests[t.uri];if(!a)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${n}`);const o=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){a.requestErrors=[];let s=l.response;this.log(`License received ${s instanceof ArrayBuffer?s.byteLength:s}`);const r=this.config.licenseResponseCallback;if(r)try{s=r.call(this.hls,l,n,Xo(Xo({},e),{},{decryptdata:t}))}catch(e){this.error(e)}i(s)}else{const h=o.errorRetry,d=h?h.maxNumRetry:0;if(a.requestErrors.push({status:l.status,message:l.statusText}),a.requestErrors.length>d||l.status>=400&&l.status<500)r(new Sa({type:Ts.KEY_SYSTEM_ERROR,details:ws.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const n=d-a.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t,s).then(i,r)}}},a.licenseXhr&&a.licenseXhr.readyState!==XMLHttpRequest.DONE&&a.licenseXhr.abort(),a.licenseXhr=l,this.setupLicenseXHR(l,n,e,t,s).then(({xhr:t,licenseChallenge:s})=>{e.keySystem==Gi.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,jd(s,"encrypted",this.onMediaEncrypted),jd(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Kd(e,"encrypted",this.onMediaEncrypted),Kd(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const s=this.mediaResolved;if(s&&s(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ki.clearKeyUriToKeyIdMap();const n=r.length;e.CDMCleanupPromise=Promise.all(r.map(e=>this.removeSession(e)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(s=>{const i=e.keyRequests[s];i.onmessage&&(t.removeEventListener("message",i.onmessage),i.onmessage=void 0),i.onkeystatuseschange&&(t.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.onkeystatuseschange=void 0);const r=i.licenseXhr;r&&(r.readyState!==XMLHttpRequest.DONE&&r.abort(),i.licenseXhr=void 0),e.keyRequests[s]=void 0}),e.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(e=>self.clearTimeout(i[e]));const{drmSystemOptions:r}=this.config,n=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(r)?new Promise((e,s)=>{self.setTimeout(()=>s(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(s)}):Promise.resolve();return n.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).then(()=>t.closed).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}).CDMCleanupPromise=void 0,ba=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,r=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(Is.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Is.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},Ta=function(){if(null!=$i&&$i.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function i(e){return s(t,e)}function r(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=t,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",S=50,E="middle",b=50,T="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(t){const i=function(t){return s(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return T},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),wa=class{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}},Ia=class{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}},La=new Ta(0,0,""),Aa="middle"===La.align?"middle":"center",ka=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new wa,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=uu(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const i=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),i}function i(e){du(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const i=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=s(),t.state){case"HEADER":/:/.test(e)?i(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Ta(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{cu(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Ra=/\r\n|\n\r|\n|\r/g,Ca="Missing initPTS for VTT ",Pa=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ss(t)&&Ss(s)&&Ss(i)&&Ss(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*i,t+=36e5*r,t},Da="stpp.ttml.im1t",Ma=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,_a=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oa={left:"start",center:"center",right:"end",start:"start",end:"end"},xa=class extends Zr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){var s;const i=null==(s=this.currentTrack.trackNode)?void 0:s.track.mode;"showing"===i?(e=this.trackId,t=!0):"hidden"===i&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){var i;const s=null==(i=this.tracksInGroup[t].trackNode)?void 0:i.track.mode;if("showing"===s){e=t;break}e<0&&"hidden"===s&&(e=t)}var r;e>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[e].trackNode)?void 0:r.track.mode)),this.setSubtitleTrack(e,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Is.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Is.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{e.trackNode||(e.trackNode=Tu(this.media,function(e){return e.forced&&(Zs.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Js))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}(e),e.name,e.lang))});const t=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==t?void 0:t.mode)&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const s=t.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{const t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some(e=>-1===(null==i?void 0:i.indexOf(e)))){this.groupIds=s;const e=[];if(this.tracks.forEach(t=>{(t.textCodec===Da?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&(t.trackNode.remove(),t.trackNode=void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let s=0;s<e.length;s++)if(e[s]!==this.tracksInGroup[s]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const s=_h(t,e);if(s>-1)r=e[s];else{const e=_h(t,this.tracks);r=this.tracks[e]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(Is.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(i),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if((!s||r.default)&&(s||e)&&(!e||Oh(r,e)))return i}if(e){for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const i=t[s];if(Cc(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.SUBTITLE_TRACK&&t.context.id===this.trackId&&Uh(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Oh(e,s))return s;const i=_h(e,this.tracksInGroup);if(i>-1){const e=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),e}if(s)return null;{const s=_h(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(Is.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){const s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=t.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(e,t=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!Ss(e))return void this.warn(`Invalid subtitle track id: ${e}`);const i=this.currentTrack,r=s[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r)return void(i&&this.hls.trigger(Is.SUBTITLE_TRACK_SWITCH,{id:e}));const n=!!r.details&&!r.details.live;if(r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:h,url:d}=r;this.hls.trigger(Is.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:d});const c=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(c)}},Fa=class extends Pi{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Is.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;jd(s,"playing",this.onMediaPlaying),jd(s,"waiting",this.onMediaWaiting),jd(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Kd(s,"playing",this.onMediaPlaying),Kd(s,"waiting",this.onMediaWaiting),Kd(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Is.MEDIA_ENDED,{stalled:!1})));if(!_i.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const d=_i.bufferInfo(n,e,0),c=this.fragmentTracker;c&&this.hls&&Ru(d,e,c,this.hls);const u=d.nextStart||0;if(a&&c&&this.hls){const t=Lu(this.hls.inFlightFragments,e),s=d.len>2,i=!u||t||u-e>2&&!c.getPartialFragment(e);if(s||i)return;this.moved=!1}const f=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(d.len>0||u))return;const t=Math.max(u,d.start||0)-e,s=null!=f&&f.live?2*f.targetduration:2,i=ku(e,c);if(t>0&&(t<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let v=this.stalled;if(null===v){if(!(p>0&&m-p<g))return void(this.stalled=m);v=this.stalled=p}const y=m-v;if(!a&&(y>=g||p&&this.moved)&&this.hls){var S;if("ended"===(null==(S=this.mediaSource)?void 0:S.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Is.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return;if(n.currentTime!==e){const t=e;return e=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${t} > ${e}`)}}const E=_i.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(E,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Is.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&e>i.end(0)){const s=_i.bufferedInfo(_i.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=_i.timeRangesToArray(i),r=_i.bufferedInfo(s,t,0).bufferedIndex;if(r>-1&&r<s.length-1){const t=_i.bufferedInfo(s,e,0).bufferedIndex,i=s[r].end,n=s[r+1].start;if((-1===t||t>r)&&n-i<1&&e-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${i} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let r=ku(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=_i.bufferInfo(this.media,e,0);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=ku(s,n);if((h||null!=l&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const d=e.buffered,c=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const e=s.getFragAtPos(t,Ps.MAIN),r=s.getFragAtPos(i,Ps.MAIN);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${gi(e)})`);this.warn(i.message),t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){const{fragmentTracker:t,media:s,hls:i}=this,r=null==i?void 0:i.config;if(!s||!t||!r)return 0;const n=s.currentTime,a=_i.bufferInfo(s,n,0);Ru(a,n,t,i);const o=n<a.start?a.start:a.nextStart;if(o){const h=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(h||d)){if(c>r.maxBufferHole){let s=!1;if(0===n){const e=t.getAppendedFrag(0,Ps.MAIN);e&&o<e.end&&(s=!0)}if(!s&&e){var l;if(null==(l=i.loadLevelObj)||!l.details)return 0;if(Lu(i.inFlightFragments,o))return 0;let s=!1,r=e.end;for(;r<o;){const e=ku(r,t),i=e?e.duration:0;if(!(i>0)){s=!0;break}r+=i}if(s)return 0}}const{nudgeMaxRetry:h,skipBufferHolePadding:d}=r,u=++this.skipRetry>h,f=Math.max(o,n)+d;if(u||(this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,s.currentTime=f),null==e||!e.gap||u){const t=new Error(u?`Playhead still not moving after seeking over buffer hole from ${n} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${f}`),s={type:Ts.MEDIA_ERROR,details:ws.BUFFER_SEEK_OVER_HOLE,fatal:u,error:t,reason:t.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?s.part=e:s.frag=e),i.trigger(Is.ERROR,s)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=null==t?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}},Ba=(()=>{const e=Cu();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Ua=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Is.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return Tu(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Cu();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===or.emsg&&!s||!i)continue;const a=Il(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>Ba&&(l=Ba),l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!Ll(s)){this.updateId3CueEnds(o,t);const e=Pu(n,o,l,s,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.track.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===Ba&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===i?e=>e.type===or.audioId3&&o:"video"===i?e=>e.type===or.emsg&&a:e=>e.type===or.audioId3&&o||e.type===or.emsg&&a,Iu(r.track,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Cu();if(s&&i&&!n){const{fragmentStart:t,fragmentEnd:i}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=i):a&&(r=this.assetCue=Pu(a,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.track.cues)&&c.length){const e=Object.keys(d).filter(e=>-1===h.indexOf(e));for(let t=e.length;t--;){var u;const s=e[t],i=null==(u=d[s])?void 0:u.cues;delete d[s],i&&Object.keys(i).forEach(e=>{const t=i[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(t)}catch(e){}}})}}else d=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==h.length&&Ss(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<h.length;e++){const t=h[e],s=l[t],i=s.startTime,r=d[t],o=(null==r?void 0:r.cues)||{};let c=(null==r?void 0:r.durationKnown)||!1,u=Ba;const{duration:f,endDate:g}=s;if(g&&null!==f)u=i+f,c=!0;else if(s.endOnNext&&!c){const e=h.reduce((e,t)=>{if(t!==s.id){const i=l[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e},null);e&&(u=e.startTime,c=!0)}const m=Object.keys(s.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!rd(l))continue;const h=o[l];if(h)!c||null!=r&&r.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=u):h.endTime=u;else if(a){let e=s.attr[l];nd(l)&&(e=Cl(e));const r=Pu(a,i,u,{key:l,data:e},or.dateRange);r&&(r.id=t,this.id3Track.track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}d[t]={cues:o,dateRange:s,durationKnown:c}}}}},Na={DISABLED:0,SWITCHING:1,SWITCHED:2},$a=class extends er{constructor(e,t,s){super(e,t,s,"stream-controller",Ps.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Na.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!Ss(t))return;if(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,Ps.MAIN,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${t} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Is.BUFFER_CREATED,this.onBufferCreated,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Is.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Is.BUFFER_CREATED,this.onBufferCreated,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=Zi.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Zi.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Zi.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=Zi.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Zi.IDLE;break}break}case Zi.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Zi.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={type:this.targetBufferType()};return this.hls.trigger(Is.BUFFER_EOS,e),void(this.state=Zi.ENDED)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===Zi.WAITING_LEVEL||this.waitForLive(n))return this.level=r,this.state=Zi.WAITING_LEVEL,void(this.startFragRequested=!1);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=void 0);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&Wo(u)&&this.fragmentTracker.getState(u)!==Ei.OK){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=void 0);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?Ds.AUDIO:Ds.VIDEO,t=(e===Ds.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}u=this.getNextFragmentLoopLoading(u,l,a,Ps.MAIN,d)}u&&(this.exceedsMaxBuffer(a,d,u)||this.loadFragment(u,n,c))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===Ei.NOT_LOADED||i===Ei.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){var e;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Na.DISABLED)&&(((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"))}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Na.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const t=this.fragPlaying;if(t){const s=t.level;this.hls.trigger(Is.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==s&&this.hls.trigger(Is.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio!==Na.SWITCHED||this.audioOnly?null:"video"}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;jd(s,"playing",this.onMediaPlaying),jd(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Kd(s,"playing",this.onMediaPlaying),Kd(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Is.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Na.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(s=s||-1!==r.indexOf("mp4a.40.2"),i=i||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&i&&!function(){var e;const t=Du();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==Zi.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Zi.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;!h||this.state!==Zi.FRAG_LOADING&&this.state!==Zi.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,d),this.hls.trigger(Is.LEVEL_UPDATED,{details:a,level:n}),this.state===Zi.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Zi.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.initPTS.some((e,t)=>{if(t>=a.startCC)return!0;delete this.initPTS[t]}),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i}`),"buffered"===this.config.liveSyncMode){var l;const e=_i.bufferInfo(s,i,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=i);if(e.start<=r)return void(s.currentTime=i);const{nextStart:t}=_i.bufferedInfo(e.buffered,r,0);t&&(s.currentTime=t)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Xr(this.hls,Ps.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,{decryptRange:m,byteRange:p}=Jh(s,i,this.iframesOnly),v=new Di(s.level,s.sn,s.stats.chunkCount,p?p.end-p.start:r.byteLength,f,g,s.duration,this.iframesOnly,m),y=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,v,y)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==Na.DISABLED;if(Bh(t.url,s))this.altAudio=Na.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=Na.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(Is.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Is.AUDIO_TRACK_SWITCHED,t)}),void s.trigger(Is.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(Is.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Bh(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?Na.SWITCHED:Na.DISABLED,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===Ps.MAIN;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Zi.PARSED&&(this.state=Zi.IDLE));let e=!1;if(Wo(s)&&(e=!!s.gap&&!s.tagList.some(e=>"GAP"===e[0])),this.fragBufferedComplete(s,i),e){var n;s.stats.retry++;const e=null==(n=this.levels)?void 0:n[s.level];e&&e.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&_i.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=Zi.ERROR;else switch(t.details){case ws.FRAG_GAP:case ws.FRAG_PARSING_ERROR:case ws.FRAG_DECRYPT_ERROR:case ws.FRAG_LOAD_ERROR:case ws.FRAG_LOAD_TIMEOUT:case ws.KEY_LOAD_ERROR:case ws.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ps.MAIN,t);break;case ws.LEVEL_LOAD_ERROR:case ws.LEVEL_LOAD_TIMEOUT:case ws.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Zi.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==Cs.LEVEL||(this.state=Zi.IDLE);break;case ws.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case ws.BUFFER_ADD_CODEC_ERROR:case ws.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ws.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ws.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Zi.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Ds.AUDIO||!this.altAudio){const e=(t===Ds.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=_i.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:s}=this,i=null==e?void 0:e.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=Zi.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(Is.FRAG_LOADED,e),i.bitrateTest=!1}).catch(t=>{this.state!==Zi.STOPPED&&this.state!==Zi.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:h,text:d,id3:c,initSegment:u}=i,{details:f}=l,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Zi.PARSING,u){const e=u.tracks;if(e){const i=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,i,r),s.trigger(Is.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:t,tracks:e})}const i=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(Ss(i)&&(!o||o.baseTime!==i||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:i,timescale:n,trackId:e};const r=this.initPTS.slice(0);s.trigger(Is.INIT_PTS_FOUND,{timestampOffsets:r,frag:a,id:t,initPTS:i,timescale:n,trackId:e})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:i,startDTS:n,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:e,endPTS:i,startDTS:n,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,i,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,e,i,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:i}=g;o&&(o.elementaryStreams[Ds.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:i}),a.setElementaryStreamInfo(Ds.AUDIO,e,t,s,i),this.bufferFragmentData(g,a,o,r)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(Is.FRAG_PARSING_METADATA,e)}if(f&&d){const e={id:t,frag:a,details:f,samples:d.samples};s.trigger(Is.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${Wo(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==Zi.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const s=e.audioCodec;let i=vh(r.codec,s);if("mp4a"===i&&(i="mp4a.40.5"),this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&!function(){if(void 0===ti){const e=Js.match(/Firefox\/(\d+)/i);ti=e?parseInt(e[1]):0}return ti}()&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&/Android/.test(Js)&&"audio/mpeg"!==r.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),s&&s!==i&&this.log(`Swapping manifest audio codec "${s}" for "${i}"`),r.levelCodec=i,r.id=Ps.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${i||""}/${s||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=Ps.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Is.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(Is.BUFFER_APPENDING,{type:e,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,Ps.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Zi.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return Ss(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Ss(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?$h(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const i=e+1e3*(t-s.start);return new Date(i)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ga=class extends $a{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const e=this.media;null!=e&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;const{seekOnAppend:s}=t,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:this.state=Zi.IDLE}this.state===Zi.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(Is.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){const t=this.media;if(t){var s;const i=null==(s=this.getLevelDetails())?void 0:s.edge,r=void 0!==i?i:t.duration;if(e>=r&&(e=r-.01),_i.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,Ps.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;const s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const e=s.shift();if(!e.data){this.cached=s.filter(e=>!!e.data),this.cachedSize=s.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}this.cachedSize-=e.data.byteLength,e.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const t=e.frag,{part:s,payload:i}=e;this.cacheFragmentData&&!s&&null!=i&&i.byteLength&&!t.data&&Wo(t)&&this.cacheSet(t,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i!==Ei.NOT_LOADED&&i!==Ei.PARTIAL||!this.canReplayCached(e)?super.loadFragment(e,t,s):this.replayCachedFragment(e)}canReplayCached(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;const s=e.decryptdata;return"identity"!==(null==s?void 0:s.keyFormat)||!!s.key}replayCachedFragment(e){const t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const s=e.stats=new Rs;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=Zi.FRAG_LOADING;const i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(Is.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=Zi.STOPPED,null!=s&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Vd(_i.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,t){if(t){const t=this.media;if(t){const s=_i.bufferInfo(t,e,0),i=s.len?s.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,Ps.MAIN),this.flushMainBuffer(i,1/0))}this.hls.once(Is.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(Is.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||i||void 0)}getMainFwdBufferInfo(){const e=this.playhead,t=this.getBufferedAt(e);if(t){const s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,Ps.MAIN);return!(null==t||!t.endList)}},Ha=class extends Ga{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;const s=null==(t=this._img)?void 0:t.src;s&&self.URL.revokeObjectURL(s),this._img=e}loadMediaAt(e){if(!this.hls)return;const t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Zi.STOPPED:case Zi.ENDED:case Zi.ERROR:this.state=Zi.IDLE}if(this.state===Zi.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Zi.IDLE){const t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{const s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){const i=e.data;i||this.fragmentTracker.removeFragment(e);const r=this._img;if(r&&i){const n=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const i=this.hls.levels[e.level];null!=i&&i.fragmentError&&(i.fragmentError=0,e.stats.retry=0);const r=self.performance.now(),n=t?t.stats:e.stats;n.buffering.end=e.stats.buffering.end=r,this.hls.trigger(Is.FRAG_BUFFERED,{frag:e,part:t,stats:n,id:e.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",e,t,s)};const a=r.src;a&&self.URL.revokeObjectURL(a);const o=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(o)}else this.state=Zi.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,i){if(!this.hls)return;const r=new Error(e);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,s,i){super.bufferFragmentData(e,t,s,i,!0);const r=Gl(new Uint8Array(e.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",t,s,i);const n=t;this.cacheSet(n,r[0]),this.updateImage(n,s,i)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;const t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){const e=this.getAppendedFrag(t);if(e&&!qo(e,this.fragPlaying))return this.fragPlaying=e,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},Wa={seekOnAppend:!0},Ka=class extends Bs{constructor(e,t){var s;super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,qa||(s=t,qa=class extends s{constructor(e,t,s,i){e.streamController||(e.streamController=Ga),super(e),this._url=t,this.streamController.setInitPts(s),this.streamController.initDetails=i}loadSource(){}loadMediaAt(e,t=Wa){if(e<0)return;const s=Xo(Xo({},Wa),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,s)}}),ja||(ja=function(e){return class extends e{constructor(e,t,s,i){e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=Ha),e.capLevelController=void 0,e.bufferController=void 0,super(e,t,s,i)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error("Image I-Frame player does not accept HTMLMediaElements")}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}(qa)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Is.MANIFEST_LOADING,this.clearAsset,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MANIFEST_LOADING,this.clearAsset,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var s;const i=null==(s=this.hls)?void 0:s.pathwayPriority;t.length&&i&&this.iframeInstances.forEach(e=>{e.pathwayPriority=i})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===Ps.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;const i=this.hls;i&&i.hasEnoughToStart&&((null==(s=i.mainForwardBufferInfo)?void 0:s.len)||0)>10&&this.iframeInstances.forEach(e=>{var t;e.loadingEnabled||e.startLoad((null==(t=this.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}createIFramePlayer(e){var t;return this.createInstance(qa,null==(t=this.hls)?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;const s=null==(t=this.hls)?void 0:t.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(ja,s,e,"image-")}createInstance(e,t,s,i){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:a,latestLevelDetails:o,loadLevelObj:l,loadLevel:h,bandwidthEstimate:d,sessionId:c}=r,{stats:u,variableList:f}=this;if(null==t||!t.length||!u||!n)return null;const g=`${i||""}iframe-player-${this.instanceCounter++}`,m=r.levels,p=l||m[h],v=Nh(p,a.videoPreference),y=(null==p?void 0:p.pathwayId)||".",S=new e(Xo(Xo({},a),{},{loggerId:g,primarySessionId:c,videoPreference:v,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),n,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(S),S.trigger(Is.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:u,networkDetails:null,url:n,variableList:f}),S}},Va=.025,Ya=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({}),za=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return!(e<=0||isNaN(s))&&(0===s||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>s)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return xu(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-xu(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Ss(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return xu(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Va))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ya.Range:Ya.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}},Qa=class{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Is.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(Is.LEVEL_LOADED,n),r.once(Is.AUDIO_TRACK_LOADED,n),r.once(Is.SUBTITLE_TRACK_LOADED,n),r.on(Is.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(Is.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(Is.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Fu(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if(null!=(s=this.hls)&&s.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),n=_i.bufferInfo(e,r,.02);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=_i.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;null==(i=this.hls)||i.on(e,t)}once(e,t,s){var i;null==(i=this.hls)||i.once(e,t)}off(e,t,s){var i;null==(i=this.hls)||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Uu(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Xa=.033,Ja=class extends Bs{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];t&&"primary"!==t&&(r=r[t]);const n=r.start,a=s[i].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(e===n||e>n&&e<o)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const e=s[i].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if((null==(s=t[i].event)?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let e=0;e<i;e++){const r=s[e];if(!r.error){const s=r.timelineStart;if(t===s||t>s&&(t<s+(r.duration||0)||e===i-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,s=e[e.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,s=0){const i=e.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},t),o=Object.keys(r),l=n?n.filter(e=>-1===o.indexOf(e.identifier)):[];a.length&&a.sort((e,t)=>{const s=e.cue.pre,i=e.cue.post,r=t.cue.pre,n=t.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=e.startTime,i=t.startTime;if(s!==i)return s-i}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,l.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,l,s)}updateSchedule(e,t=[],s=0,i=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(r,e,s);(i||t.length||(null==n?void 0:n.length)!==a.length||a.some((e,t)=>Math.abs(e.playout.start-n[t].playout.start)>.005||Math.abs(e.playout.end-n[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new za(o,t),this.eventMap[a]=e,!1===s&&(e.appendInPlace=s)),i.push(e)}}return i}parseSchedule(e,t,s=0){const i=[],r=t.main.details,n=r.live?1/0:r.edge;let a=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let l=0,h=0;if(e.forEach((t,o)=>{const d=t.cue.pre,c=t.cue.post,u=e[o-1]||null,f=t.appendInPlace,g=c?n:t.startOffset,m=t.duration,p=t.timelineOccupancy===Ya.Range?m:0,v=d&&r.live?s+(t.resumeOffset||0):0,y=v||t.resumptionOffset,S=(null==u?void 0:u.startTime)===g,E=g+t.cumulativeDuration;let b=f?E+m:g+y;if(d||!c&&g<=0){const e=h;h+=p,t.timelineStart=E;const s=a;a+=m,i.push({event:t,start:E,end:b,playout:{start:s,end:a},integrated:{start:e,end:h}})}else{if(!(g<=n))return;{if(!S){const s=g-l;if(s>Xa){const r=l,n=h;h+=s;const d=a;a+=s;const c={previousEvent:e[o-1]||null,nextEvent:t,start:r,end:r+s,playout:{start:d,end:a},integrated:{start:n,end:h}};i.push(c)}else s>0&&u&&(u.cumulativeDuration+=s,i[i.length-1].end=g)}c&&(b=E),t.timelineStart=E;const s=h;h+=p;const r=a;a+=m,i.push({event:t,start:E,end:b,playout:{start:r,end:a},integrated:{start:s,end:h}})}}const T=v||t.resumeTime;l=c||T>n?n:!d&&b&&t.appendInPlaceStarted&&T-b>Xa?b:T}),l<n){var o;const e=l,t=h,s=n-l;h+=s;const r=a;a+=s,i.push({previousEvent:(null==(o=i[i.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:e+s,playout:{start:r,end:a},integrated:{start:t,end:h}})}this.setDurations(n,a,h)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:n,playout:{start:e,end:n},integrated:{start:e,end:n}}),this.setDurations(n,n,n)}return i}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,d=l?0:h?i:a.startTime;this.updateAssetDurations(a),n===d?a.cumulativeDuration=r:(r=0,n=d),!h&&a.snapOptions.in&&(a.resumeAnchor=$h(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<e.length&&e[o+1].startTime-e[o].resumeTime<Xa&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const c=Ss(a.resumeOffset)?a.resumeOffset:a.duration;r+=c})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Va?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(i=>{const r=t[i].details,n=r.edge;if(s>=n)return this.log(`"${e.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=$h(null,r.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s)<Va+o||Math.abs(a.end-s)<Va+o||(this.log(`"${e.identifier}" resumption ${s} not aligned with ${i} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),0))})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,i||(i=null===a.duration),r||(r=!!a.error),s+=a.error?0:a.duration||0}e.duration=i&&!r?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}},Za=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Fu(s,this.hls.sessionId,e.baseUrl)}catch(t){const i=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(Is.ERROR,i)}t&&"data:"!==i.protocol&&kh(i,"_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={type:Cs.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,s,i,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,ws.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);return void this.hls.trigger(Is.ERROR,t)}e.assetListResponse=n,this.hls.trigger(Is.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,s,i,r)=>{const n=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,r,i);this.hls.trigger(Is.ERROR,n)},onTimeout:(t,s,i)=>{const r=this.assignAssetListError(e,ws.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,i);this.hls.trigger(Is.ERROR,r)}};return n.load(a,l,h),this.hls.trigger(Is.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:Ts.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}},eo=class extends Bs{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=e,this.bufferedPos=e;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),s&&e<i.start||e>=i.end){var r;const t=this.findItemIndex(i);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const t=i.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&e<a||e>=a+o)&&(null!=(l=i.event)&&l.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;s&&e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>Nu(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,d=null;i&&(h=this.updateItem(i,this.timelinePos),this.itemsMatch(i,h)?this.playingItem=h:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const c=this.bufferingItem;if(c&&(d=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,d)?this.bufferingItem=d:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,s=e.timelineOffset-t;if(s)try{e.timelineOffset=t}catch(i){Math.abs(s)>Va&&this.warn(`${i} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(Is.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.indexOf(i.event.identifier)>-1)return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);i&&this.trimInPlace(h,i),c&&d!==h&&this.trimInPlace(d,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Za(e),this.schedule=new Ja(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Is.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Is.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Is.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Is.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Is.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Is.MEDIA_ENDED,this.onMediaEnded,this),e.on(Is.ERROR,this.onError,this),e.on(Is.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Is.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Is.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Is.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Is.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Is.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Is.MEDIA_ENDED,this.onMediaEnded,this),e.off(Is.ERROR,this.onError,this),e.off(Is.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Kd(e,"play",this.onPlay),Kd(e,"pause",this.onPause),Kd(e,"seeking",this.onSeeking),Kd(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;jd(s,"seeking",this.onSeeking),jd(s,"timeupdate",this.onTimeupdate),jd(s,"play",this.onPlay),jd(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=t=>t?e.getAssetPlayer(t.identifier):t,i=(t,i,n,a,o)=>{if(t){let l=t[i].start;const h=t.event;if(h){if("playout"===i||h.timelineOccupancy!==Ya.Point){const e=s(n);(null==e?void 0:e.interstitial)===h&&(l+=e.assetItem.startOffset+e[o])}}else l+=("bufferedPos"===a?r():e[a])-t.start;return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var s,i;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,r),d=null==(a=e.schedule.items)?void 0:a[h],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(f||g)){const n=s(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=t;if("primary"!==r){const e=t-d[r].start;s=d.start+e}const i=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(h>n){const t=e.schedule.findJumpRestrictedIndex(n+1,h);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(i)e.timelinePos=s,e.checkBuffer();else{const e=d.event.assetList,s=t-(d[r]||d).start;for(let t=e.length;t--;){const i=e[t];if(i.duration&&s>=i.startOffset&&s<i.startOffset+i.duration){a=t;break}}}e.setSchedulePosition(h,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=s)}}},o=()=>{const s=e.effectivePlayingItem;if(e.isInterstitial(s))return s;const i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){const s=t(),r=e.bufferingItem;var n;return r&&r===s&&(i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),s=e.effectivePlayingItem;return s&&s===t?i(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(t){const s=o(),i=e.effectivePlayingItem;i&&i===s&&a(t+i.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const s=null==(t=o())?void 0:t.event.assetList;return s?s.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const s=null==(t=o())?void 0:t.event;return s&&e.effectivePlayingAsset?s.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((t,s)=>{var i;if(0!==t&&null!=(i=e.schedule)&&i.length){var r;const i=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[i];if(n)return t+(n[s].start-n.start)}return t})(e.seekableStart,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,s=null==t?void 0:t.event;if(s&&!s.restrictions.skip){const i=e.findItemIndex(t);if(s.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(s,i,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&s)&&this.findItemIndex(t)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);const r=null==(t=i)?void 0:t.currentTime;return void 0!==r&&Ss(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${gi(s)}`),this.detachedData=s}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else{const e=this.getBufferingPlayer();e?(r=e.transferMedia(),this.detachedData=r,h=`${e}`):h=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${gi(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState);if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!d&&!a)return void e.attachMedia(t);const c=d&&r?r:{media:t},u=this.schedule;if(u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t||!1===e.appendInPlace}}if(!d&&o){const t=e,s=t.assetItem.timelineStart;if(s){const e=t.hls,i=Math.max(this.timelinePos-s,Number.EPSILON);e.startPosition!==i&&(this.log(`Set ${t} startPosition: ${i}`),e.config.startPosition=i,e.loadingEnabled&&e.startLoad(i))}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){if(!s.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const i=s.startPosition;if(this.timelinePos=i,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Gu("checkStart (preroll)",i));const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(i>=0||!this.primaryLive){this.log(Gu("checkStart",i));const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}else 0===s.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Gu("checkStart (playing item)",r.start));const t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Bu(s,i);if(s.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=this.getNextItemIndex(e,!0),s=null==(n=this.schedule.items)?void 0:n[t];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,r)}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!Ss(e.resumeOffset)&&this.hls){const e=this.getLiveStartPos();if(t){const t=this.getBufferingPlayer();return e+(null!=t&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){const s=this.livePrerollResumption(e.event,t);if(void 0!==s)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){const i=Bu(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const i=s[t],r=i.event?this.getNextItemIndex(i):t+1;if(r>=s.length)return void this.setSchedulePosition(-1);const n=e.resumeTime;this.timelinePos<n&&(this.log(Gu("advanceAfterAssetEnded",n)),this.timelinePos=n,e.appendInPlace&&!s[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(e.appendInPlace){const t=e.assetList[i];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const t=s.findEventIndex(i),n=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?Nu(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==t&&c!==s.assetList[t].identifier)){var o;const t=s.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Uu(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(Is.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(c,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Nu(n)}`),s.hasPlayed=!0,this.hls.trigger(Is.INTERSTITIAL_ENDED,{event:s,schedule:i.slice(0),scheduleIndex:e}),s.cue.once&&this.hls)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const o=this.findItemIndex(r),l=this.livePrerollResumption(s);if(void 0!==l){let t=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(i[r])){var h;const e=null==(h=this.primaryDetails)?void 0:h.fragments;if(s.snapOptions.in&&e){const s=$h(null,e,l);s&&(t=Math.min(Math.max(i[r].start,xu(t,s)),i[r].end))}}if(this.log(Gu("live join (preroll)",t)),this.timelinePos=t,r!==o&&(r||0===r))return void this.advanceSchedule(r,e,void 0,n,a)}this.advanceSchedule(o,e,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const s=t.interstitial,i=n.findEventIndex(s.identifier);(i<e||i>e+1)&&this.clearInterstitial(s,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===s){const t=Bu(r,(s=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,s);s=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,s);if(this.eventItemsMatch(a,l||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Nu(a)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(Is.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=r.assetList[s];if(!d)return void this.advanceAfterAssetEnded(r,e,s||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){const e=r.assetList.length;this.warn(`asset ${s+1}/${e} player destroyed ${r}`),h=this.createAssetPlayer(r,d,s),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,s,t,e,o),this.shouldPlay&&$u(h.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&$u(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var i,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Nu(e)}`);let n=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<e.start||n>=e.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(e,t),this.log(Gu("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,e)),!s)return;const a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Nu(e)}`),this.hls.trigger(Is.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,s){const i=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;const e=this.endedItem||this.playingItem,r=null!=e&&e.event?this.livePrerollResumption(e.event,s):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:e,edge:t}=n;if(i<e||i>t&&!s){const s=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${e}-${t}]) snapping to liveSync ${s}`),s||e}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;const t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||s&&s-t<i?s||0:t}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:_i.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Gu("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:n}=s,a=!t&&s.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} instructToSeek: ${a} startPosition: ${n} loadingEnabled: ${i} bufferingEnabled: ${r}`),a||!i||Math.abs(n-e)>.1){const i=this.primaryDetails;if(null!=i&&i.live&&e>=i.edge){const t=this.bufferingItem;return this.log(`Resume primary loading when live reaches ${e} buffering item: ${t?Nu(t):null}`),s.pauseBuffering(),void(this.bufferPastEdge=!0)}s.startLoad(e,t)}else r||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Is.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Is.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=Xo(Xo({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===r?0:r),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const e=this.primaryDetails,t=this.bufferedPos;if(null!=e&&e.live&&t<e.edge){this.bufferPastEdge=!1;const s=this.bufferingItem;if(this.log(`Live edge ${e.edge} reached buffer: ${t} buffering item: ${s?Nu(s):null}`),(null==s?void 0:s.end)===1/0)this.startLoadingPrimaryAt(Math.max(t,s.start));else{const e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(Is.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Xo(Xo({},this.altSelection),{},{audio:s}));const r=Xo(Xo({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i)return void(this.altSelection=Xo(Xo({},this.altSelection),{},{subtitles:s}));const r=Xo(Xo({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Mh(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Mh(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){const e=this.getEventItem(s.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=null==(s=this.schedule)?void 0:s.items;return e&&i&&i[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,s)=>{e.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(t.identifier,null)});const s=e.end+.25,i=_i.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${Nu(e)} (was ${Nu(t)})`);const i=!0;this.attachPrimary(s,null,i),this.flushFrontBuffer(s)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;const s=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;const i=this.mediaSelection;if(!i)return;const r=(null==(t=this.hls)?void 0:t.liveSyncPosition)||0;null==(s=this.schedule)||s.updateSchedule(i,[],r,e)}checkBuffer(e){var t;const s=null==(t=this.schedule)?void 0:t.items;if(!s)return;const i=_i.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(r),i=Math.min(s+1,t.length-1),n=t[i];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=i),this.isInterstitial(r)){const e=r.event;if(i-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const s=this.getAssetPlayer(e.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Nu(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,s)=>{const i=this.getAssetPlayer(e.identifier);i&&(s===t&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(Is.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),s=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),i=this.detachedData;if(i)if(i.mediaSource){const t=!0;this.attachPrimary(s,e,t)}else this.startLoadingPrimaryAt(s);else this.startLoadingPrimaryAt(s)}}bufferedToEvent(e,t){const s=e.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=0===i&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;e.appendInPlace&&(this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25));let l,h=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!e.cue.pre&&!e.cue.post){const e=h-r;e>0&&(l=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${h?` live-start: ${h} start-offset: ${l} (timeline-start: ${r})`:""}`),s)return this.createAsset(e,0,0,r,e.duration,s);const d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!n&&i){for(let s=t;s<i;s++){const t=e.assetList[s],i=this.getAssetPlayerQueueIndex(t.identifier);-1!==i&&!this.playerQueue[i].destroyed||t.error||this.createAssetPlayer(e,t,s)}const s=e.assetList[t];if(s){const e=this.getAssetPlayer(s.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;const s=this.primaryDetails;s&&e>=s.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(Is.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,i,r,n){const a={parentIdentifier:e.identifier,identifier:Ou(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig,n=Nh(i.loadLevelObj||i.levels[i.currentLevel],r.videoPreference),a=i.audioTracks[i.audioTrack],o=i.subtitleTracks[i.subtitleTrack];let l=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>=0){const s=t.duration;s&&e<s&&(l=e)}}const h=t.identifier,d=Xo(Xo({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:a||r.audioPreference,subtitlePreference:o||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const c=d.cmcd;null!=c&&c.sessionId&&c.contentId&&(d.cmcd=zo({},c,{contentId:fu(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const u=new Qa(this.HlsPlayerClass,d,e,t);this.playerQueue.push(u),e.assetList[s]=t;let f=!0;const g=i=>{if(i.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),i={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=this.findEventIndex(e.identifier);return void this.handleAssetItemError(i,e,r,s,t.message)}const r=i.edge-i.fragmentStart,n=t.duration;(f||null===n||r>n)&&(f=!1,this.log(`Interstitial asset "${h}" duration change ${n} > ${r}`),t.duration=r,this.updateSchedule())};u.on(Is.LEVEL_UPDATED,(e,{details:t})=>g(t)),u.on(Is.LEVEL_PTS_UPDATED,(e,{details:t})=>g(t)),u.on(Is.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(e,t)=>{const s=this.getAssetPlayer(h);if(s&&t.tracks){s.off(Is.BUFFER_CODECS,m),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};u.on(Is.BUFFER_CODECS,m),u.on(Is.BUFFERED_TO_END,()=>{const t=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;const s=this.getEventItem(e.identifier);s&&this.advanceAssetBuffering(s,t.assetItem)});const p=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const s=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return u.once(Is.MEDIA_ENDED,p(s)),u.once(Is.PLAYOUT_LIMIT_REACHED,p(1/0)),u.on(Is.ERROR,(t,i)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(i.details===ws.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));i.details!==ws.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(i,e,this.findEventIndex(e.identifier),s,`Asset player error ${i.error} ${e}`)}),u.on(Is.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${h}`),i={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(i,e,this.findEventIndex(e.identifier),s,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Uu(t)}`),this.hls.trigger(Is.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:u}),u}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){const e=this.playerQueue[s];this.log(`clear ${e} toSegment: ${t?Nu(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(null==h?void 0:h.identifier)!==o&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Uu(a)}`),this.hls.trigger(Is.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=e,n=this.getEventItem(i.identifier);if(!n)return;if(e.loadSource(),this.setBufferingItem(n),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))return void this.advanceAssetBuffering(n,r);const a=this.getBufferingPlayer();if(a===e)return;const o=i.appendInPlace;if(o&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const l=(null==a?void 0:a.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(o&&r!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(l&&!cl(l,e.tracks)){const t=new Error(`Asset ${Uu(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),s={fatal:!0,type:Ts.OTHER_ERROR,details:ws.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=i.findAssetIndex(r);return void this.handleAssetItemError(s,i,this.findEventIndex(i.identifier),n,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s,a.currentTime))&&a.hls){const s=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,r)}}}}advanceInPlace(e){const t=this.primaryMedia;if(t&&t.currentTime<e){const s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,i,r){if(e.details===ws.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Uu(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,d=zo({},e,{fatal:!1,errorAction:Vh(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(Is.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let e=i;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==c?void 0:c.identifier)===a?this.advanceAfterAssetEnded(t,s,i):(null==u?void 0:u.identifier)===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${a} playing: ${Nu(s)} startPosition: ${n} seekableStart: ${r} error: ${e.error}`),-1===a&&(a=n),a=Math.max(a,r);const i=this.updateItem(s,a);this.itemsMatch(s,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(i))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(r,t,h,o+h,s,e.URI),h+=s}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(i=this.bufferingItem)?void 0:i.event;if(c){const e=this.findEventIndex(n),t=this.getEventItem(n);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r);this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ws.ASSET_LIST_PARSING_ERROR:case ws.ASSET_LIST_LOAD_ERROR:case ws.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ws.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);const t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==t?void 0:t.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},to=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,i)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Is.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Is.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Is.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ws.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}},so=class extends er{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",Ps.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Is.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Is.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Is.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Is.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Zi.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,part:i,success:r}=t;if(!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=(i||s).start;for(let e=0;e<n.length;e++)if(o>=n[e].start&&o<=n[e].end){a=n[e];break}const l=o+(i||s).duration;if(a?a.end=l:(a={start:o,end:l},n.push(a)),!i||l>=s.end){const e=this.fragmentTracker.fragBuffered(s);i&&e&&(e.range.subs={time:[{startPTS:s.start,endPTS:l}],partial:!0}),Wo(s)&&!this.fragContextChanged(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(0===s&&i!==Number.POSITIVE_INFINITY){const e=i-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}}),this.fragmentTracker.removeFragmentsInRange(s,e,Ps.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===Ps.SUBTITLE&&(t.details===ws.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Zi.STOPPED&&(this.state=Zi.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Rc(this.levels,t)?this.levels=t.map(e=>new ui(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new ui(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ps.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Zi.STOPPED&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let h=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var d;o.details&&(h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)),n.alignedSliding||(qd(l,n,this),h=n.fragmentStart)}o.details=n,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,h),a===i&&(this.hls.trigger(Is.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:t,part:s,payload:i}=e;s&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,s)}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e;!this.fragContextChanged(t)&&null!=s&&s.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(s,t,null)}shouldDecrypt(e){const t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&ld(t.method))}decryptPayload(e,t,s){const i=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,hd(i.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(Is.FRAG_DECRYPTED,{frag:t,part:s,payload:e,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:s}),s||(this.warn(`${e.name}: ${e.message}`),this.state=Zi.IDLE)})}doTick(){if(this.state===Zi.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=_i.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:h,len:d}=l;if(d>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||d&&!this.buffering)return;let c=this.getNextFragment(h,n);if(!c)return;if(Wo(c)){var t;const e=c.sn-n.startSN,s=n.fragments[e-1];c.cc!==(null==s?void 0:s.cc)||null!=(t=n.partList)&&t.length||this.fragmentTracker.getState(s)!==Ei.NOT_LOADED||(c=s)}this.loadFragment(c,r,h)}}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i!==Ei.NOT_LOADED&&i!==Ei.PARTIAL||super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new io(this.tracksBuffered[this.currentTrackId]||[])}},io=class{constructor(e){this.buffered=void 0;const t=(t,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}},ro={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},no=e=>String.fromCharCode(ro[e]||e),ao=15,oo=42,lo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ho={17:2,18:4,21:6,22:8,23:10,19:13,20:15},co={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},uo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],go=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;Gs.log(`${this.time} [${e}] ${s}`)}}},mo=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},po=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),vo=class{constructor(){this.styles=po}get foreground(){return this.styles.foreground}set foreground(e){const t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){const t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){const t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=po}setStyles(e){const t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},yo=class{constructor(){this.uchar=" ",this.penState=new vo}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},So=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new vo,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<oo;e++)this.chars.push(new yo);this.logger=e}equals(e){const t=this.chars,s=e.chars;for(let e=0;e<oo;e++){const i=t[e],r=s[e];if(i.uchar!==r.uchar)return!1;const n=i.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(e){for(let t=0;t<oo;t++)this.chars[t].copy(e.chars[t])}isEmpty(){const e=this.chars;for(let t=0;t<oo;t++){const s=e[t];if(" "!==s.uchar)return!1;const i=s.penState.styles;if(i!==po&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=oo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(e){const t=Math.min(this.pos+e,oo);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=no(e);this.pos>=oo?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<oo;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<oo;s++){const i=this.chars[s].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Eo=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ao;t++)this.rows.push(new So(e));this.logger=e}reset(){for(let e=0;e<ao;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<ao;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ao;t++){const s=this.rows[t].chars,i=e.rows[t].chars;for(let e=0;e<oo;e++){const t=s[e],r=i[e];t.uchar=r.uchar,t.penState.styles=r.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<ao;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 = "+gi(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<ao;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[e].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[t-this.nrRollUpRows+i+1].copy(s.rows[e+i])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,i=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[i].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+gi(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let s=0;s<ao;s++){const r=this.rows[s].getTextString();r&&(i=s+1,e?t.push("Row "+i+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}},bo=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Eo(s),this.nonDisplayedMemory=new Eo(s),this.lastOutputScreen=new Eo(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+gi(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},To=class{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new go,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,null==(s=this.channels[e])||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new bo(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const s=127&t[e],i=127&t[e+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,()=>"["+mo([t[e],t[e+1]])+"] -> ("+mo([s,i])+")");const a=this.cmdHistory;if(s>=16&&s<=31){if(Wu(s,i,a)){Hu(null,null,a),this.logger.log(3,()=>"Repeated command ("+mo([s,i])+") is dropped");continue}Hu(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else Hu(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+mo([s,i])+" orig: "+mo([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,i=this.getChannel(s);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+mo([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;const i=e<=23?1:2;return s=t>=64&&t<=95?1===i?lo[e]:co[e]:1===i?ho[e]:uo[e],this.getChannel(i).setPAC(this.interpretPAC(s,t)),this.currentChannel=i,!0}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+no(e)+"' in channel "+s),i=[e]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+mo(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let s;const i={};16===e||24===e?(s=Math.floor((t-32)/2),i.background=fo[s],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));const r=e<=23?1:2;return this.getChannel(r).setBkgData(i),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Hu(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}},wo=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Io=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Is.FRAG_LOADING,this.onFragLoading,this),e.on(Is.FRAG_LOADED,this.onFragLoaded,this),e.on(Is.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Is.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Is.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Is.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Is.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Is.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Is.FRAG_LOADING,this.onFragLoading,this),e.off(Is.FRAG_LOADED,this.onFragLoaded,this),e.off(Is.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Is.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Is.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Is.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Is.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Is.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new wo(this,"textTrack1"),t=new wo(this,"textTrack2"),s=new wo(this,"textTrack3"),i=new wo(this,"textTrack4");this.cea608Parser1=new To(1,e,t),this.cea608Parser2=new To(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let e=r.length;e--;){const i=r[e],a=qu(i[0],i[1],t,s);if(a>=0&&(i[0]=Math.min(i[0],t),i[1]=Math.max(i[1],s),n=!0,a/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const r=this.cueCache[e];if(r){const e=this.Cues.newCue(null,t,s,i);e.length&&r.push.apply(r,e)}else{const r=this.captionsTracks[e].track;this.Cues.newCue(r,t,s,i)}}else{var a;const r=this.Cues.newCue(null,t,s,i),n=null==(a=this.captionsProperties[e])?void 0:a.media;this.hls.trigger(Is.CUES_PARSED,{type:"captions",cues:r,track:e,closedCaptions:n})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){const{unparsedVttFrags:i}=this;t===Ps.MAIN&&(this.initPTS=s),i.length&&(this.unparsedVttFrags=[],i.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Is.FRAG_LOADED,e):this.hls.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,cueCache:i,media:r}=this,{label:n,languageCode:a}=t[e];r&&(i[e]=[],s[e]=Tu(r,"captions",n,a,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Is.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:e,cueCache:t}=this;for(const s in e)e[s].remove(),delete t[s]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!Rc(this.tracks,s)){const e=s.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(Is.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,i=this.captionsProperties[s];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Ps.MAIN){var s,i;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(i=t.part)?void 0:i.index)?s:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.level<this.tracks.length&&s.type===Ps.SUBTITLE)if(i.byteLength){const e=s.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),(null==e?void 0:e.textCodec)===Da?this._parseIMSC1(t):this._parseVTTs(t)}}else{const e="part"in t?t.part:null;this.hls.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:e,error:new Error("Empty subtitle payload")})}}_parseIMSC1(e){const{frag:t,payload:s}=e,i="part"in e?e.part:null,r=this.hls;mu(s,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),r.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:i})},e=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),r.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:i,error:e})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,r="part"in e?e.part:null,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&-1===o)return void a.push(e);const l=this.hls,h=null==(t=s.initSegment)?void 0:t.data;!function(e,t,s,i,r,n,a){const o=new ka,l=bl(new Uint8Array(e)).trim().replace(Ra,"\n").split("\n"),h=[],d=t?function(e,t=1){return yc(e,$r,1/t)}(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!1,p=!0;o.oncue=function(e){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(m){if(null!=n&&n.new&&(a=s.ccOffset=n.start),o){if(!t)return void(c=new Error(Ca+"MPEGTS"));a=o-s.presentationOffset}}else{if(!t)return void(c=new Error(Ca+"without X-TIMESTAMP-MAP"));a=-t.baseTime/t.timescale}const l=e.endTime-e.startTime,u=Tc(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?i&&(e.id=`hlsjscc${i}_${e.id}`):e.id=gu(e.startTime,e.endTime,p),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(h)},l.forEach(e=>{if(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,m=!0,e.slice(16).split(",").forEach(e=>{e.startsWith("LOCAL:")?u=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=Pa(u)/1e3}catch(e){c=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}(h?eh(h,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!h?r:s).start,e=>{this._appendCues(e,s.level),l.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},t=>{const i=t.message.startsWith("Missing initPTS");l.logger.log(`${i?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${t}`),i?a.push(e):(this.config.enableIMSC1&&this._fallbackToIMSC1(e),l.trigger(Is.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:t}))})}_fallbackToIMSC1(e){const{frag:t,payload:s}=e,i=this.tracks[t.level];i.textCodec||mu(s,this.initPTS[t.cc],()=>{i.textCodec=Da,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const s=null==(i=this.tracks[t].trackNode)?void 0:i.track;if(!s||"disabled"===s.mode)return;e.forEach(e=>wu(s,e))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(Is.CUES_PARSED,{type:"subtitles",cues:e,track:r,subtitleTrack:i})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===Ps.SUBTITLE&&this.onFragLoaded(Is.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(s.type!==Ps.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(t);this.cea608Parser1.addData(i[e].pts,s[0]),this.cea608Parser2.addData(i[e].pts,s[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var s;const{type:e,timeRanges:i}=t;if("video"===e&&null!=(s=i[e])&&s.length){const{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(s=>{var i;const r=null==(i=e[s])?void 0:i.track;if(r){const e=t[s];for(let t=0;t<e.length;t++)wu(r,e[t])}delete t[s]})}}}onBufferFlushing(e,t){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:n}=t,{media:a}=this;if(a&&!(a.currentTime<i)){if(!n||"video"===n){const{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Iu(e[t].track,s,i)),Object.keys(t).forEach(e=>{const r=t[e];for(let e=r.length;e--;){const t=r[e];t.startTime>=s&&t.endTime<=i&&r.splice(e,1)}})}this.config.renderTextTracksNatively&&0===s&&void 0!==r&&this.tracks.forEach(e=>{var t;const i=null==(t=e.trackNode)?void 0:t.track;i&&Iu(i,s,r)})}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let i=2;for(let r=0;r<s;r++){const s=e[i++],r=127&e[i++],n=127&e[i++];if((0!==r||0!==n)&&4&s){const e=3&s;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},Lo=/\s/,Ao={newCue(e,t,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)Lo.test(n.chars[e].uchar)&&o?l++:(h+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const i=uu(h.trim()),f=gu(t,s,i);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new d(t,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>wu(e,t))),r}},ko=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Rs}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(nl(e,this.stats.retry,!0))this.retry(e);else{var t;Gs.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=il(e,s.retry),s.retry++,Gs.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}},Ro=/(\d+)-(\d+)\/(\d+)/,Co=class extends ko{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||Ku}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:t,stats:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=function(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(zo({},e.headers))};return e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),s}(t,this.controller.signal),r="arraybuffer"===t.responseType,n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:o}=e.loadPolicy;this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=a&&Ss(a)?a:o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(kc(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var n;this.response=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},o-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new Po(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Ro.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ss(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}(i.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&Ss(e.highWaterMark)?this.loadProgressively(i,s,t,e.highWaterMark,l):r?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{var r,a;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[n];l&&(s.loaded=s.total=l);const h={url:o.url,data:i,code:o.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!Ss(e.highWaterMark)&&d(s,t,i,o),null==(a=this.callbacks)||a.onSuccess(h,s,t,o)}).catch(i=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=i&&i.code||0,n=i?i.message:null,a=e.loadPolicy.errorRetry;var o;nl(a,s.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(a):(Gs.error(`${r} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},t,i?i.details:null,s))})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new tr,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}},Po=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},Do=(e,t,s)=>Math.max(t,Math.min(e,s)),Mo=/^age:\s*[\d.]+\s*$/im,_o=class extends ko{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r.call(this,s,t.url,t)}).catch(e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:e.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[t]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&Ss(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,l="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const r=null!=l?l:t.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,r,t);const h={url:t.responseURL,data:r,code:i};return e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&Gs.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(h,s,e,t))}}const h=r.loadPolicy.errorRetry;var o;nl(h,s.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(h):(Gs.error(`${i} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:i,text:t.statusText},e,t,s))}}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Mo.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}},Oo={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},xo=Xo(Xo({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:_o,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:qi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:Oo},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:$a,abrController:mi,bufferController:on,capLevelController:ln,errorController:Si,fpsController:ba,id3TrackController:Ua,gapController:Fa,latencyController:to},{cueHandler:Ao,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:so,subtitleTrackController:xa,timelineController:Io,audioStreamController:Jr,audioTrackController:en,emeController:Ea,cmcdController:va,contentSteeringController:ya,iframeController:Ka,interstitialsController:eo}),Fo=class extends Zr{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Is.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Is.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Is.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Is.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1,h=!1;t.levels.forEach(e=>{const t=e.attrs,d=Qu(e,s),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:m}=e;if(!d)return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);a||(a=!(!g||!m)),o||(o=!!u),l||(l=!!c),h||(h=!!f);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":S,RESOLUTION:E,"VIDEO-RANGE":b}=t,T=`${S||"."}-${e.bitrate}-${E}-${v}-${p}-${b}-${y}`;if(r[T])if(r[T].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(r[T].addGroupId("audio",t.AUDIO),r[T].addGroupId("text",t.SUBTITLES));else{const t=n[T]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);r[T]=s,i.push(s)}else{const t=this.createLevel(e);r[T]=t,n[T]=1,i.push(t)}}),this.filterAndSortMediaOptions(i,t,a,o,l,h)}createLevel(e){const t=new ui(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!zu(s.videoCodec,this.hls.config.preferManagedMediaSource)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=Th(e,[])}return t}filterAndSortMediaOptions(e,t,s,i,r,n){var a;let o=[],l=[],h=e;const d=(null==(a=t.stats)?void 0:a.parsing)||{},c=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(h=h.filter(({videoCodec:e,videoRange:t,width:s,height:i})=>{return(!!e||!(!s||!i))&&!!(r=t)&&hi.indexOf(r)>-1;var r})),i&&n&&(h=h.filter(e=>!e.imageCodec)),0===h.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${gi(t.levels.map(e=>e.attrs.CODECS).filter((e,t,s)=>s.indexOf(e)===t))}`,this.warn(s),e+=` (${s})`);const i=new Error(e);this.hls.trigger(Is.ERROR,{type:Ts.MEDIA_ERROR,details:ws.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:s})}}),void(d.end=performance.now());t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Yu(e.audioCodec,c)),Xu(o)),t.subtitles&&(l=t.subtitles,Xu(l));const u=h.slice(0);h.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return hi.indexOf(e.videoRange)-hi.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=gh(e.videoCodec),i=gh(t.videoCodec);if(s!==i)return i-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=mh(e.codecSet),i=mh(t.codecSet);if(s!==i)return i-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let f=u[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==u.length))for(let e=0;e<u.length;e++)if(u[e].pathwayId===h[0].pathwayId){f=u[e];break}this._levels=h;for(let e=0;e<h.length;e++)if(h[e]===f){var g;this._firstLevel=e;const t=f.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${t}`),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const m=t.iframeVariants.filter(e=>Qu(e,c));this._iframeVariants=m;const p=r&&!i,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),S={levels:h,audioTracks:o,subtitleTracks:l,iframeVariants:m,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!p&&o.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(Is.MANIFEST_PARSED,S)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:s,reason:s.message}),i)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Is.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===Cs.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===Ps.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(i,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(Is.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){const s=this.hls.config.abrSwitchInterval;if(s>0){const i=performance.now(),r=i-this.lastABRSwitchTime,n=1e3*s;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms < ${n}ms / ${s}s)`);this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms >= ${n}ms / ${s}s)`)}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Ud(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Is.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Is.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}},Bo=class extends Bs{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);const i=e.decryptdata;if(!i){const t=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,t))}const r=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){const t=function(e){const t=[];return Ql(e,e=>t.push(e.subarray(8,24))),t}(e.initSegment.data);if(t.length){let s=t[0];const i=e.decryptdata.uri;if(s.some(e=>0!==e))this.log(`Using keyId found in init segment ${Rl(s)} keyUri: ${i}`),Ki.setKeyIdForUri(i,s);else{const e=Ki.addKeyIdForUri(i);this.log(`Patching empty keyId with ${Rl(e)} keyUri: ${i}`),s=e}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(Ju(e,ws.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return t.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(s=>(t.key=i.decryptdata.key,Xo(Xo({},s),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Rl(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);const r=this.config,n=new(0,r.loader)(r);e.keyLoader=n;const a=this.keyLoaderInfo[s]={decryptdata:t,keyLoadPromise:null,loader:n};return a.keyLoadPromise=new Promise((t,i)=>{const o={type:Cs.KEY,keyInfo:a,frag:e,responseType:"arraybuffer",url:s},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,s,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyLoaderInfo[l])return i(Ju(a,ws.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=o.loader=o.keyLoadPromise=null,t({frag:a,keyInfo:o})},onError:(t,r,n,a)=>{this.resetLoader(r),i(Ju(e,ws.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),n,Xo({url:s,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),i(Ju(e,ws.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),i(Ju(e,ws.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};n.load(o,h,d)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}},Uo=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Is.LEVEL_LOADING,this.onLevelLoading,this),e.on(Is.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Is.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Is.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Is.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Is.LEVEL_LOADING,this.onLevelLoading,this),e.off(Is.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Is.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Is.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Cs.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Cs.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Cs.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Cs.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[Cs.LEVEL];if(s){const e=s.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(s.abort(),delete this.loaders[Cs.LEVEL])}}load(e){var t;const s=this.hls.config;let i,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,s=r.context;if((null==s?void 0:s.levelOrTrack)===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(i=e.type===Cs.MANIFEST?s.manifestLoadPolicy.default:zo({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Ss(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===Cs.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Cs.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Cs.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);i=zo({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),Ji.isMediaPlaylist(n)||s.type!==Cs.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,s,i||null,r):this.handleMasterPlaylist(e,t,s,i)},onError:(e,t,s,i)=>{this.handleNetworkError(t,s,!1,e,i)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=ef(e,s),o=Ji.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);const{contentSteering:l,levels:h,iframeVariants:d,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g,h.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:i,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];ch(a,"audio",s)?(e.audioCodec=i=i?`${i},${a}`:a,ii.audio[i.substring(0,4)]=2,t.splice(n,1)):ch(a,"video",s)&&(e.videoCodec=r=r?`${r},${a}`:a,ii.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Ji.parseMasterPlaylistMedia(n,a,o);m.length&&(m.some(e=>!e.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Bi({}),bitrate:0,url:""}))),r.trigger(Is.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,iframeVariants:d,captions:v,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=ef(e,s),d=Ss(o)?o:Ss(a)?a:0,c=Zu(s),u=Ji.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(l===Cs.MANIFEST){const e={attrs:new Bi({}),bitrate:0,details:u,name:"",url:h};u.requestScheduled=t.loading.start+Od(u,0),n.trigger(Is.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.MANIFEST_PARSING_ERROR,fatal:t.type===Cs.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Cs.LEVEL?n+=`: ${e.level} id: ${e.id}`:e.type!==Cs.AUDIO_TRACK&&e.type!==Cs.SUBTITLE_TRACK||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ws.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Cs.MANIFEST:o=s?ws.MANIFEST_LOAD_TIMEOUT:ws.MANIFEST_LOAD_ERROR,l=!0;break;case Cs.LEVEL:o=s?ws.LEVEL_LOAD_TIMEOUT:ws.LEVEL_LOAD_ERROR,l=!1;break;case Cs.AUDIO_TRACK:o=s?ws.AUDIO_TRACK_LOAD_TIMEOUT:ws.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Cs.SUBTITLE_TRACK:o=s?ws.SUBTITLE_TRACK_LOAD_TIMEOUT:ws.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const d={type:Ts.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};if(i){let s=e.url;t&&"url"in t&&(s=t.url),d.response=Xo({url:s,data:void 0},i)}this.hls.trigger(Is.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:u}=i,f=ef(t,i),g=Zu(i);let m="number"==typeof i.level&&g===Ps.MAIN?l:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(Is.ERROR,{type:Ts.NETWORK_ERROR,details:ws.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:i,level:m,parent:g,networkDetails:r,stats:s})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Cs.MANIFEST:case Cs.LEVEL:if(m)if(h){if(h!==a.levels[m]){const e=a.levels.indexOf(h);e>-1&&(m=e)}}else m=0;a.trigger(Is.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:m||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===Cs.MANIFEST,context:i});break;case Cs.AUDIO_TRACK:a.trigger(Is.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i});break;case Cs.SUBTITLE_TRACK:a.trigger(Is.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:s,networkDetails:r,deliveryDirectives:u,context:i})}}},(No=class e{static get version(){return nr}static isMSESupported(){return Mu()}static isSupported(){return _u()}static getMediaSource(){return dl()}static get Events(){return Is}static get MetadataSchema(){return or}static get ErrorTypes(){return Ts}static get ErrorDetails(){return ws}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:xo}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new rr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const s=this.logger=function(e,t,s){const i=ll();if("object"==typeof console&&!0===e||"object"==typeof e){const t=["debug","log","info","warn","error"];t.forEach(t=>{i[t]=hl(t,e,s)});try{i.log('Debug logs enabled for "Hls instance" in hls.js version 1.7.0')}catch(e){return ll()}t.forEach(t=>{$s[t]=hl(t,e)})}else zo($s,i);return i}(t.debug||!1,0,t.loggerId||t.assetPlayerId),i=this.config=function(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){const e=t.liveMaxUnchangedPlaylistRefresh,i=Do(e,2,1/0);i!==e&&s.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${i}.`),t.liveMaxUnchangedPlaylistRefresh=i}const i=Vu(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(s=>{const r=`${e}Loading${s}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=i[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${gi(t[n])}`)}),Xo(Xo({},i),t)}(e.DefaultConfig,t,s);this.userConfig=t,i.progressive&&function(e,t){const s=e.loader;s!==Co&&s!==_o?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):ju()&&(e.loader=Co,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,s);const{streamController:r,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),m=new bi(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,e):null,y=a?this.bufferController=new a(this,m):null,S=o?this.capLevelController=new o(this):null,E=h?new h(this):null,b=i.cmcdController,T=b?this.cmcdController=new b(this):null,w=new Uo(this),I=i.contentSteeringController,L=I?new I(this):null,A=this.levelController=new Fo(this,L),k=d?new d(this):void 0,R=new Bo(this.config,this.logger),C=this.streamController=new r(this,m,R),P=this.gapController=u?new u(this,m):void 0;S&&S.setStreamController(C);const D=[w,A,C];v&&D.splice(1,0,v),L&&D.splice(1,0,L),this.networkControllers=D;const M=[g];y&&M.push(y),P&&M.push(P),S&&M.push(S),E&&(E.setStreamController(C),M.push(E)),k&&M.push(k),M.push(m),this.audioTrackController=this.createController(i.audioTrackController,D);const _=i.audioStreamController;_&&D.push(this.audioStreamController=new _(this,m,R)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);const O=i.subtitleStreamController;O&&D.push(this.subtititleStreamController=new O(this,m,R)),this.createController(i.timelineController,M),R.emeController=this.emeController=this.createController(i.emeController,M),T&&M.push(T),this.latencyController=this.createController(i.latencyController,M),this.coreComponents=M,this.iframeController=c?new c(this,e):void 0,D.push(f);const x=f.onErrorOut;"function"==typeof x&&this.on(Is.ERROR,x,f),this.on(Is.MANIFEST_LOADED,w.onManifestLoaded,w)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===Is.ERROR;this.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Is.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Is.ERROR,{type:Ts.OTHER_ERROR,details:ws.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(Is.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(Is.MEDIA_DETACHING,e),this._media=null,this.trigger(Is.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(Is.MEDIA_DETACHING,s),this.trigger(Is.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();const s=this.media,i=this._url,r=this._url=ks.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(Is.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started&&this.streamController.state!==Zi.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Ps.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Ps.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Ps.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=this.started,s=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=gl()),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=this.capLevelController,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return li.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=i;t--;){const i=e[t].attrs["HDCP-LEVEL"];if(i&&i<=s)return t}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1}set nextAudioTrack(e){const{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}get latency(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}get maxLatency(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}get targetLatency(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){return Ih(e,Dh(t),navigator.mediaCapabilities)}}).defaultConfig=void 0}});function sf(e,t){return t?`${e}|${t.start}-${t.end}`:e}function rf(e,t){if(void 0!==e&&void 0!==t&&e<=t)return{start:e,end:t}}var nf,af,of,lf,hf,df,cf,uf,ff,gf,mf,pf,vf,yf,Sf,Ef,bf,Tf,wf=o({"../../node_modules/p2p-media-loader-hlsjs/lib/utils.js"(){}}),If=o({"../../node_modules/p2p-media-loader-core/lib/types.js"(){nf=class extends Error{constructor(e,t,s){super(t),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=s}},af=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerError"})}},of=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerWarning"})}},lf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TrackerError"})}},hf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"TrackerWarning"})}},df=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PeerConnectError"})}},cf=class extends nf{constructor(e,t,s){super(e,t,s),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RequestError"}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.timestamp=performance.now()}},uf=class extends nf{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CoreRequestError"})}}}}),Lf=o({"../../node_modules/p2p-media-loader-core/lib/utils/abort-controller.js"(){ff=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},mf=class{constructor(){Object.defineProperty(this,"aborted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),gf.set(this,new Set)}addEventListener(e,t){ff(this,gf,"f").add(t)}removeEventListener(e,t){ff(this,gf,"f").delete(t)}dispatchEvent(e){this.aborted=!0;for(const e of ff(this,gf,"f"))try{e()}catch(e){}ff(this,gf,"f").clear()}},gf=new WeakMap,pf=class{constructor(){Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:new mf})}abort(){this.signal.dispatchEvent("abort")}},vf="undefined"!=typeof AbortController,yf=vf?AbortController:pf}}),Af=o({"../../node_modules/p2p-media-loader-core/lib/http-loader.js"(){If(),Lf(),Sf=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ef=class{isAborted(){return this.abortController.signal.aborted}constructor(e,t,s){Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"httpConfig",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:new yf}),Object.defineProperty(this,"expectedBytesLength",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestByteRange",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onChunkDownloaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.onChunkDownloaded=s.getEventDispatcher("onChunkDownloaded");const{byteRange:i}=this.request.segment;i&&(this.requestByteRange=Object.assign({},i))}execute(){var e;const t={onAbort:()=>this.abortController.abort(),notReceivingBytesTimeoutMs:this.httpConfig.httpNotReceivingBytesTimeoutMs};if(this.request.tryCompleteByLoadedBytes({downloadSource:"http"},t,this.httpConfig.validateHTTPSegment,"http-segment-validation-failed"))return;0!==this.request.loadedBytes&&(this.requestByteRange=null!==(e=this.requestByteRange)&&void 0!==e?e:{start:0},this.requestByteRange.start=this.requestByteRange.start+this.request.loadedBytes),this.request.totalBytes&&(this.expectedBytesLength=this.request.totalBytes-this.request.loadedBytes);const s=this.request.start({downloadSource:"http"},t);this.fetch(s)}fetch(e){return Sf(this,void 0,void 0,function*(){var t,s,i;const{segment:r}=this.request;let n;if(this.isAborted())return;const a=()=>{try{null==n||n.cancel().catch(()=>{})}catch(e){}};this.abortController.signal.addEventListener("abort",a);const o=vf?this.abortController.signal:void 0;try{let a=yield null===(s=(t=this.httpConfig).httpRequestSetup)||void 0===s?void 0:s.call(t,r.url,r.byteRange,o,this.requestByteRange);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!a){const e=new Headers;this.requestByteRange&&e.set("Range",`bytes=${this.requestByteRange.start}-${null!==(i=this.requestByteRange.end)&&void 0!==i?i:""}`);const t={headers:e};o&&(t.signal=o),a=new Request(r.url,t)}if(this.isAborted())throw new DOMException("Request aborted before request fetch","AbortError");const l=yield window.fetch(a);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(this.handleResponseHeaders(l),e.firstBytesReceived(),l.body&&"function"==typeof l.body.getReader){const t=l.body.getReader();for(n=t;;){if(this.isAborted())throw new DOMException("Request aborted","AbortError");const{done:s,value:i}=yield t.read();if(s)break;if(this.isAborted())throw new DOMException("Request aborted","AbortError");e.addLoadedChunk(i),this.onChunkDownloaded(i.byteLength,"http",void 0,r.stream.type,this.request.infoHash)}}else{const t=yield l.arrayBuffer();if(this.isAborted())throw new DOMException("Request aborted","AbortError");const s=new Uint8Array(t);e.addLoadedChunk(s),this.onChunkDownloaded(s.byteLength,"http",void 0,r.stream.type,this.request.infoHash)}if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(void 0!==this.request.totalBytes&&this.request.loadedBytes!==this.request.totalBytes)throw new cf("http-bytes-mismatch",`HTTP response truncated: received ${this.request.loadedBytes} of ${this.request.totalBytes} bytes`);const h=yield this.request.validateData(this.httpConfig.validateHTTPSegment);if(this.isAborted())throw new DOMException("Request aborted","AbortError");if(!h)throw this.request.clearLoadedBytes(),new cf("http-segment-validation-failed");e.completeOnSuccess()}catch(t){this.handleError(t,e)}finally{this.abortController.signal.removeEventListener("abort",a)}})}handleResponseHeaders(e){if(!e.ok)throw 406===e.status||416===e.status?(this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText)):new cf("http-error",e.statusText);const{requestByteRange:t}=this;if(t)if(200===e.status){if(this.request.segment.byteRange)throw new cf("http-unexpected-status-code");this.request.clearLoadedBytes()}else{if(206!==e.status)throw new cf("http-unexpected-status-code",e.statusText);const s=e.headers.get("Content-Length");if(s&&void 0!==this.expectedBytesLength&&this.expectedBytesLength!==+s)throw this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText);const i=e.headers.get("Content-Range"),r=i?function(e){const t=bf.exec(e.trim());if(!t)return;const[,s,i,r]=t;return{from:s?parseInt(s):void 0,to:i?parseInt(i):void 0,total:r?parseInt(r):void 0}}(i):void 0;if(r){const{from:s,to:i}=r,n=void 0!==i&&void 0!==s?i-s+1:void 0;if(void 0!==n&&this.expectedBytesLength!==n||void 0!==s&&t.start!==s||void 0!==i&&void 0!==t.end&&t.end!==i)throw this.request.clearLoadedBytes(),new cf("http-bytes-mismatch",e.statusText)}}if(200===e.status&&void 0===this.request.totalBytes){const t=e.headers.get("Content-Length");t&&this.request.setTotalBytes(+t)}}handleError(e,t){if(!this.isAborted()&&e instanceof Error){const s=e instanceof cf?e:new cf("http-error",e.message);t.failWithError(s)}}},bf=/^bytes (?:(?:(\d+)|)-(?:(\d+)|)|\*)\/(?:(\d+)|\*)$/}}),kf=l({"../../node_modules/ms/index.js"(e,t){var s=1e3,i=60*s,r=60*i,n=24*r,a=7*n;function o(e,t,s,i){var r=t>=1.5*s;return Math.round(e/s)+" "+i+(r?"s":"")}t.exports=function(e,t){t=t||{};var l,h,d=typeof e;if("string"===d&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return o*a;case"days":case"day":case"d":return o*n;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*i;case"seconds":case"second":case"secs":case"sec":case"s":return o*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===d&&isFinite(e))return t.long?(l=e,(h=Math.abs(l))>=n?o(l,h,n,"day"):h>=r?o(l,h,r,"hour"):h>=i?o(l,h,i,"minute"):h>=s?o(l,h,s,"second"):l+" ms"):function(e){var t=Math.abs(e);return t>=n?Math.round(e/n)+"d":t>=r?Math.round(e/r)+"h":t>=i?Math.round(e/i)+"m":t>=s?Math.round(e/s)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}}),Rf=l({"../../node_modules/debug/src/common.js"(e,t){t.exports=function(e){function t(e){let i,r,n,a=null;function o(...e){if(!o.enabled)return;const s=o,r=Number(new Date),n=r-(i||r);s.diff=n,s.prev=i,s.curr=r,i=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,r)=>{if("%%"===i)return"%";a++;const n=t.formatters[r];if("function"==typeof n){const t=e[a];i=n.call(s,t),e.splice(a,1),a--}return i}),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=s,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==t.namespaces&&(r=t.namespaces,n=t.enabled(e)),n),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function s(e,s){const i=t(this.namespace+(void 0===s?":":s)+e);return i.log=this.log,i}function i(e,t){let s=0,i=0,r=-1,n=0;for(;s<e.length;)if(i<t.length&&(t[i]===e[s]||"*"===t[i]))"*"===t[i]?(r=i,n=s,i++):(s++,i++);else{if(-1===r)return!1;i=r+1,n++,s=n}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of s)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(i(e,s))return!1;for(const s of t.names)if(i(e,s))return!0;return!1},t.humanize=kf(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(s=>{t[s]=e[s]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}}}),Cf=l({"../../node_modules/debug/src/browser.js"(e,t){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const s="color: "+this.color;e.splice(1,0,s,"color: inherit");let i=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(r=i))}),e.splice(r,0,s)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(e){}},e.load=function(){let t;try{t=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch(e){}return!t&&"undefined"!=typeof process&&"env"in process&&(t=process.env.DEBUG),t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(e){}}(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),t.exports=Rf()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}}),Pf=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/types.js"(){var e;(e=Tf||(Tf={}))[e.SegmentsAnnouncement=0]="SegmentsAnnouncement",e[e.SegmentRequest=1]="SegmentRequest",e[e.SegmentData=2]="SegmentData",e[e.SegmentDataSendingCompleted=3]="SegmentDataSendingCompleted",e[e.SegmentAbsent=4]="SegmentAbsent",e[e.CancelSegmentRequest=5]="CancelSegmentRequest"}});function Df(){let e,t;return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}function Mf(e){Promise.resolve().then(e)}function _f(e,t){null!=t||(t=e.reduce((e,t)=>e+t.byteLength,0));const s=new Uint8Array(t);let i=0;for(const t of e)s.set(t,i),i+=t.byteLength;return s}function*Of(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function xf(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Ff(e){if(function(e){return Array.isArray(e)}(e))return e.map(e=>Ff(e));if(xf(e)){const t={};for(const s of Object.keys(e))t[s]=Ff(e[s]);return t}return e}function Bf(e,t,s={}){return"object"!=typeof e||null===e||"object"!=typeof t||null===t||Object.keys(t).forEach(i=>{const r="symbol"==typeof i?i.toString():String(i);if("__proto__"===i||"constructor"===i||"prototype"===i)throw new Error(`Attempt to modify restricted property '${r}'`);const n=t[i],a=s[i];i in e&&(e[i]=void 0===n?void 0===a?void 0:a:n)}),e}function Uf(e){const{defaultConfig:t,baseConfig:s={},specificStreamConfig:i={}}=e,r=Ff(Object.assign(Object.assign(Object.assign({},t),s),i)),n=Object.keys(t),a={};return n.forEach(e=>{e in r&&(a[e]=r[e])}),a}var Nf,$f,Gf,Hf,Wf,qf,jf,Kf,Vf,Yf,zf=o({"../../node_modules/p2p-media-loader-core/lib/utils/utils.js"(){}});function Qf(e){const t=e.length,s=(e,s)=>{const i=8*(t-1-s);return e*Math.pow(2,i)};let i=s(127&e[0],0);for(let r=1;r<t;r++)i+=s(e[r],r);return(128&e[0])>>7&&(i=-i),i}function Xf(e){const t=function(e){const t=e<0,s=function(e){if(0===e)return 1;const t=Math.floor(Math.log2(Math.abs(e)))+2;return Math.ceil(t/8)}(e),i=new Uint8Array(s);e=Math.abs(e);for(let t=0;t<s;t++){const r=8*(s-1-t),n=255&Math.floor(e/Math.pow(2,r));i[t]=n}return t&&(i[0]=128|i[0]),i}(e),s=Vf.Int<<4|t.length;return new Uint8Array([s,...t])}function Jf(e){if(0===e.length)throw new Error("Buffer is too short");const t=e[0];if(t>>4!==Vf.Int)throw new Error("Trying to deserialize integer with invalid serialized item code");const s=15&t;if(0===s)throw new Error("Invalid integer: zero byte length");if(s>7)throw new Error("Invalid integer: byte length exceeds safe integer limit");const i=1+s;if(e.length<i)throw new Error("Buffer is too short");return{number:Qf(e.subarray(1,i)),byteLength:s+1}}function Zf(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!==Vf.SimilarIntArray)throw new Error("Trying to deserialize similar int array with invalid serialized item code");let i=2;const r=[];for(let t=0;t<s;t++){const{number:t,byteLength:s}=Jf(e.subarray(i));i+=s;const n=255&t,a=0===n?256:n,o=t-n;if(i+a>e.length)throw new Error("Malformed similar int array: buffer too short");for(let t=0;t<a;t++){const t=e[i];r.push(o+t),i++}}return{numbers:r,byteLength:i}}function eg(e){if(e.length<2)throw new Error("Buffer is too short");const[t,s]=e;if(t>>4!==Vf.String)throw new Error("Trying to deserialize bytes (sting) with invalid serialized item code.");const i=(15&t)<<8|s;if(e.length<i+2)throw new Error("Malformed string: buffer too short");const r=e.subarray(2,i+2);return{string:Kf.decode(r),byteLength:i+2}}var tg,sg,ig,rg,ng,ag,og,lg,hg,dg,cg,ug,fg,gg,mg,pg,vg,yg,Sg,Eg,bg,Tg,wg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/binary-serialization.js"(){var e;zf(),Nf=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$f=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},jf=new TextEncoder,Kf=new TextDecoder("utf8"),(e=Vf||(Vf={}))[e.Min=-1]="Min",e[e.Int=0]="Int",e[e.SimilarIntArray=1]="SimilarIntArray",e[e.String=2]="String",e[e.Max=3]="Max",Yf=class{constructor(){Gf.add(this),Hf.set(this,[]),Wf.set(this,0)}push(e){Nf(this,Gf,"m",qf).call(this,e,"end")}unshift(e){Nf(this,Gf,"m",qf).call(this,e,"start")}getBytesChunks(){return Nf(this,Hf,"f")}getBuffer(){return _f(Nf(this,Hf,"f"),Nf(this,Wf,"f"))}get length(){return Nf(this,Wf,"f")}},Hf=new WeakMap,Wf=new WeakMap,Gf=new WeakSet,qf=function(e,t){let s;s=e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):new Uint8Array([e]),$f(this,Wf,Nf(this,Wf,"f")+s.length,"f"),Nf(this,Hf,"f")["start"===t?"unshift":"push"](s)}}});function Ig(e){if(e.length<Sg)return!1;const{length:t}=fg,s=e.subarray(-t);return vg.some(t=>Cg(e,t,ug))&&yg.some(e=>Cg(s,e,ug))}function Lg(e){const[t]=e,s={c:t};let i=1;for(;i<e.length;){if(i+1>=e.length)throw new Error("Malformed command buffer: truncated name/type header");const t=String.fromCharCode(e[i]);switch(i++,Ag(e[i])){case Vf.Int:{const{number:r,byteLength:n}=Jf(e.subarray(i));s[t]=r,i+=n}break;case Vf.SimilarIntArray:{const{numbers:r,byteLength:n}=Zf(e.subarray(i));s[t]=r,i+=n}break;case Vf.String:{const{string:r,byteLength:n}=eg(e.subarray(i));s[t]=r,i+=n}}}return function(e){switch(e.c){case Tf.SegmentsAnnouncement:return e;case Tf.SegmentRequest:return Pg(e,"i","r"),e;case Tf.SegmentData:return Pg(e,"i","r","s"),e;case Tf.SegmentAbsent:case Tf.CancelSegmentRequest:case Tf.SegmentDataSendingCompleted:return Pg(e,"i","r"),e;default:throw new Error(`Unknown peer command type: ${String(e.c)}`)}}(s)}function Ag(e){const t=e>>4;if(t<=Vf.Min||t>=Vf.Max)throw new Error("Not existing type");return t}function kg(e,t){if(t&&e.length!==t)throw new Error("Wrong string length");const s=new Uint8Array(null!=t?t:e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}function Rg(e,t,s){const i=new Uint8Array(e.length+t.length+s.length);return i.set(t),i.set(e,t.length),i.set(s,t.length+e.length),i}function Cg(e,t,s){for(let i=0;i<s;i++)if(e[i]!==t[i])return!1;return!0}function Pg(e,...t){for(const s of t)if("number"!=typeof e[s])throw new Error(`Expected number field "${s}", got ${typeof e[s]}`)}var Dg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/binary-command-creator.js"(){wg(),Pf(),tg=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},sg=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},fg=kg("cstr",ug=4),gg=kg("cend",ug),mg=kg("dstr",ug),pg=kg("dend",ug),vg=[fg,mg],yg=[gg,pg],Sg=fg.length+gg.length,Eg=class extends Error{constructor(e){super(),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:e})}},bg=class{constructor(e){ig.add(this),rg.set(this,new Yf),ng.set(this,"joining"),ag.set(this,void 0),tg(this,ag,e,"f")}addCommandChunk(e){if("completed"===sg(this,ng,"f"))return;const t=!((s=e).length<Sg)&&Cg(s,fg,ug);var s;if(!sg(this,rg,"f").length&&!t)throw new Eg("no-first-chunk");if(sg(this,rg,"f").length&&t)throw new Eg("incomplete-joining");sg(this,rg,"f").push(sg(this,ig,"m",og).call(this,e)),function(e){return!(e.length<Sg)&&Cg(e.subarray(-ug),gg,ug)}(e)&&(tg(this,ng,"completed","f"),sg(this,ag,"f").call(this,sg(this,rg,"f").getBuffer()))}},rg=new WeakMap,ng=new WeakMap,ag=new WeakMap,ig=new WeakSet,og=function(e){if(e.length<Sg)throw new Error("Command chunk is too short to unframe");return e.subarray(ug,e.length-ug)},Tg=class{constructor(e,t){lg.set(this,new Yf),hg.set(this,[]),dg.set(this,"creating"),cg.set(this,void 0),tg(this,cg,t,"f"),sg(this,lg,"f").push(e)}addInteger(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=Xf(t);sg(this,lg,"f").push(s)}addUniqueSimilarIntArr(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=function(e){var t;const s=new Map;for(const i of e){const e=255&i,r=i-e,n=null!==(t=s.get(r))&&void 0!==t?t:new Yf;n.length||s.set(r,n),n.push(e)}const i=new Yf;i.push([Vf.SimilarIntArray<<4,s.size]);for(const[e,t]of s){const{length:s}=t,r=e+(255&s);t.unshift(Xf(r)),i.push(t.getBuffer())}return i.getBuffer()}(t);sg(this,lg,"f").push(s)}addString(e,t){sg(this,lg,"f").push(e.charCodeAt(0));const s=function(e){const t=jf.encode(e),{length:s}=t;if(s>4095)throw new Error("String exceeds maximum length of 4095 bytes");const i=new Yf;return i.push([Vf.String<<4|s>>8&15,255&s]),i.push(t),i.getBuffer()}(t);sg(this,lg,"f").push(s)}complete(){if(!sg(this,lg,"f").length)throw new Error("Buffer is empty");if("completed"===sg(this,dg,"f"))return;tg(this,dg,"completed","f");const e=sg(this,lg,"f").getBuffer();if(e.length+Sg<=sg(this,cg,"f"))return void sg(this,hg,"f").push(Rg(e,fg,gg));let t=Math.ceil(e.length/sg(this,cg,"f"));Math.ceil(e.length/t)+Sg>sg(this,cg,"f")&&t++;for(const[s,i]of function*(e,t){const s=Math.ceil(e.length/t);for(let i=0;i<t;i++)yield[i,e.subarray(i*s,(i+1)*s)]}(e,t))0===s?sg(this,hg,"f").push(Rg(i,fg,pg)):s===t-1?sg(this,hg,"f").push(Rg(i,mg,gg)):sg(this,hg,"f").push(Rg(i,mg,pg))}getResultBuffers(){if("creating"===sg(this,dg,"f")||!sg(this,hg,"f").length)throw new Error("Command is not complete.");return sg(this,hg,"f")}},lg=new WeakMap,hg=new WeakMap,dg=new WeakMap,cg=new WeakMap}});function Mg(e,t){switch(e.c){case Tf.CancelSegmentRequest:case Tf.SegmentAbsent:case Tf.SegmentDataSendingCompleted:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t);case Tf.SegmentRequest:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("r",e.r),e.b&&s.addInteger("b",e.b),s.complete(),s.getResultBuffers()}(e,t);case Tf.SegmentsAnnouncement:return function(e,t){const{c:s,p:i,l:r}=e,n=new Tg(s,t);return(null==r?void 0:r.length)&&n.addUniqueSimilarIntArr("l",r),(null==i?void 0:i.length)&&n.addUniqueSimilarIntArr("p",i),n.complete(),n.getResultBuffers()}(e,t);case Tf.SegmentData:return function(e,t){const s=new Tg(e.c,t);return s.addInteger("i",e.i),s.addInteger("s",e.s),s.addInteger("r",e.r),s.complete(),s.getResultBuffers()}(e,t)}}var _g=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/commands.js"(){Dg(),Pf()}}),Og={};h(Og,{BinaryCommandChunksJoiner:()=>bg,BinaryCommandJoiningError:()=>Eg,PeerCommandType:()=>Tf,deserializeCommand:()=>Lg,isCommandChunk:()=>Ig,serializePeerCommand:()=>Mg});var xg=o({"../../node_modules/p2p-media-loader-core/lib/p2p/commands/index.js"(){Pf(),_g(),Dg()}});function Fg(e,t="RTC error"){return function(e,t="RTC error"){var s,i;const r=e;if(r.error instanceof Error)return r.error;const n=null!==(i=null===(s=r.error)||void 0===s?void 0:s.message)&&void 0!==i?i:t;return new Error(n)}(e,t).message}function Bg(e){return"failed"===e||"closed"===e||"disconnected"===e}var Ug,Ng,$g,Gg,Hg,Wg,qg,jg,Kg,Vg,Yg,zg,Qg,Xg,Jg,Zg,em,tm,sm,im,rm,nm,am,om,lm,hm,dm,cm,um,fm,gm,mm,pm,vm,ym,Sm,Em,bm,Tm,wm,Im,Lm,Am,km,Rm,Cm,Pm,Dm,Mm,_m,Om,xm,Fm,Bm,Um,Nm,$m,Gm,Hm,Wm,qm,jm=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/utils.js"(){}}),Km=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/data-channel-sender.js"(){zf(),jm(),Ug=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ng=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$g=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Hg=class{constructor(e,t){Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"maxMessageSize",{enumerable:!0,configurable:!0,writable:!0,value:t}),Gg.set(this,void 0)}sendData(e,t){return Ug(this,void 0,void 0,function*(){if(Ng(this,Gg,"f"))throw new Error("Already sending data");if("open"!==this.channel.readyState)throw new Error("Data channel is not open");this.channel.bufferedAmountLowThreshold=8192;const{promise:s,resolve:i,reject:r}=Df();let n,a=0,o=!1;const l=()=>!o&&(o=!0,void 0!==n&&clearTimeout(n),$g(this,Gg,void 0,"f"),this.channel.removeEventListener("bufferedamountlow",g),this.channel.removeEventListener("closing",h),this.channel.removeEventListener("close",h),this.channel.removeEventListener("error",d),!0);$g(this,Gg,{cancel:()=>{l()&&r(new Error("Send cancelled"))}},"f");const h=()=>{l()&&r(new Error("Data channel closed"))},d=e=>{if(!l())return;const t=Fg(e,"Unknown error");r(new Error(`Data channel error: ${t}`))},c=ArrayBuffer.isView(e)?e.buffer:e,u=ArrayBuffer.isView(e)?e.byteOffset:0,f=()=>{void 0===n&&(n=setTimeout(()=>{n=void 0,g()},25))},g=()=>{if(!o)if("open"===this.channel.readyState){try{for(;a<e.byteLength;){if(this.channel.bufferedAmount>=16384)return void f();const s=Math.min(this.maxMessageSize,e.byteLength-a),i=new Uint8Array(c,u+a,s);if(this.channel.send(i),a+=s,null==t||t(s),!Ng(this,Gg,"f"))return}}catch(e){return void(l()&&r(e instanceof Error?e:new Error(String(e))))}l()&&i()}else l()&&r(new Error(`Data channel not open (state: ${this.channel.readyState})`))};return this.channel.addEventListener("bufferedamountlow",g),this.channel.addEventListener("closing",h),this.channel.addEventListener("close",h),this.channel.addEventListener("error",d),g(),s})}cancel(){var e;null===(e=Ng(this,Gg,"f"))||void 0===e||e.cancel()}},Gg=new WeakMap}}),Vm=o({"../../node_modules/p2p-media-loader-core/lib/p2p/peer-protocol.js"(){Wg=d(Cf(),1),xg(),Km(),qg=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},jg=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Kg=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},nm=(0,Wg.default)("p2pml-core:peer-protocol"),am=class{constructor(e,t,s,i,r){if(Vg.add(this),Yg.set(this,void 0),zg.set(this,void 0),Qg.set(this,void 0),Xg.set(this,void 0),Jg.set(this,void 0),Zg.set(this,void 0),em.set(this,void 0),tm.set(this,void 0),sm.set(this,void 0),im.set(this,e=>{try{const t=new Uint8Array(e.data);Ig(t)?Kg(this,Vg,"m",rm).call(this,t):(Kg(this,tm,"f").onSegmentChunkReceived(t),Kg(this,Xg,"f").call(this,t.byteLength,"p2p",Kg(this,sm,"f"),Kg(this,em,"f").streamType,Kg(this,em,"f").infoHash))}catch(e){nm("error handling data channel message: %O",e),Kg(this,tm,"f").onProtocolError(e)}}),jg(this,Zg,e,"f"),jg(this,em,t,"f"),jg(this,tm,s,"f"),jg(this,sm,r,"f"),jg(this,zg,new Hg(e,t.webRtcMaxMessageSize),"f"),jg(this,Xg,i.getEventDispatcher("onChunkDownloaded"),"f"),jg(this,Jg,i.getEventDispatcher("onChunkUploaded"),"f"),"arraybuffer"!==e.binaryType)throw new Error(`Expected binaryType "arraybuffer", got "${e.binaryType}"`);e.addEventListener("message",Kg(this,im,"f"))}sendCommand(e){if("open"!==Kg(this,Zg,"f").readyState)throw new Error(`cannot send command ${e.c} (channel state: ${Kg(this,Zg,"f").readyState})`);const t=Mg(e,Kg(this,em,"f").webRtcMaxMessageSize);for(const e of t)Kg(this,Zg,"f").send(e)}stopUploadingSegmentData(){Kg(this,zg,"f").cancel(),jg(this,Qg,void 0,"f")}getUploadingRequestId(){return Kg(this,Qg,"f")}splitSegmentDataToChunksAndUploadAsync(e,t){return qg(this,void 0,void 0,function*(){if(void 0!==Kg(this,Qg,"f"))throw new Error("Some segment data is already uploading.");jg(this,Qg,t,"f");try{yield Kg(this,zg,"f").sendData(e,e=>{Kg(this,Jg,"f").call(this,e,Kg(this,sm,"f"),Kg(this,em,"f").streamType,Kg(this,em,"f").infoHash)})}finally{Kg(this,Qg,"f")===t&&jg(this,Qg,void 0,"f")}})}destroy(){Kg(this,Zg,"f").removeEventListener("message",Kg(this,im,"f")),Kg(this,zg,"f").cancel(),jg(this,Yg,void 0,"f"),jg(this,Qg,void 0,"f")}},Yg=new WeakMap,zg=new WeakMap,Qg=new WeakMap,Xg=new WeakMap,Jg=new WeakMap,Zg=new WeakMap,em=new WeakMap,tm=new WeakMap,sm=new WeakMap,im=new WeakMap,Vg=new WeakSet,rm=function(e){var t;jg(this,Yg,null!==(t=Kg(this,Yg,"f"))&&void 0!==t?t:new bg(e=>{let t;jg(this,Yg,void 0,"f");try{t=Lg(e)}catch(e){return nm("error deserializing command: %O",e),void Kg(this,tm,"f").onProtocolError(e)}Kg(this,tm,"f").onCommandReceived(t)}),"f");try{Kg(this,Yg,"f").addCommandChunk(e)}catch(e){nm("error receiving command chunks: %O",e),jg(this,Yg,void 0,"f"),Kg(this,tm,"f").onProtocolError(e)}}}}),Ym=o({"../../node_modules/p2p-media-loader-core/lib/bandwidth-calculator.js"(){om=class{constructor(e=2e4){Object.defineProperty(this,"clearThresholdMs",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"loadingsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"bytes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"loadingOnlyTimestamps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"timestamps",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"noLoadingsTime",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"loadingsStoppedAt",{enumerable:!0,configurable:!0,writable:!0,value:0})}addBytes(e,t=performance.now()){this.bytes.push(e),this.loadingOnlyTimestamps.push(t-this.noLoadingsTime),this.timestamps.push(t)}startLoading(e=performance.now()){this.clearStale(),0===this.loadingsCount&&0!==this.loadingsStoppedAt&&(this.noLoadingsTime+=e-this.loadingsStoppedAt),this.loadingsCount++}stopLoading(e=performance.now()){this.loadingsCount>0&&(this.loadingsCount--,0===this.loadingsCount&&(this.loadingsStoppedAt=e))}getBandwidthLoadingOnly(e,t=Number.NEGATIVE_INFINITY){if(!this.loadingOnlyTimestamps.length)return 0;const s=1e3*e,i=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1];let r=i;const n=i-s;let a=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.loadingOnlyTimestamps[e];if(s<n||this.timestamps[e]<t)break;r=s,a+=this.bytes[e]}return 8e3*a/Math.max(i-r,1)}getBandwidth(e,t=Number.NEGATIVE_INFINITY,s=performance.now()){if(!this.timestamps.length)return 0;const i=s-1e3*e;let r=s,n=0;for(let e=this.bytes.length-1;e>=0;e--){const s=this.timestamps[e];if(s<i||s<t)break;r=s,n+=this.bytes[e]}return 8e3*n/Math.max(s-r,1)}clearStale(){if(!this.loadingOnlyTimestamps.length)return;const e=this.loadingOnlyTimestamps[this.loadingOnlyTimestamps.length-1]-this.clearThresholdMs;let t=0;for(const s of this.loadingOnlyTimestamps){if(s>e)break;t++}this.bytes.splice(0,t),this.loadingOnlyTimestamps.splice(0,t),this.timestamps.splice(0,t)}clear(){this.bytes.length=0,this.loadingOnlyTimestamps.length=0,this.timestamps.length=0,this.loadingsCount=0,this.noLoadingsTime=0,this.loadingsStoppedAt=0}}}}),zm=o({"../../node_modules/p2p-media-loader-core/lib/p2p/peer.js"(){lm=d(Cf(),1),If(),xg(),Vm(),Ym(),hm=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},dm=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},cm=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},({PeerCommandType:Om}=Og),xm=class{get isDestroyed(){return dm(this,wm,"f")}constructor(e,t,s,i,r,n){um.add(this),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:n}),fm.set(this,void 0),gm.set(this,void 0),mm.set(this,new Set),pm.set(this,new Set),vm.set(this,0),ym.set(this,new om),Sm.set(this,{value:0,timestamp:0}),Em.set(this,(0,lm.default)("p2pml-core:peer")),bm.set(this,0),Tm.set(this,void 0),wm.set(this,!1),Object.defineProperty(this,"connectedAt",{enumerable:!0,configurable:!0,writable:!0,value:performance.now()}),Im.set(this,void 0),Lm.set(this,void 0),Am.set(this,void 0),km.set(this,e=>hm(this,void 0,void 0,function*(){var t;switch(e.c){case Om.SegmentsAnnouncement:cm(this,mm,new Set(e.l),"f"),cm(this,pm,new Set(e.p),"f"),dm(this,Lm,"f").onSegmentsAnnouncement(dm(this,mm,"f").size,dm(this,pm,"f").size);break;case Om.SegmentRequest:cm(this,Tm,e.r,"f"),dm(this,fm,"f").stopUploadingSegmentData(),dm(this,Lm,"f").onSegmentRequested(this,e.i,e.r,e.b);break;case Om.SegmentData:{if(!dm(this,gm,"f"))break;if(dm(this,gm,"f").isSegmentDataCommandReceived)break;const{request:t,controls:s,requestId:i}=dm(this,gm,"f");if(t.segment.externalId!==e.i||i!==e.r)break;dm(this,gm,"f").isSegmentDataCommandReceived=!0,s.firstBytesReceived(),void 0===t.totalBytes?t.setTotalBytes(t.loadedBytes+e.s):t.totalBytes-t.loadedBytes!==e.s&&dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch")}break;case Om.SegmentDataSendingCompleted:{const t=dm(this,gm,"f");if(!(null==t?void 0:t.isSegmentDataCommandReceived))return;const{request:s,controls:i,requestId:r}=t;if(s.segment.externalId!==e.i||r!==e.r)return void dm(this,um,"m",Cm).call(this,"protocol-violation","Peer protocol violation");if(s.loadedBytes!==s.totalBytes)return void dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch");const n=yield s.validateData(dm(this,Am,"f").validateP2PSegment);if(dm(this,wm,"f"))return;if(dm(this,gm,"f")!==t)return;if(!n)return void dm(this,um,"m",Cm).call(this,"validation-failed","P2P segment validation failed");cm(this,vm,0,"f"),i.completeOnSuccess(),dm(this,ym,"f").stopLoading(),cm(this,gm,void 0,"f");break}case Om.SegmentAbsent:dm(this,mm,"f").delete(e.i),(null===(t=dm(this,gm,"f"))||void 0===t?void 0:t.request.segment.externalId)===e.i&&dm(this,gm,"f").requestId===e.r&&dm(this,um,"m",Pm).call(this,"peer-segment-absent");break;case Om.CancelSegmentRequest:if(dm(this,Tm,"f")===e.r&&cm(this,Tm,void 0,"f"),dm(this,fm,"f").getUploadingRequestId()!==e.r)break;dm(this,fm,"f").stopUploadingSegmentData()}})),Rm.set(this,e=>{var t;if(!(null===(t=dm(this,gm,"f"))||void 0===t?void 0:t.isSegmentDataCommandReceived))return;const{request:s,controls:i}=dm(this,gm,"f");void 0!==s.totalBytes&&s.loadedBytes+e.byteLength>s.totalBytes?dm(this,um,"m",Cm).call(this,"bytes-length-mismatch","Peer response bytes length mismatch"):(dm(this,ym,"f").addBytes(e.byteLength),dm(this,Sm,"f").timestamp=0,i.addLoadedChunk(e))}),cm(this,Im,s,"f"),cm(this,Lm,i,"f"),cm(this,Am,r,"f"),cm(this,fm,new am(t,r,{onSegmentChunkReceived:dm(this,Rm,"f"),onCommandReceived:e=>{dm(this,km,"f").call(this,e).catch(t=>{dm(this,Em,"f").call(this,"error processing command %O: %O",e,t),this.destroy(!1,new af("protocol-violation",t instanceof Error?t.message:"Error processing command",t))})},onProtocolError:e=>{this.destroy(!1,new af("protocol-violation",e instanceof Error?e.message:"Protocol error",e))}},n,e),"f")}get downloadingSegment(){var e;return null===(e=dm(this,gm,"f"))||void 0===e?void 0:e.request.segment}get isUploadingSegment(){return void 0!==dm(this,fm,"f").getUploadingRequestId()}getDownloadBandwidth(){const e=performance.now();return e-dm(this,Sm,"f").timestamp>1e3&&(dm(this,Sm,"f").value=dm(this,ym,"f").getBandwidthLoadingOnly(15),dm(this,Sm,"f").timestamp=e),dm(this,Sm,"f").value}getSegmentStatus(e){const{externalId:t}=e;return dm(this,mm,"f").has(t)?"loaded":dm(this,pm,"f").has(t)?"http-loading":void 0}downloadSegment(e){if(dm(this,wm,"f"))return;if(dm(this,gm,"f"))throw new Error("Some segment already is downloading");if(e.tryCompleteByLoadedBytes({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:dm(this,Am,"f").p2pNotReceivingBytesTimeoutMs,onAbort:()=>{}},dm(this,Am,"f").validateP2PSegment,"p2p-segment-validation-failed"))return;dm(this,ym,"f").startLoading(),cm(this,bm,(dm(this,bm,"f")+1)%1e9,"f"),cm(this,gm,{request:e,requestId:dm(this,bm,"f"),isSegmentDataCommandReceived:!1,controls:e.start({downloadSource:"p2p",peerId:this.id},{notReceivingBytesTimeoutMs:dm(this,Am,"f").p2pNotReceivingBytesTimeoutMs,onAbort:t=>{var s;if(!dm(this,gm,"f")||dm(this,gm,"f").request!==e)return;const{request:i,requestId:r}=dm(this,gm,"f");dm(this,um,"m",Dm).call(this,i.segment,r),dm(this,ym,"f").stopLoading(),"abort"!==t.type&&(dm(this,ym,"f").clear(),dm(this,Sm,"f").timestamp=0,dm(this,Em,"f").call(this,`cleared bandwidth history due to ${t.type}`)),cm(this,gm,void 0,"f"),"bytes-receiving-timeout"===t.type&&cm(this,vm,(s=dm(this,vm,"f"),++s),"f"),dm(this,vm,"f")>=dm(this,Am,"f").p2pErrorRetries?this.destroy(!1,new af("timeout","Too many timeout errors")):"bytes-receiving-timeout"===t.type&&dm(this,Lm,"f").onWarning(new of("timeout-strike",`Timeout strike ${dm(this,vm,"f")}/${dm(this,Am,"f").p2pErrorRetries}`))}})},"f");const t={c:Om.SegmentRequest,r:dm(this,gm,"f").requestId,i:e.segment.externalId};e.loadedBytes&&(t.b=e.loadedBytes),dm(this,um,"m",_m).call(this,t)||dm(this,um,"m",Pm).call(this,"peer-closed")}uploadSegmentData(e,t,s){return hm(this,void 0,void 0,function*(){if(dm(this,wm,"f"))return;if(t!==dm(this,Tm,"f"))return void dm(this,Em,"f").call(this,`discarding obsolete upload request ${t} for segment ${e.externalId}`);const{externalId:i}=e;dm(this,Em,"f").call(this,`send segment ${e.externalId} to ${this.id} (byteLength: ${s.byteLength})`);const r={c:Om.SegmentData,i:i,r:t,s:s.byteLength};if(dm(this,um,"m",_m).call(this,r))try{if(yield dm(this,fm,"f").splitSegmentDataToChunksAndUploadAsync(s,t),this.isDestroyed||t!==dm(this,Tm,"f"))return;dm(this,um,"m",Mm).call(this,e,t),dm(this,Em,"f").call(this,`segment ${i} has been sent to ${this.id}`)}catch(e){dm(this,Em,"f").call(this,`cancel segment uploading ${i}: %O`,e)}})}sendSegmentsAnnouncementCommand(e,t){const s={c:Om.SegmentsAnnouncement,p:t,l:e};dm(this,um,"m",_m).call(this,s)}sendSegmentAbsentCommand(e,t){dm(this,um,"m",_m).call(this,{c:Om.SegmentAbsent,i:e,r:t})}destroy(e=!1,t){dm(this,wm,"f")||(cm(this,wm,!0,"f"),dm(this,um,"m",Pm).call(this,"peer-closed",t),dm(this,fm,"f").destroy(),e||dm(this,Im,"f").call(this,t),dm(this,Em,"f").call(this,`peer closed ${this.id}`))}},fm=new WeakMap,gm=new WeakMap,mm=new WeakMap,pm=new WeakMap,vm=new WeakMap,ym=new WeakMap,Sm=new WeakMap,Em=new WeakMap,bm=new WeakMap,Tm=new WeakMap,wm=new WeakMap,Im=new WeakMap,Lm=new WeakMap,Am=new WeakMap,km=new WeakMap,Rm=new WeakMap,um=new WeakSet,Cm=function(e,t){var s;null===(s=dm(this,gm,"f"))||void 0===s||s.request.clearLoadedBytes();const i=new af(e,t);dm(this,um,"m",Pm).call(this,"peer-closed",i),this.destroy(!1,i)},Pm=function(e,t){if(!dm(this,gm,"f"))return;const{request:s,controls:i}=dm(this,gm,"f"),{segment:r}=s;dm(this,Em,"f").call(this,`cancel segment request ${r.externalId} (${e})`);const n=new cf(e,void 0,t);i.failWithError(n),dm(this,ym,"f").stopLoading(),"peer-segment-absent"!==e&&(dm(this,ym,"f").clear(),dm(this,Sm,"f").timestamp=0,dm(this,Em,"f").call(this,`cleared bandwidth history due to ${n.type}`)),cm(this,gm,void 0,"f")},Dm=function(e,t){dm(this,um,"m",_m).call(this,{c:Om.CancelSegmentRequest,i:e.externalId,r:t})},Mm=function(e,t){dm(this,um,"m",_m).call(this,{c:Om.SegmentDataSendingCompleted,r:t,i:e.externalId})},_m=function(e){if(dm(this,wm,"f"))return!1;try{return dm(this,fm,"f").sendCommand(e),!0}catch(t){return dm(this,Em,"f").call(this,"error sending command %d: %O",e.c,t),!1}}}}),Qm=o({"../../node_modules/p2p-media-loader-core/lib/utils/event-target.js"(){Fm=class{constructor(){Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}dispatchEvent(e,t,s,i,r,n){const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch(e){}}getEventDispatcher(e){return(t,s,i,r,n)=>{const a=this.events.get(e);if(a)for(const e of a)try{e(t,s,i,r,n)}catch(e){}}}addEventListener(e,t){const s=this.events.get(e);s?this.events.set(e,[...s,t]):this.events.set(e,[t])}removeEventListener(e,t){const s=this.events.get(e);if(!s)return;const i=s.indexOf(t);if(-1===i)return;if(1===s.length)return void this.events.delete(e);const r=s.slice();r.splice(i,1),this.events.set(e,r)}clear(){this.events.clear()}}}});function Xm(e,t){return qm?e.setLocalDescription(t):new Promise((s,i)=>{try{e.setLocalDescription(t,s,i)}catch(e){i(e)}})}function Jm(e,t){return qm?e.setRemoteDescription(t):new Promise((s,i)=>{try{e.setRemoteDescription(t,s,i)}catch(e){i(e)}})}var Zm,ep,tp,sp,ip,rp,np,ap,op,lp,hp,dp,cp,up,fp,gp,mp,pp,vp,yp,Sp,Ep,bp,Tp,wp,Ip,Lp,Ap,kp,Rp,Cp,Pp,Dp,Mp,_p,Op,xp,Fp,Bp,Up,Np=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-client/webrtc-utils.js"(){Gm="undefined"!=typeof window?window:{},Hm=null!==(Um=null!==(Bm=Gm.RTCPeerConnection)&&void 0!==Bm?Bm:Gm.webkitRTCPeerConnection)&&void 0!==Um?Um:Gm.mozRTCPeerConnection,Wm=null!==($m=null!==(Nm=Gm.RTCSessionDescription)&&void 0!==Nm?Nm:Gm.webkitRTCSessionDescription)&&void 0!==$m?$m:Gm.mozRTCSessionDescription,qm=(()=>{if(!Gm.RTCPeerConnection&&!Gm.webkitRTCPeerConnection&&!Gm.mozRTCPeerConnection)return!1;let e;try{e=new Hm;const t=e.createOffer();if("function"==typeof(null==t?void 0:t.then))return t.catch(()=>{}),!0}catch(e){}finally{try{null==e||e.close()}catch(e){}}return!1})()}});function $p(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&Bp.has(t.type)&&"string"==typeof t.sdp}var Gp,Hp,Wp,qp,jp,Kp,Vp,Yp,zp,Qp,Xp,Jp,Zp,ev,tv=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-client/index.js"(){Qm(),zf(),jm(),If(),Lf(),Np(),Zm=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},ep=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},tp=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Bp=new Set(["offer","answer","pranswer","rollback"]),ip=Up=class{constructor(e){var t,s,i,r,n,a;sp.add(this),ap.set(this,void 0),op.set(this,void 0),lp.set(this,new Fm),hp.set(this,new Map),dp.set(this,new Set),cp.set(this,new yf),up.set(this,null),fp.set(this,null),gp.set(this,0),mp.set(this,null),pp.set(this,void 0),vp.set(this,null),yp.set(this,!1),bp.set(this,()=>{ep(this,sp,"m",Ip).call(this,ep(ip,ip,"f",rp)),ep(this,sp,"m",Ap).call(this,"started").catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("announce-failed",`Initial announce failed: ${e instanceof Error?e.message:String(e)}`,e))})}),Tp.set(this,()=>{ep(this,sp,"m",Lp).call(this),tp(this,fp,null,"f")}),wp.set(this,e=>{if(ep(this,sp,"m",Sp).call(this))return;let t;try{const s="string"==typeof e?e:(new TextDecoder).decode(e);t=JSON.parse(s)}catch(e){return void ep(this,lp,"f").dispatchEvent("error",new lf("parse-error",`Failed to parse tracker message: ${e instanceof Error?e.message:String(e)}`,e))}if("object"!=typeof t||null===t||Array.isArray(t))return;const s=t,i=s.info_hash;if("string"==typeof i&&i!==ep(this,ap,"f").infoHash)return;const r=s["warning message"];"string"==typeof r&&ep(this,lp,"f").dispatchEvent("warning",new hf("tracker-response",r));const n=s["failure reason"];if("string"==typeof n)return void ep(this,lp,"f").dispatchEvent("error",new lf("tracker-response",n));const{interval:a}=s;if("number"==typeof a&&a>0){const e=Math.max(ep(ip,ip,"f",np),a);ep(this,fp,"f")!==e&&ep(this,sp,"m",Ip).call(this,e)}const o=s["tracker id"];"string"==typeof o&&tp(this,vp,o,"f");const l=s.peer_id;if("string"==typeof l&&l===ep(this,ap,"f").peerId)return;const h=s.offer_id;"string"==typeof l&&"string"==typeof h&&($p(s.offer)?ep(this,sp,"m",Pp).call(this,{sdp:s.offer,peerId:l,offerId:h}).catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("signaling-failed",`Failed to handle offer: ${e instanceof Error?e.message:String(e)}`,e))}):$p(s.answer)&&ep(this,sp,"m",Dp).call(this,{sdp:s.answer,peerId:l,offerId:h}).catch(e=>{ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("error",new lf("signaling-failed",`Failed to handle answer: ${e instanceof Error?e.message:String(e)}`,e))}))}),tp(this,ap,{infoHash:e.infoHash,peerId:e.peerId,rtcConfig:e.rtcConfig,channelConfig:e.channelConfig,offerTimeout:null!==(t=e.offerTimeout)&&void 0!==t?t:()=>5e4,offersCount:null!==(s=e.offersCount)&&void 0!==s?s:()=>5,iceGatheringTimeout:null!==(i=e.iceGatheringTimeout)&&void 0!==i?i:()=>5e3,connectionTimeout:null!==(r=e.connectionTimeout)&&void 0!==r?r:()=>15e3,claimPeer:null!==(n=e.claimPeer)&&void 0!==n?n:()=>!0,shouldGenerateOffers:null!==(a=e.shouldGenerateOffers)&&void 0!==a?a:()=>!0},"f"),tp(this,op,e.wsClient,"f")}addEventListener(e,t){ep(this,lp,"f").addEventListener(e,t)}removeEventListener(e,t){ep(this,lp,"f").removeEventListener(e,t)}start(){ep(this,sp,"m",Sp).call(this)||ep(this,yp,"f")||(tp(this,yp,!0,"f"),ep(this,op,"f").addEventListener("connected",ep(this,bp,"f")),ep(this,op,"f").addEventListener("disconnected",ep(this,Tp,"f")),ep(this,op,"f").addEventListener("message",ep(this,wp,"f")),"connected"===ep(this,op,"f").state&&ep(this,bp,"f").call(this))}destroy(){ep(this,sp,"m",Sp).call(this)||(ep(this,cp,"f").abort(),ep(this,sp,"m",Lp).call(this),ep(this,sp,"m",Rp).call(this),ep(this,sp,"m",xp).call(this),ep(this,sp,"m",Fp).call(this),ep(this,yp,"f")&&(ep(this,op,"f").removeEventListener("connected",ep(this,bp,"f")),ep(this,op,"f").removeEventListener("disconnected",ep(this,Tp,"f")),ep(this,op,"f").removeEventListener("message",ep(this,wp,"f"))),ep(this,lp,"f").clear())}},ap=new WeakMap,op=new WeakMap,lp=new WeakMap,hp=new WeakMap,dp=new WeakMap,cp=new WeakMap,up=new WeakMap,fp=new WeakMap,gp=new WeakMap,mp=new WeakMap,pp=new WeakMap,vp=new WeakMap,yp=new WeakMap,bp=new WeakMap,Tp=new WeakMap,wp=new WeakMap,sp=new WeakSet,Sp=function(){return ep(this,cp,"f").signal.aborted},Ep=function(){if(ep(this,cp,"f").signal.aborted)throw new Error("Client destroyed")},Ip=function(e){var t;ep(this,sp,"m",Lp).call(this),tp(this,fp,e,"f");const s=tp(this,gp,(t=ep(this,gp,"f"),++t),"f"),i=()=>Zm(this,void 0,void 0,function*(){try{yield ep(this,sp,"m",Ap).call(this)}catch(e){if(ep(this,sp,"m",Sp).call(this))return;ep(this,lp,"f").dispatchEvent("error",new lf("announce-failed",`Announce failed: ${e instanceof Error?e.message:String(e)}`,e))}ep(this,sp,"m",Sp).call(this)||null===ep(this,fp,"f")||ep(this,gp,"f")!==s||tp(this,up,setTimeout(i,1e3*ep(this,fp,"f")),"f")});tp(this,up,setTimeout(i,1e3*e),"f")},Lp=function(){null!==ep(this,up,"f")&&(clearTimeout(ep(this,up,"f")),tp(this,up,null,"f"))},Ap=function(e){return Zm(this,void 0,void 0,function*(){if(ep(this,sp,"m",Sp).call(this)||"connected"!==ep(this,op,"f").state)return;if(e&&tp(this,pp,e,"f"),ep(this,mp,"f"))return ep(this,mp,"f");const t=(()=>Zm(this,void 0,void 0,function*(){const e=ep(this,ap,"f").shouldGenerateOffers()?ep(this,ap,"f").offersCount():0,t=yield Promise.all(Array.from({length:e},()=>ep(this,sp,"m",kp).call(this)));if(ep(this,sp,"m",Sp).call(this)){for(const e of t)e&&ep(this,sp,"m",Op).call(this,e.offer_id);return}const s=[];for(const e of t)e&&s.push(e);const i=ep(this,pp,"f");tp(this,pp,void 0,"f");const r=ep(this,sp,"m",Cp).call(this,{numwant:s.length,offers:s,event:i});if("connected"===ep(this,op,"f").state)try{ep(this,op,"f").send(JSON.stringify(r))}catch(e){for(const e of s)ep(this,sp,"m",Op).call(this,e.offer_id);throw e}else for(const e of s)ep(this,sp,"m",Op).call(this,e.offer_id)}))();tp(this,mp,t,"f");try{yield t}finally{ep(this,mp,"f")===t&&tp(this,mp,null,"f")}})},kp=function(){return Zm(this,void 0,void 0,function*(){var e,t;if(ep(this,sp,"m",Sp).call(this))return;let s;try{s=new Hm(null===(t=(e=ep(this,ap,"f")).rtcConfig)||void 0===t?void 0:t.call(e)),ep(this,dp,"f").add(s);const i=s.createDataChannel("webtorrent",ep(this,ap,"f").channelConfig),r=yield function(e,t){return qm?e.createOffer(t):new Promise((s,i)=>{try{e.createOffer(s,i,t)}catch(e){i(e)}})}(s);ep(this,sp,"m",Ep).call(this),yield Xm(s,r),ep(this,sp,"m",Ep).call(this),yield ep(this,sp,"m",Mp).call(this,s),ep(this,sp,"m",Ep).call(this);const n=s.localDescription;if(!(null==n?void 0:n.sdp))return void s.close();const a=function(){let e="";for(let t=0;t<20;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()));return e}();return ep(this,hp,"f").set(a,{connection:s,channel:i,timeoutId:setTimeout(()=>{ep(this,sp,"m",Op).call(this,a)},ep(this,ap,"f").offerTimeout())}),{offer:{type:n.type,sdp:n.sdp},offer_id:a}}catch(e){null==s||s.close(),ep(this,sp,"m",Sp).call(this)||ep(this,lp,"f").dispatchEvent("warning",new hf("offer-failed",`Failed to create offer: ${e instanceof Error?e.message:String(e)}`,e))}finally{s&&ep(this,dp,"f").delete(s)}})},Rp=function(){if("connected"!==ep(this,op,"f").state)return;const e=ep(this,sp,"m",Cp).call(this,{numwant:0,offers:[],event:"stopped"});try{ep(this,op,"f").send(JSON.stringify(e))}catch(e){}},Cp=function({numwant:e,offers:t,event:s}){const i={action:"announce",info_hash:ep(this,ap,"f").infoHash,peer_id:ep(this,ap,"f").peerId,numwant:e,uploaded:0,downloaded:0,offers:t};return s&&(i.event=s),ep(this,vp,"f")&&(i.trackerid=ep(this,vp,"f")),i},Pp=function(e){return Zm(this,arguments,void 0,function*({sdp:e,peerId:t,offerId:s}){var i,r;if(ep(this,sp,"m",Sp).call(this))return;if(!ep(this,ap,"f").claimPeer(t))return;let n;try{n=new Hm(null===(r=(i=ep(this,ap,"f")).rtcConfig)||void 0===r?void 0:r.call(i)),ep(this,dp,"f").add(n),yield Jm(n,new Wm(e)),ep(this,sp,"m",Ep).call(this);const a=yield function(e,t){return qm?e.createAnswer(t):new Promise((s,i)=>{try{e.createAnswer(s,i,t)}catch(e){i(e)}})}(n);ep(this,sp,"m",Ep).call(this),yield Xm(n,a),ep(this,sp,"m",Ep).call(this),yield ep(this,sp,"m",Mp).call(this,n),ep(this,sp,"m",Ep).call(this);const o=n.localDescription;if(!o)throw new Error("Failed to get local description after ICE gathering");const l={action:"announce",info_hash:ep(this,ap,"f").infoHash,peer_id:ep(this,ap,"f").peerId,to_peer_id:t,offer_id:s,answer:{type:o.type,sdp:o.sdp}};ep(this,op,"f").send(JSON.stringify(l));const h=yield ep(this,sp,"m",_p).call(this,n);ep(this,sp,"m",Ep).call(this),ep(this,lp,"f").dispatchEvent("peerConnected",{peerId:t,connection:n,channel:h})}catch(e){null==n||n.close(),ep(this,lp,"f").dispatchEvent("peerConnectFailed",{peerId:t,error:new df("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{n&&ep(this,dp,"f").delete(n)}})},Dp=function(e){return Zm(this,arguments,void 0,function*({sdp:e,peerId:t,offerId:s}){if(ep(this,sp,"m",Sp).call(this))return;const i=ep(this,hp,"f").get(s);if(i)if(ep(this,hp,"f").delete(s),clearTimeout(i.timeoutId),ep(this,ap,"f").claimPeer(t)){ep(this,dp,"f").add(i.connection);try{yield Jm(i.connection,new Wm(e)),ep(this,sp,"m",Ep).call(this);const s=yield ep(this,sp,"m",_p).call(this,i.connection,i.channel);ep(this,sp,"m",Ep).call(this),ep(this,lp,"f").dispatchEvent("peerConnected",{peerId:t,connection:i.connection,channel:s})}catch(e){i.connection.close(),ep(this,lp,"f").dispatchEvent("peerConnectFailed",{peerId:t,error:new df("connection-failed",e instanceof Error?e.message:String(e),e)})}finally{ep(this,dp,"f").delete(i.connection)}}else i.connection.close()})},Mp=function(e){return new Promise((t,s)=>{if("complete"===e.iceGatheringState)return void t();if("closed"===e.signalingState)return void s(new Error("RTCPeerConnection closed"));let i;const r=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",n),e.removeEventListener("icecandidate",a),e.removeEventListener("signalingstatechange",o),ep(this,cp,"f").signal.removeEventListener("abort",l)},n=()=>{"complete"===e.iceGatheringState&&(r(),t())},a=e=>{null===e.candidate&&(r(),t())},o=()=>{"closed"===e.signalingState&&(r(),s(new Error("RTCPeerConnection closed")))},l=()=>{r(),s(new Error("ICE gathering aborted due to teardown"))};ep(this,cp,"f").signal.aborted?l():(i=setTimeout(()=>{r(),t()},ep(this,ap,"f").iceGatheringTimeout()),e.addEventListener("icegatheringstatechange",n),e.addEventListener("icecandidate",a),e.addEventListener("signalingstatechange",o),ep(this,cp,"f").signal.addEventListener("abort",l))})},_p=function(e,t){const{promise:s,resolve:i,reject:r}=Df();let n,a=t;const o=()=>!!Bg(e.iceConnectionState)&&(g(),r(new Error(`ICE connection ${e.iceConnectionState}`)),!0),l=()=>{g(),a?i(a):r(new Error("Data channel missing on open"))},h=()=>{g(),r(new Error("Data channel error"))},d=()=>{g(),r(new Error("Data channel closed prematurely"))},c=e=>{a=e,"open"===e.readyState?l():"closed"===e.readyState||"closing"===e.readyState?d():(e.addEventListener("open",l),e.addEventListener("error",h),e.addEventListener("close",d),e.addEventListener("closing",d))},u=e=>{a||c(e.channel)},f=()=>{g(),r(new Error("Connection aborted due to teardown"))},g=()=>{clearTimeout(n),e.removeEventListener("iceconnectionstatechange",o),e.removeEventListener("datachannel",u),a&&(a.removeEventListener("open",l),a.removeEventListener("error",h),a.removeEventListener("close",d),a.removeEventListener("closing",d)),ep(this,cp,"f").signal.removeEventListener("abort",f)};return ep(this,cp,"f").signal.aborted?(f(),s):(o()||(n=setTimeout(()=>{g(),r(new Error("Data channel open timeout"))},ep(this,ap,"f").connectionTimeout()),e.addEventListener("iceconnectionstatechange",o),ep(this,cp,"f").signal.addEventListener("abort",f),a?c(a):e.addEventListener("datachannel",u)),s)},Op=function(e,t){const s=null!=t?t:ep(this,hp,"f").get(e);s&&(clearTimeout(s.timeoutId),s.connection.close(),ep(this,hp,"f").delete(e))},xp=function(){for(const[e,t]of ep(this,hp,"f"))ep(this,sp,"m",Op).call(this,e,t)},Fp=function(){for(const e of ep(this,dp,"f"))e.close();ep(this,dp,"f").clear()},rp={value:120},np={value:20}}}),sv=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-manager/index.js"(){If(),Qm(),jm(),tv(),Gp=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Hp=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},ev=class{constructor(e){var t,s;Wp.add(this),qp.set(this,void 0),jp.set(this,new Fm),Kp.set(this,new Set),Vp.set(this,new Map),Yp.set(this,new Set),zp.set(this,!1),Qp.set(this,!1),Xp.set(this,e=>{if(Hp(this,zp,"f"))return!1;if(Hp(this,Kp,"f").has(e)||Hp(this,Vp,"f").has(e))return!1;const t=Math.floor(Hp(this,qp,"f").maxPeers()*Math.max(1,Hp(this,qp,"f").maxPeersMultiplier()));return!(Hp(this,Kp,"f").size+Hp(this,Vp,"f").size>=t||(Hp(this,Kp,"f").add(e),0))}),Gp(this,qp,Object.assign(Object.assign({},e),{maxPeers:null!==(t=e.maxPeers)&&void 0!==t?t:()=>50,maxPeersMultiplier:null!==(s=e.maxPeersMultiplier)&&void 0!==s?s:()=>1.5}),"f")}addEventListener(e,t){Hp(this,jp,"f").addEventListener(e,t)}removeEventListener(e,t){Hp(this,jp,"f").removeEventListener(e,t)}start(){if(!Hp(this,zp,"f")&&!Hp(this,Qp,"f")){Gp(this,Qp,!0,"f");try{for(const e of Hp(this,qp,"f").trackerUrls){const{client:t,release:s}=Hp(this,qp,"f").socketPool.acquire(e);let i=!1;try{const r=new Up({infoHash:Hp(this,qp,"f").infoHash,peerId:Hp(this,qp,"f").peerId,wsClient:t,rtcConfig:Hp(this,qp,"f").rtcConfig,channelConfig:Hp(this,qp,"f").channelConfig,claimPeer:Hp(this,Xp,"f"),offersCount:Hp(this,qp,"f").offersCount,offerTimeout:Hp(this,qp,"f").offerTimeout,iceGatheringTimeout:Hp(this,qp,"f").iceGatheringTimeout,connectionTimeout:Hp(this,qp,"f").connectionTimeout,shouldGenerateOffers:()=>Hp(this,Kp,"f").size+Hp(this,Vp,"f").size<Hp(this,qp,"f").maxPeers()}),n=t=>{Hp(this,Kp,"f").delete(t.peerId),Hp(this,Wp,"m",Zp).call(this,t.peerId,t.connection,t.channel,e)},a=t=>{Hp(this,Kp,"f").has(t.peerId)&&(Hp(this,Kp,"f").delete(t.peerId),Hp(this,jp,"f").dispatchEvent("peerConnectFailed",{peerId:t.peerId,trackerUrl:e,error:t.error}))},o=t=>{Hp(this,jp,"f").dispatchEvent("warning",{trackerUrl:e,warning:t})},l=t=>{Hp(this,jp,"f").dispatchEvent("error",{trackerUrl:e,error:t})};r.addEventListener("peerConnected",n),r.addEventListener("peerConnectFailed",a),r.addEventListener("warning",o),r.addEventListener("error",l);const h=()=>{r.removeEventListener("peerConnected",n),r.removeEventListener("peerConnectFailed",a),r.removeEventListener("warning",o),r.removeEventListener("error",l)};Hp(this,Yp,"f").add({client:r,releaseSocket:s,cleanupListeners:h}),i=!0,r.start()}catch(e){throw i||s(),e}}}catch(e){throw this.destroy(),e}}}destroy(){if(Hp(this,zp,"f"))return;Gp(this,zp,!0,"f");for(const{client:e,releaseSocket:t,cleanupListeners:s}of Hp(this,Yp,"f"))s(),e.destroy(),t();Hp(this,Yp,"f").clear(),Hp(this,Kp,"f").clear();const e=[...Hp(this,Vp,"f").entries()];Hp(this,Vp,"f").clear();for(const[t,s]of e){s.cleanup();try{s.channel.close()}catch(e){}try{s.connection.close()}catch(e){}Hp(this,jp,"f").dispatchEvent("peerDisconnected",{peerId:t,trackerUrl:s.trackerUrl,disconnectReason:"Manager destroyed"})}Hp(this,jp,"f").clear()}},qp=new WeakMap,jp=new WeakMap,Kp=new WeakMap,Vp=new WeakMap,Yp=new WeakMap,zp=new WeakMap,Qp=new WeakMap,Xp=new WeakMap,Wp=new WeakSet,Jp=function(e,t){if(Hp(this,zp,"f"))return;const s=Hp(this,Vp,"f").get(e);if(s){Hp(this,Vp,"f").delete(e),s.cleanup();try{s.channel.close()}catch(e){}try{s.connection.close()}catch(e){}Hp(this,jp,"f").dispatchEvent("peerDisconnected",Object.assign({peerId:e,trackerUrl:s.trackerUrl},t))}},Zp=function(e,t,s,i){if(Bg(t.iceConnectionState)){try{t.close()}catch(e){}return void Hp(this,jp,"f").dispatchEvent("peerConnectFailed",{peerId:e,trackerUrl:i,error:new df("connection-failed","Connection failed during promotion")})}const r=t=>Hp(this,Wp,"m",Jp).call(this,e,t),n=()=>{Bg(t.iceConnectionState)&&r({error:new af("connection-lost",`ICE connection state became ${t.iceConnectionState}`)})},a=()=>r({disconnectReason:"Data channel closed"}),o=()=>r({disconnectReason:"Data channel closing"}),l=e=>{const t=Fg(e,"Data channel error");r({error:new af("transport-error",`Data channel error: ${t}`)})};let h=t=>Hp(this,Wp,"m",Jp).call(this,e,t?{error:t}:{disconnectReason:"Closed by consumer"});Hp(this,Vp,"f").set(e,{connection:t,channel:s,trackerUrl:i,cleanup:()=>{h=null,t.removeEventListener("iceconnectionstatechange",n),s.removeEventListener("close",a),s.removeEventListener("closing",o),s.removeEventListener("error",l)}}),t.addEventListener("iceconnectionstatechange",n),s.addEventListener("close",a),s.addEventListener("closing",o),s.addEventListener("error",l),Hp(this,jp,"f").dispatchEvent("peerConnected",{peerId:e,connection:t,channel:s,trackerUrl:i,close:e=>null==h?void 0:h(e)})}}});function iv(e){const t=(s=e,(new TextEncoder).encode(s));var s;const i=[],r=8*t.length;for(let e=0;e<t.length;e++)i[e>>2]|=(255&t[e])<<24-e%4*8;i[r>>5]|=128<<24-r%32,i[15+(r+64>>9<<4)]=r;let n=1732584193,a=4023233417,o=2562383102,l=271733878,h=3285377520;const d=[];for(let e=0;e<i.length;e+=16){const t=n,s=a,r=o,c=l,u=h;for(let t=0;t<80;t++){if(t<16)d[t]=0|i[e+t];else{const e=d[t-3]^d[t-8]^d[t-14]^d[t-16];d[t]=e<<1|e>>>31}let s;s=t<20?1518500249+(a&o|~a&l):t<40?1859775393+(a^o^l):t<60?(a&o|a&l|o&l)-1894007588:(a^o^l)-899497514;const r=(n<<5|n>>>27)+h+(d[t]>>>0)+s|0;h=l,l=o,o=a<<30|a>>>2,a=n,n=r}n=n+t|0,a=a+s|0,o=o+r|0,l=l+c|0,h=h+u|0}let c="";const u=[n,a,o,l,h];for(let e=0;e<20;e++){const t=24-e%4*8,s=u[e>>2];c+=String.fromCharCode(s>>>t&255)}return c}var rv,nv=o({"../../node_modules/p2p-media-loader-core/lib/utils/hash.js"(){zf()}});function av({bitrate:e,codecs:t,width:s,height:i,language:r,channels:n,name:a,frameRate:o,videoRange:l}){const h=t?t.split(",").map(e=>{const t=(e=e.trim().toLowerCase()).split(".");if(3===t.length&&("avc1"===t[0]||"avc"===t[0])){const s=parseInt(t[1],10),i=parseInt(t[2],10);if(!isNaN(s)&&!isNaN(i)&&t[1]===s.toString()&&t[2]===i.toString()){const r=`00${s.toString(16)}`.slice(-2),n=`00${i.toString(16)}`.slice(-2);e=`${t[0]}.${r}00${n}`}}return e}).sort().join(","):"",d=r&&"und"!==r?r.slice(0,2).toLowerCase():"",c=n?n.toString().split("/")[0]:"",u=a?a.toLowerCase().trim():"",f=o&&!isNaN(Number(o))?Number(o).toString():"",g=l?l.toUpperCase().trim():"";return btoa(iv(`${null!=e?e:0}-${h}-${null!=s?s:""}-${null!=i?i:""}-${d}-${c}-${u}-${f}-${g}`))}function ov(e,t){return`${rv}-${e}-${function(e){return`${e.type}-${e.index}`}(t)}`}function lv(e,t){for(const s of e.values()){const e=s.segments.get(t);if(e)return e}}function hv(e,t,s,i,r){const{highDemandTimeWindow:n,httpDownloadTimeWindow:a,p2pDownloadTimeWindow:o}=function(e,t){const{highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r}=e,n={highDemandTimeWindow:s,httpDownloadTimeWindow:i,p2pDownloadTimeWindow:r};return t<=5?(n.httpDownloadTimeWindow=0,n.p2pDownloadTimeWindow=0):t<=10&&(n.p2pDownloadTimeWindow=n.httpDownloadTimeWindow),n}(s,r);return{isHighDemand:dv(e,t,n),isHttpDownloadable:dv(e,t,a),isP2PDownloadable:dv(e,t,o)&&i.isSegmentLoadingOrLoadedBySomeone(e)}}function dv(e,t,s){const{startTime:i,endTime:r}=e,{position:n,rate:a}=t;return!(n+s*a<i||n>r)}var cv,uv,fv,gv,mv=o({"../../node_modules/p2p-media-loader-core/lib/utils/stream.js"(){nv(),rv="v2"}}),pv=o({"../../node_modules/p2p-media-loader-core/lib/utils/version.js"(){cv="3.0.1"}});function vv(e){return btoa(iv(e).slice(0,15))}var yv,Sv,Ev,bv,Tv,wv,Iv,Lv,Av,kv,Rv,Cv,Pv,Dv,Mv,_v,Ov,xv,Fv,Bv,Uv,Nv,$v,Gv,Hv,Wv,qv,jv,Kv,Vv,Yv,zv,Qv,Xv,Jv,Zv,ey,ty=o({"../../node_modules/p2p-media-loader-core/lib/utils/peer.js"(){nv(),pv(),uv=`-PM${function(){const e=cv.split(".");return`${`00${e[0]}`.slice(-2)}${`00${e[1]}`.slice(-2)}`}()}-`,fv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",gv=20}});function sy(e){if(1===e.length)return e[0];let t=0;for(const s of e){const e=s.getDownloadBandwidth();e>t&&(t=e)}if(t>0){const s=Math.max(1,.1*t);let i=0,r=0;for(const t of e)t.getDownloadBandwidth()<=s?i++:r+=t.getDownloadBandwidth();let n=s;return i>0&&r>0&&i*s>r&&(n=r/i),function(e){if(0===e.length)throw new Error("Cannot get item from empty array");if(1===e.length)return e[0];let t=0;const s=e.map(e=>{const s=(i=e,Math.max(i.getDownloadBandwidth(),n));var i;return t+=s,s});let i=Math.random()*t;for(let t=0;t<e.length;t++)if(i-=s[t],i<=0)return e[t];return e[e.length-1]}(e)}return(s=e)[Math.floor(Math.random()*s.length)];var s}var iy=o({"../../node_modules/p2p-media-loader-core/lib/p2p/loader.js"(){zm(),sv(),mv(),zf(),ty(),yv=d(Cf(),1),Sv=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ev=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},bv=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},ey=class{constructor(e,t,s,i,r,n,a,o,l){var h;Tv.add(this),wv.set(this,void 0),Iv.set(this,new Map),Lv.set(this,void 0),Av.set(this,void 0),kv.set(this,!1),Rv.set(this,(0,yv.default)("p2pml-core:webtorrent-manager")),Cv.set(this,(0,yv.default)("p2pml-core:churn-cleanup")),Pv.set(this,void 0),Dv.set(this,void 0),Mv.set(this,void 0),_v.set(this,void 0),Ov.set(this,void 0),xv.set(this,void 0),Fv.set(this,void 0),Bv.set(this,void 0),Uv.set(this,void 0),Nv.set(this,void 0),$v.set(this,void 0),Gv.set(this,void 0),Hv.set(this,void 0),Wv.set(this,void 0),qv.set(this,void 0),jv.set(this,void 0),Kv.set(this,void 0),Vv.set(this,void 0),Yv.set(this,()=>{Ev(this,Nv,setTimeout(bv(this,Yv,"f"),Math.max(1e3,bv(this,xv,"f").p2pChurnCleanupIntervalMs)),"f");const e=bv(this,Iv,"f").size-bv(this,xv,"f").p2pMaxPeers;if(e<=0)return;const t=[],s=performance.now();for(const e of bv(this,Iv,"f").values())e.downloadingSegment||e.isUploadingSegment||s-e.connectedAt<bv(this,xv,"f").p2pChurnGracePeriodMs||t.push(e);if(0===t.length)return;t.sort((e,t)=>e.getDownloadBandwidth()-t.getDownloadBandwidth()||e.connectedAt-t.connectedAt);const i=t.slice(0,e);bv(this,Cv,"f").call(this,`Background churn cleanup: dropping ${i.length} excess peers (total: ${bv(this,Iv,"f").size}, target: ${bv(this,xv,"f").p2pMaxPeers}, eligible: ${t.length})`);for(const e of i)bv(this,Cv,"f").call(this,`dropping excess peer ${e.id} with bandwidth ${e.getDownloadBandwidth()}`),e.destroy()}),Qv.set(this,e=>{if(bv(this,Rv,"f").call(this,`peerConnected: peerId=${e.peerId}`),bv(this,Iv,"f").has(e.peerId))return void e.close();const t=new xm(e.peerId,e.channel,e.close,{onSegmentRequested:(e,t,s,i)=>{bv(this,Zv,"f").call(this,e,t,s,i).catch(s=>{bv(this,Rv,"f").call(this,`Error in onSegmentRequested ${t} for peer ${e.id}:`,s)})},onSegmentsAnnouncement:(t,s)=>{bv(this,Vv,"f").call(this,e.peerId,bv(this,Pv,"f"),bv(this,Mv,"f").type,t,s),bv(this,Uv,"f").call(this)},onWarning:e=>{bv(this,qv,"f").call(this,{peerId:t.id,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,warning:e})}},{p2pNotReceivingBytesTimeoutMs:bv(this,xv,"f").p2pNotReceivingBytesTimeoutMs,webRtcMaxMessageSize:bv(this,xv,"f").webRtcMaxMessageSize,p2pErrorRetries:bv(this,xv,"f").p2pErrorRetries,validateP2PSegment:bv(this,xv,"f").validateP2PSegment,streamType:bv(this,Mv,"f").type,infoHash:bv(this,Pv,"f")},bv(this,Bv,"f"));if(bv(this,Iv,"f").set(e.peerId,t),bv(this,$v,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type}),bv(this,xv,"f").isP2PUploadDisabled)return;const{httpLoading:s,loaded:i}=bv(this,Tv,"m",zv).call(this);t.sendSegmentsAnnouncementCommand(i,s)}),Xv.set(this,e=>{var t;bv(this,Rv,"f").call(this,"peerDisconnected: peerId=%s error=%s reason=%s",e.peerId,null===(t=e.error)||void 0===t?void 0:t.message,e.disconnectReason);const s=bv(this,Iv,"f").get(e.peerId);s&&(bv(this,Iv,"f").delete(e.peerId),s.destroy(!0),e.error&&bv(this,Wv,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,error:e.error}),bv(this,Hv,"f").call(this,{peerId:s.id,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type}))}),Object.defineProperty(this,"broadcastAnnouncement",{enumerable:!0,configurable:!0,writable:!0,value:(e=!1)=>{e?bv(this,Jv,"f").call(this,e):bv(this,kv,"f")||bv(this,xv,"f").isP2PUploadDisabled||bv(this,Jv,"f").call(this)}}),Jv.set(this,(e=!1)=>{Ev(this,kv,!0,"f"),Mf(()=>{const{loaded:t=[],httpLoading:s=[]}=e?{}:bv(this,Tv,"m",zv).call(this);for(const e of bv(this,Iv,"f").values())e.sendSegmentsAnnouncementCommand(t,s);Ev(this,kv,!1,"f")})}),Zv.set(this,(e,t,s,i)=>Sv(this,void 0,void 0,function*(){const r=function(e,t){for(const s of e.segments.values())if(s.externalId===t)return s}(bv(this,Mv,"f"),t);if(!r)return;if(bv(this,xv,"f").isP2PUploadDisabled)return void e.sendSegmentAbsentCommand(t,s);let n;try{n=yield bv(this,Ov,"f").getSegmentData(bv(this,Lv,"f"),bv(this,Av,"f"),r.externalId)}catch(s){bv(this,Rv,"f").call(this,`Storage error for segment ${t} requested by peer ${e.id}:`,s)}!bv(this,Iv,"f").has(e.id)||(n?yield e.uploadSegmentData(r,s,void 0!==i?new Uint8Array(n).subarray(i):n):e.sendSegmentAbsentCommand(t,s))})),Ev(this,Dv,e,"f"),Ev(this,Mv,t,"f"),Ev(this,_v,s,"f"),Ev(this,Ov,i,"f"),Ev(this,xv,r,"f"),Ev(this,Fv,n,"f"),Ev(this,Bv,a,"f"),Ev(this,Uv,l,"f"),Ev(this,$v,a.getEventDispatcher("onPeerConnect"),"f"),Ev(this,Gv,a.getEventDispatcher("onPeerConnectError"),"f"),Ev(this,Hv,a.getEventDispatcher("onPeerClose"),"f"),Ev(this,Wv,a.getEventDispatcher("onPeerError"),"f"),Ev(this,qv,a.getEventDispatcher("onPeerWarning"),"f"),Ev(this,jv,a.getEventDispatcher("onTrackerWarning"),"f"),Ev(this,Kv,a.getEventDispatcher("onTrackerError"),"f"),Ev(this,Vv,a.getEventDispatcher("onPeerSegmentsAnnouncement"),"f"),Ev(this,Lv,null!==(h=bv(this,xv,"f").swarmId)&&void 0!==h?h:bv(this,Dv,"f"),"f"),Ev(this,Av,ov(bv(this,Lv,"f"),bv(this,Mv,"f")),"f");const d=vv(bv(this,Av,"f"));Ev(this,Pv,d,"f"),Ev(this,wv,new ev({infoHash:d,peerId:o,trackerUrls:bv(this,xv,"f").announceTrackers,rtcConfig:()=>bv(this,xv,"f").rtcConfig,socketPool:bv(this,Fv,"f"),maxPeers:()=>bv(this,xv,"f").p2pMaxPeers,maxPeersMultiplier:()=>bv(this,xv,"f").p2pChurnMaxPeersMultiplier,offersCount:()=>bv(this,xv,"f").webRtcOffersCount,offerTimeout:()=>bv(this,xv,"f").webRtcOfferTimeoutMs,iceGatheringTimeout:()=>bv(this,xv,"f").webRtcIceGatheringTimeoutMs,connectionTimeout:()=>bv(this,xv,"f").webRtcConnectionTimeoutMs}),"f"),bv(this,wv,"f").addEventListener("peerConnected",bv(this,Qv,"f")),bv(this,wv,"f").addEventListener("peerDisconnected",bv(this,Xv,"f")),bv(this,wv,"f").addEventListener("peerConnectFailed",e=>{bv(this,Rv,"f").call(this,`Peer connection failed (${e.peerId}) from tracker ${e.trackerUrl}:`,e.error),bv(this,Gv,"f").call(this,{peerId:e.peerId,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,trackerUrl:e.trackerUrl,error:e.error})}),bv(this,wv,"f").addEventListener("warning",e=>{bv(this,Rv,"f").call(this,`Tracker warning (${e.trackerUrl}):`,e.warning),bv(this,jv,"f").call(this,{trackerUrl:e.trackerUrl,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,warning:e.warning})}),bv(this,wv,"f").addEventListener("error",e=>{bv(this,Rv,"f").call(this,`Tracker error (${e.trackerUrl}):`,e.error),bv(this,Kv,"f").call(this,{trackerUrl:e.trackerUrl,infoHash:bv(this,Pv,"f"),streamType:bv(this,Mv,"f").type,error:e.error})}),bv(this,Bv,"f").addEventListener(`onStorageUpdated-${bv(this,Av,"f")}`,this.broadcastAnnouncement),bv(this,wv,"f").start(),Ev(this,Nv,setTimeout(bv(this,Yv,"f"),Math.max(1e3,bv(this,xv,"f").p2pChurnCleanupIntervalMs)),"f")}downloadSegment(e){const t=[];for(const s of bv(this,Iv,"f").values())s.downloadingSegment||"loaded"!==s.getSegmentStatus(e)||t.push(s);if(0===t.length)return;const s=sy(t),i=bv(this,_v,"f").getOrCreateRequest(e);s.downloadSegment(i)}isSegmentLoadingOrLoadedBySomeone(e){for(const t of bv(this,Iv,"f").values())if(t.getSegmentStatus(e))return!0;return!1}isSegmentLoadedBySomeone(e){for(const t of bv(this,Iv,"f").values())if("loaded"===t.getSegmentStatus(e))return!0;return!1}get connectedPeerCount(){return bv(this,Iv,"f").size}*peers(){for(const e of bv(this,Iv,"f").values())yield e}destroy(){clearTimeout(bv(this,Nv,"f")),Ev(this,Nv,void 0,"f"),bv(this,Bv,"f").removeEventListener(`onStorageUpdated-${bv(this,Av,"f")}`,this.broadcastAnnouncement),bv(this,wv,"f").destroy();for(const e of bv(this,Iv,"f").values())e.destroy();bv(this,Iv,"f").clear()}},wv=new WeakMap,Iv=new WeakMap,Lv=new WeakMap,Av=new WeakMap,kv=new WeakMap,Rv=new WeakMap,Cv=new WeakMap,Pv=new WeakMap,Dv=new WeakMap,Mv=new WeakMap,_v=new WeakMap,Ov=new WeakMap,xv=new WeakMap,Fv=new WeakMap,Bv=new WeakMap,Uv=new WeakMap,Nv=new WeakMap,$v=new WeakMap,Gv=new WeakMap,Hv=new WeakMap,Wv=new WeakMap,qv=new WeakMap,jv=new WeakMap,Kv=new WeakMap,Vv=new WeakMap,Yv=new WeakMap,Qv=new WeakMap,Xv=new WeakMap,Jv=new WeakMap,Zv=new WeakMap,Tv=new WeakSet,zv=function(){const e=bv(this,Ov,"f").getStoredSegmentIds(bv(this,Lv,"f"),bv(this,Av,"f")),t=[];for(const e of bv(this,_v,"f").httpRequests()){const s=bv(this,Mv,"f").segments.get(e.segment.runtimeId);s&&t.push(s.externalId)}return{loaded:e,httpLoading:t}}}});function ry(e){return`${e.type}-${e.index}`}function ny(e){const{externalId:t}=e;return`(${ry(e.stream)} | ${t})`}var ay,oy,ly,hy,dy,cy,uy,fy,gy,my,py,vy,yy,Sy,Ey,by,Ty,wy,Iy,Ly,Ay,ky,Ry,Cy,Py,Dy=o({"../../node_modules/p2p-media-loader-core/lib/utils/logger.js"(){}}),My=o({"../../node_modules/p2p-media-loader-core/lib/p2p/loaders-container.js"(){iy(),ay=d(Cf(),1),Dy(),mv(),oy=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},ly=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},Ly=class{constructor(e,t,s,i,r,n,a,o,l){hy.add(this),dy.set(this,new Map),cy.set(this,void 0),uy.set(this,(0,ay.default)("p2pml-core:p2p-loaders-container")),fy.set(this,void 0),gy.set(this,void 0),my.set(this,void 0),py.set(this,void 0),vy.set(this,void 0),yy.set(this,void 0),Sy.set(this,void 0),Ey.set(this,void 0),oy(this,fy,e,"f"),oy(this,gy,s,"f"),oy(this,my,i,"f"),oy(this,py,r,"f"),oy(this,vy,n,"f"),oy(this,yy,a,"f"),oy(this,Sy,o,"f"),oy(this,Ey,l,"f"),oy(this,cy,ly(this,hy,"m",Ty).call(this,t),"f"),ly(this,uy,"f").call(this,`set current p2p loader: ${ry(t)}`)}changeCurrentLoader(e){var t;const s=null!==(t=ly(this,py,"f").swarmId)&&void 0!==t?t:ly(this,fy,"f"),i=ov(s,ly(this,cy,"f").stream);ly(this,my,"f").getStoredSegmentIds(s,i).length?ly(this,hy,"m",wy).call(this,ly(this,cy,"f")):ly(this,hy,"m",Iy).call(this,ly(this,cy,"f")),oy(this,cy,ly(this,hy,"m",Ty).call(this,e),"f"),ly(this,uy,"f").call(this,`change current p2p loader: ${ry(e)}`)}get currentLoader(){return ly(this,cy,"f").loader}destroy(){for(const{loader:e,destroyTimeoutId:t}of ly(this,dy,"f").values())e.destroy(),clearTimeout(t);ly(this,dy,"f").clear()}},dy=new WeakMap,cy=new WeakMap,uy=new WeakMap,fy=new WeakMap,gy=new WeakMap,my=new WeakMap,py=new WeakMap,vy=new WeakMap,yy=new WeakMap,Sy=new WeakMap,Ey=new WeakMap,hy=new WeakSet,by=function(e){if(ly(this,dy,"f").has(e.runtimeId))throw new Error("Loader for this stream already exists");const t=new ey(ly(this,fy,"f"),e,ly(this,gy,"f"),ly(this,my,"f"),ly(this,py,"f"),ly(this,vy,"f"),ly(this,yy,"f"),ly(this,Sy,"f"),()=>{ly(this,cy,"f").loader===t&&ly(this,Ey,"f").call(this)}),s=ry(e);return ly(this,uy,"f").call(this,`created new loader: ${s}`),{loader:t,stream:e,loggerInfo:s}},Ty=function(e){const t=ly(this,dy,"f").get(e.runtimeId);if(t)return clearTimeout(t.destroyTimeoutId),t.destroyTimeoutId=void 0,t;{const t=ly(this,hy,"m",by).call(this,e);return ly(this,dy,"f").set(e.runtimeId,t),t}},wy=function(e){e.destroyTimeoutId=window.setTimeout(()=>ly(this,hy,"m",Iy).call(this,e),ly(this,py,"f").p2pInactiveLoaderDestroyTimeoutMs)},Iy=function(e){e.loader.destroy(),ly(this,dy,"f").delete(e.stream.runtimeId),ly(this,uy,"f").call(this,"destroy p2p loader: ",e.loggerInfo)}}});function _y(e){return{runtimeId:e.runtimeId,externalId:e.externalId,url:e.url,byteRange:e.byteRange,startTime:e.startTime,endTime:e.endTime}}var Oy,xy,Fy=o({"../../node_modules/p2p-media-loader-core/lib/requests/request.js"(){Ay=d(Cf(),1),If(),zf(),ky=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Ry=class{constructor(e,t,s,i,r,n,a){Object.defineProperty(this,"segment",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"requestProcessQueueCallback",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"playbackConfig",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"infoHash",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"currentAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_failedAttempts",{enumerable:!0,configurable:!0,writable:!0,value:new Cy}),Object.defineProperty(this,"finalData",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"bytes",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_loadedBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_totalBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_status",{enumerable:!0,configurable:!0,writable:!0,value:"not-started"}),Object.defineProperty(this,"progress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"notReceivingBytesTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_onAbortCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"notReceivingBytesTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_isHandledByProcessQueue",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"onSegmentError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentAbort",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onSegmentLoaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortOnTimeout",{enumerable:!0,configurable:!0,writable:!0,value:()=>{var e,t;if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress||void 0===this.notReceivingBytesTimeoutMs)return;const s=performance.now()-(null!==(e=this.progress.lastLoadedChunkTimestamp)&&void 0!==e?e:this.progress.startTimestamp);if(s<this.notReceivingBytesTimeoutMs)return void this.notReceivingBytesTimeout.restart(this.notReceivingBytesTimeoutMs-s);const i=new cf("bytes-receiving-timeout");null===(t=this._onAbortCallback)||void 0===t||t.call(this,i),this.handleFailure(i)}}),Object.defineProperty(this,"failWithError",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&this.handleFailure(e)}}),Object.defineProperty(this,"handleFailure",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.currentAttempt&&(this.setStatus("failed"),this.logger(`${this.downloadSource} ${this.segment.externalId} failed ${e.type}`),this._failedAttempts.add(Object.assign(Object.assign({},this.currentAttempt),{error:e})),this.onSegmentError({segment:_y(this.segment),error:e,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.notReceivingBytesTimeout.clear(),this.manageBandwidthCalculatorsState("stop"),this.requestProcessQueueCallback())}}),Object.defineProperty(this,"completeOnSuccess",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.throwErrorIfNotLoadingStatus(),this.currentAttempt&&(this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear(),this.setStatus("succeed"),this._totalBytes=this._loadedBytes,this.onSegmentLoaded({segmentUrl:this.segment.url,segment:_y(this.segment),bytesLength:this.data.byteLength,downloadSource:this.currentAttempt.downloadSource,peerId:"p2p"===this.currentAttempt.downloadSource?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this.logger(`${this.currentAttempt.downloadSource} ${this.segment.externalId} succeed`),this.requestProcessQueueCallback())}}),Object.defineProperty(this,"addLoadedChunk",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(this.throwErrorIfNotLoadingStatus(),!this.currentAttempt||!this.progress)return;const{byteLength:t}=e,{all:s,http:i}=this.bandwidthCalculators;s.addBytes(t),"http"===this.currentAttempt.downloadSource&&i.addBytes(t),this.bytes.push(e),this.progress.lastLoadedChunkTimestamp=performance.now(),this.progress.loadedBytes+=t,this._loadedBytes+=t}}),Object.defineProperty(this,"firstBytesReceived",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.throwErrorIfNotLoadingStatus()}}),this.onSegmentError=n.getEventDispatcher("onSegmentError"),this.onSegmentAbort=n.getEventDispatcher("onSegmentAbort"),this.onSegmentStart=n.getEventDispatcher("onSegmentStart"),this.onSegmentLoaded=n.getEventDispatcher("onSegmentLoaded");const{byteRange:o}=this.segment;if(o){const{end:e,start:t}=o;this._totalBytes=e-t+1}this.notReceivingBytesTimeout=new Py(this.abortOnTimeout);const{type:l}=this.segment.stream;this._logger=(0,Ay.default)(`p2pml-core:request-${l}`)}clearLoadedBytes(){this._loadedBytes=0,this.bytes=[],this._totalBytes=void 0,this.finalData=void 0}get status(){return this._status}setStatus(e){this._status=e,this._isHandledByProcessQueue=!1}get downloadSource(){var e;return null===(e=this.currentAttempt)||void 0===e?void 0:e.downloadSource}get loadedBytes(){return this._loadedBytes}get totalBytes(){return this._totalBytes}get data(){var e;return null!==(e=this.finalData)&&void 0!==e||(this.finalData=_f(this.bytes).buffer),this.finalData}get failedAttempts(){return this._failedAttempts}get isHandledByProcessQueue(){return this._isHandledByProcessQueue}markHandledByProcessQueue(){this._isHandledByProcessQueue=!0}setTotalBytes(e){if(void 0!==this._totalBytes)throw new Error("Request total bytes value is already set");this._totalBytes=e}tryCompleteByLoadedBytes(e,t,s,i){if(!this._totalBytes)return!1;if(this._loadedBytes>this._totalBytes)return this.logger(`${e.downloadSource} ${this.segment.externalId} loaded bytes overflow: ${this._loadedBytes} > ${this._totalBytes}, clearing`),this.clearLoadedBytes(),!1;if(this._loadedBytes!==this._totalBytes)return!1;const r=this.start(e,t);return this.notReceivingBytesTimeout.clear(),s?this.validateAndComplete(e.downloadSource,r,s,i):r.completeOnSuccess(),!0}validateData(e){return ky(this,void 0,void 0,function*(){if(!e)return!0;try{return yield e(this.segment.url,this.segment.byteRange,this.data)}catch(e){return this.logger(`validation threw an error: ${String(e)}`),!1}})}validateAndComplete(e,t,s,i){return ky(this,void 0,void 0,function*(){const r=yield this.validateData(s);if("loading"===this._status){if(!r)return this.logger(`${e} ${this.segment.externalId} validation failed for already-loaded bytes, clearing`),this.clearLoadedBytes(),void t.failWithError(new cf(i));this.logger(`${e} ${this.segment.externalId} validation passed for already-loaded bytes`),t.completeOnSuccess()}})}start(e,t){if("succeed"===this._status)throw new Error(`Request ${this.segment.externalId} has been already succeed.`);if("loading"===this._status)throw new Error(`Request ${this.segment.externalId} has been already started.`);this.setStatus("loading"),this.currentAttempt=Object.assign({},e),this.progress={startFromByte:this._loadedBytes,loadedBytes:0,startTimestamp:performance.now()},this.manageBandwidthCalculatorsState("start");const{notReceivingBytesTimeoutMs:s}=t;return this._onAbortCallback=t.onAbort,this.notReceivingBytesTimeoutMs=s,void 0!==s&&this.notReceivingBytesTimeout.start(s),this.logger(`${e.downloadSource} ${this.segment.externalId} started`),this.onSegmentStart({segment:_y(this.segment),downloadSource:e.downloadSource,peerId:"p2p"===e.downloadSource?e.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),{firstBytesReceived:this.firstBytesReceived,addLoadedChunk:this.addLoadedChunk,completeOnSuccess:this.completeOnSuccess,failWithError:this.failWithError}}cancel(){var e,t,s,i;this.throwErrorIfNotLoadingStatus(),this.setStatus("aborted"),this.logger(`${null===(e=this.currentAttempt)||void 0===e?void 0:e.downloadSource} ${this.segment.externalId} aborted`),null===(t=this._onAbortCallback)||void 0===t||t.call(this,new cf("abort")),this.onSegmentAbort({segment:_y(this.segment),downloadSource:null===(s=this.currentAttempt)||void 0===s?void 0:s.downloadSource,peerId:"p2p"===(null===(i=this.currentAttempt)||void 0===i?void 0:i.downloadSource)?this.currentAttempt.peerId:void 0,infoHash:this.infoHash,streamType:this.segment.stream.type}),this._onAbortCallback=void 0,this.manageBandwidthCalculatorsState("stop"),this.notReceivingBytesTimeout.clear()}throwErrorIfNotLoadingStatus(){if("loading"!==this._status)throw new Error(`Request has been already ${this.status}.`)}logger(e){var t;this._logger.color="http"===(null===(t=this.currentAttempt)||void 0===t?void 0:t.downloadSource)?"green":"red",this._logger(e),this._logger.color=""}manageBandwidthCalculatorsState(e){var t;const{all:s,http:i}=this.bandwidthCalculators,r="start"===e?"startLoading":"stopLoading";"http"===(null===(t=this.currentAttempt)||void 0===t?void 0:t.downloadSource)&&i[r](),s[r]()}},Cy=class{constructor(){Object.defineProperty(this,"attempts",{enumerable:!0,configurable:!0,writable:!0,value:[]})}add(e){this.attempts.push(e)}get httpAttemptsCount(){return this.attempts.reduce((e,t)=>"http"===t.downloadSource?e+1:e,0)}get p2pAttemptsCount(){return this.attempts.reduce((e,t)=>"p2p"===t.downloadSource?e+1:e,0)}get lastAttempt(){return this.attempts[this.attempts.length-1]}clear(){this.attempts=[]}},Py=class{constructor(e){Object.defineProperty(this,"action",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"timeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}start(e){if(this.timeoutId)throw new Error("Timeout is already started.");this.ms=e,this.timeoutId=window.setTimeout(this.action,this.ms)}restart(e){this.clear(),void 0!==e&&(this.ms=e),void 0!==this.ms&&(this.timeoutId=window.setTimeout(this.action,this.ms))}clear(){clearTimeout(this.timeoutId),this.timeoutId=void 0}}}}),By=o({"../../node_modules/p2p-media-loader-core/lib/requests/request-container.js"(){Fy(),mv(),ty(),Oy=class{constructor(e,t,s,i,r,n){Object.defineProperty(this,"requestProcessQueueCallback",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"swarmId",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"requests",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}get executingHttpCount(){let e=0;for(const t of this.httpRequests())"loading"===t.status&&e++;return e}get executingP2PCount(){let e=0;for(const t of this.p2pRequests())"loading"===t.status&&e++;return e}get(e){return this.requests.get(e)}getOrCreateRequest(e){let t=this.requests.get(e);if(!t){const s=vv(ov(this.swarmId,e.stream));t=new Ry(e,this.requestProcessQueueCallback,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,s),this.requests.set(e,t)}return t}remove(e){this.requests.delete(e.segment)}items(){return this.requests.values()}*httpRequests(){for(const e of this.requests.values())"http"===e.downloadSource&&(yield e)}*p2pRequests(){for(const e of this.requests.values())"p2p"===e.downloadSource&&(yield e)}destroy(){for(const e of this.requests.values())"loading"===e.status&&e.cancel();this.requests.clear()}}}}),Uy=o({"../../node_modules/p2p-media-loader-core/lib/requests/engine-request.js"(){If(),xy=class{constructor(e,t){Object.defineProperty(this,"segment",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"engineCallbacks",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"_status",{enumerable:!0,configurable:!0,writable:!0,value:"pending"}),Object.defineProperty(this,"_shouldBeStartedImmediately",{enumerable:!0,configurable:!0,writable:!0,value:!1})}get status(){return this._status}get shouldBeStartedImmediately(){return this._shouldBeStartedImmediately}resolve(e,t){"pending"===this._status&&(this._status="succeed",this.engineCallbacks.onSuccess({data:e,bandwidth:t}))}reject(){"pending"===this._status&&(this._status="failed",this.engineCallbacks.onError(new uf("failed")))}abort(){"pending"===this._status&&(this._status="aborted",this.engineCallbacks.onError(new uf("aborted")))}markAsShouldBeStartedImmediately(){this._shouldBeStartedImmediately=!0}}}});function*Ny(e,t,s,i,r){const{runtimeId:n,stream:a}=e,o=a.segments.get(n);if(!o)return;const l=a.segments.values();let h;do{const e=l.next();if(e.done)return;h=e.value}while(h!==o);const d=hv(h,t,s,i,r);if($y(d)){const e=l.next();if(e.done)return;const n=e.value,a=hv(n,t,s,i,r);if($y(a))return;d.isHighDemand=!0,yield{segment:h,statuses:d},yield{segment:n,statuses:a}}else yield{segment:h,statuses:d};for(const e of l){const n=hv(e,t,s,i,r);if($y(n))break;yield{segment:e,statuses:n}}}function $y(e){const{isHighDemand:t,isHttpDownloadable:s,isP2PDownloadable:i}=e;return!t&&!s&&!i}var Gy,Hy,Wy,qy,jy,Ky,Vy,Yy,zy,Qy,Xy,Jy,Zy,eS,tS,sS,iS,rS,nS,aS,oS,lS,hS,dS,cS,uS,fS,gS,mS,pS,vS,yS,SS,ES,bS,TS,wS,IS,LS,AS,kS,RS,CS,PS,DS,MS,_S,OS,xS,FS,BS,US,NS,$S,GS,HS,WS,qS,jS,KS,VS,YS,zS,QS=o({"../../node_modules/p2p-media-loader-core/lib/utils/queue.js"(){mv()}}),XS=o({"../../node_modules/p2p-media-loader-core/lib/hybrid-loader.js"(){Af(),My(),By(),Uy(),QS(),Dy(),mv(),zf(),Gy=d(Cf(),1),Hy=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Wy=class{constructor(e,t,s,i,r,n,a,o,l){var h;Object.defineProperty(this,"streamManifestUrl",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lastRequestedSegment",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"streamDetails",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"segmentStorage",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"webTorrentSocketPool",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"peerId",{enumerable:!0,configurable:!0,writable:!0,value:l}),Object.defineProperty(this,"requests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"engineRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"p2pLoaders",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentAvgDuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"levelChangedTimestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastQueueProcessingTimeStamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"randomHttpDownloadTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"initialHttpDelayTimeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isProcessQueueMicrotaskCreated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"swarmId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"createdAt",{enumerable:!0,configurable:!0,writable:!0,value:performance.now()}),Object.defineProperty(this,"requestProcessQueueMicrotask",{enumerable:!0,configurable:!0,writable:!0,value:(e=!0)=>{const t=performance.now();!e&&void 0!==this.lastQueueProcessingTimeStamp&&t-this.lastQueueProcessingTimeStamp<=1e3||this.isProcessQueueMicrotaskCreated||(this.isProcessQueueMicrotaskCreated=!0,Mf(()=>{try{this.processQueue(),this.lastQueueProcessingTimeStamp=t}finally{this.isProcessQueueMicrotaskCreated=!1}}))}});const d=this.lastRequestedSegment.stream;this.swarmId=null!==(h=this.config.swarmId)&&void 0!==h?h:this.streamManifestUrl,this.playback={position:this.lastRequestedSegment.startTime,rate:1},this.segmentAvgDuration=function(e){const{segments:t}=e;let s=0;const{size:i}=t;if(0===i)return 0;for(const e of t.values())s+=e.endTime-e.startTime;return s/i}(d),this.requests=new Oy(this.requestProcessQueueMicrotask,this.bandwidthCalculators,this.playback,this.config,this.eventTarget,this.swarmId),this.p2pLoaders=new Ly(this.streamManifestUrl,this.lastRequestedSegment.stream,this.requests,this.segmentStorage,this.config,this.webTorrentSocketPool,this.eventTarget,this.peerId,this.requestProcessQueueMicrotask),this.logger=(0,Gy.default)(`p2pml-core:hybrid-loader-${d.type}`),this.logger.color="coral",this.setIntervalLoading()}setIntervalLoading(){const e=this.p2pLoaders.currentLoader.connectedPeerCount,t=1e3*Math.random()*e+1e3;this.randomHttpDownloadTimeout=window.setTimeout(()=>{this.loadRandomThroughHttp(),this.setIntervalLoading()},t)}loadSegment(e,t){return Hy(this,void 0,void 0,function*(){var s;this.logger(`requests: ${ny(e)}`);const{stream:i}=e;i!==this.lastRequestedSegment.stream&&(this.logger(`stream changed to ${ry(i)}`),this.p2pLoaders.changeCurrentLoader(i)),this.lastRequestedSegment=e;const r=ov(this.swarmId,i);this.segmentStorage.onSegmentRequested(this.swarmId,r,e.externalId,e.startTime,e.endTime,i.type,this.streamDetails.isLive);const n=new xy(e,t);try{if(this.segmentStorage.hasSegment(this.swarmId,r,e.externalId)){const t=yield this.segmentStorage.getSegmentData(this.swarmId,r,e.externalId);if(t){const{queueDownloadRatio:e}=this.generateQueue();return void n.resolve(t,this.getBandwidth(e))}}null===(s=this.engineRequest)||void 0===s||s.abort(),this.engineRequest=n;const t=this.requests.get(e);"failed"===(null==t?void 0:t.status)&&t.failedAttempts.clear()}catch(t){this.logger(`request failed for ${ny(e)} in ${ry(i)}`,t),n.reject()}finally{this.requestProcessQueueMicrotask()}})}processRequests(e,t){var s;const{stream:i}=this.lastRequestedSegment,{httpErrorRetries:r}=this.config,n=performance.now();for(const a of this.requests.items()){const{downloadSource:o,status:l,segment:h,isHandledByProcessQueue:d}=a,c=(null===(s=this.engineRequest)||void 0===s?void 0:s.segment)===h?this.engineRequest:void 0;switch(l){case"loading":e.has(h.runtimeId)||c||(a.cancel(),this.requests.remove(a));break;case"succeed":{if(!o)break;"http"===o&&this.p2pLoaders.currentLoader.broadcastAnnouncement(),c&&(c.resolve(a.data,this.getBandwidth(t)),this.engineRequest=void 0),this.requests.remove(a),this.logger(`succeed: ${ny(h)} (byteLength: ${a.data.byteLength})`);const e=ov(this.swarmId,i);this.segmentStorage.storeSegment(this.swarmId,e,h.externalId,a.data,h.startTime,h.endTime,h.stream.type,this.streamDetails.isLive);break}case"failed":"http"!==o||d||this.p2pLoaders.currentLoader.broadcastAnnouncement(),c||i.segments.has(a.segment.runtimeId)||this.requests.remove(a),a.failedAttempts.httpAttemptsCount>=r&&c&&(this.engineRequest=void 0,c.reject());break;case"not-started":case"aborted":this.requests.remove(a)}a.markHandledByProcessQueue();const{lastAttempt:u}=a.failedAttempts;u&&n-u.error.timestamp>6e4&&a.failedAttempts.clear()}}processQueue(){var e,t,s;const{queue:i,queueSegmentIds:r,queueDownloadRatio:n}=this.generateQueue();this.processRequests(r,n);const{simultaneousHttpDownloads:a,simultaneousP2PDownloads:o,httpErrorRetries:l,httpDownloadInitialTimeoutMs:h}=this.config,d=performance.now()-this.createdAt,c=h>0&&d<h;c&&(null!==(e=this.initialHttpDelayTimeoutId)&&void 0!==e||(this.initialHttpDelayTimeoutId=window.setTimeout(()=>{this.initialHttpDelayTimeoutId=void 0,this.requestProcessQueueMicrotask()},h-d)));const{engineRequest:u}=this;if(u){const{segment:e}=u,s=this.requests.get(e);if(u.shouldBeStartedImmediately&&"pending"===u.status&&(!s||"not-started"===s.status||"failed"===s.status||"aborted"===s.status)){const i=!c&&(null!==(t=null==s?void 0:s.failedAttempts.httpAttemptsCount)&&void 0!==t?t:0)<l&&this.requests.executingHttpCount<a,r=this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(e)&&this.requests.executingP2PCount<o;this.config.preferP2PForEngineRequest&&r?this.loadThroughP2P(e):i?this.loadThroughHttp(e):r&&this.loadThroughP2P(e)}}for(const e of i){const{statuses:t,segment:r}=e,n=this.requests.get(r);if("succeed"!==(null==n?void 0:n.status))if(t.isHighDemand){const e=!c&&(null!==(s=null==n?void 0:n.failedAttempts.httpAttemptsCount)&&void 0!==s?s:0)<l;if("loading"===(null==n?void 0:n.status)){!this.config.preferP2PForEngineRequest&&e&&"p2p"===n.downloadSource&&(this.requests.executingHttpCount<a||this.abortLastHttpLoadingInQueueAfterItem(i,r))&&(n.cancel(),this.loadThroughHttp(r));continue}if(e&&(this.requests.executingHttpCount<a||this.abortLastHttpLoadingInQueueAfterItem(i,r))){this.loadThroughHttp(r);continue}this.p2pLoaders.currentLoader.isSegmentLoadedBySomeone(r)&&(this.requests.executingP2PCount<o||this.abortLastP2PLoadingInQueueAfterItem(i,r))&&this.loadThroughP2P(r)}else t.isP2PDownloadable&&"loading"!==(null==n?void 0:n.status)&&this.requests.executingP2PCount<o&&this.loadThroughP2P(r)}}abortSegmentRequest(e){var t;(null===(t=this.engineRequest)||void 0===t?void 0:t.segment.runtimeId)===e&&(this.engineRequest.abort(),this.logger("abort: ",ny(this.engineRequest.segment)),this.engineRequest=void 0,this.requestProcessQueueMicrotask())}loadThroughHttp(e){const t=this.requests.getOrCreateRequest(e);new Ef(t,this.config,this.eventTarget).execute(),this.p2pLoaders.currentLoader.broadcastAnnouncement()}loadThroughP2P(e){this.p2pLoaders.currentLoader.downloadSegment(e)}loadRandomThroughHttp(){const{httpDownloadInitialTimeoutMs:e}=this.config;if(e>0&&performance.now()-this.createdAt<e)return;const t=this.getAvailableStorageCapacityPercent();if(t<=10)return;const{simultaneousHttpDownloads:s,httpErrorRetries:i}=this.config,r=this.p2pLoaders.currentLoader;if(this.requests.executingHttpCount>=s||!r.connectedPeerCount)return;const n=[];for(const{segment:e,statuses:s}of Ny(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,t)){const t=ov(this.swarmId,e.stream);if(!s.isHttpDownloadable||s.isP2PDownloadable||this.segmentStorage.hasSegment(this.swarmId,t,e.externalId))continue;const r=this.requests.get(e);r&&("loading"===r.status||"succeed"===r.status||r.failedAttempts.httpAttemptsCount>=i)||n.push(e)}if(!n.length)return;if(0===s-this.requests.executingHttpCount)return;const a=r.connectedPeerCount+1,o=Math.min(n.length,s*a),l=function(e){for(let t=e.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]]}return e}(Array.from({length:o},(e,t)=>t));let h=o/a;for(const e of l){if(this.requests.executingHttpCount>=s)break;if(h>=1||Math.random()<=h){const t=n[e];this.loadThroughHttp(t)}if(h--,h<=0)break}}abortLastHttpLoadingInQueueAfterItem(e,t){for(const{segment:s}of Of(e)){if(s===t)break;const e=this.requests.get(s);if("http"===(null==e?void 0:e.downloadSource)&&"loading"===e.status)return e.cancel(),!0}return!1}abortLastP2PLoadingInQueueAfterItem(e,t){for(const{segment:s}of Of(e)){if(s===t)break;const e=this.requests.get(s);if("p2p"===(null==e?void 0:e.downloadSource)&&"loading"===e.status)return e.cancel(),!0}return!1}getAvailableStorageCapacityPercent(){const{totalCapacity:e,usedCapacity:t}=this.segmentStorage.getUsage();return 100-t/e*100}generateQueue(){var e;const t=[],s=new Set;let i=0,r=0;const n=this.getAvailableStorageCapacityPercent();for(const a of Ny(this.lastRequestedSegment,this.playback,this.config,this.p2pLoaders.currentLoader,n)){i++;const{segment:n}=a,o=ov(this.swarmId,n.stream);this.segmentStorage.hasSegment(this.swarmId,o,n.externalId)||"succeed"===(null===(e=this.requests.get(n))||void 0===e?void 0:e.status)?r++:(t.push(a),s.add(n.runtimeId))}return{queue:t,queueSegmentIds:s,maxPossibleLength:i,alreadyLoadedCount:r,queueDownloadRatio:0!==i?r/i:0}}getBandwidth(e){const{http:t,all:s}=this.bandwidthCalculators,{activeLevelBitrate:i}=this.streamDetails;if(0===i)return s.getBandwidthLoadingOnly(3);const r=Math.max(s.getBandwidth(30,this.levelChangedTimestamp),s.getBandwidth(60,this.levelChangedTimestamp),s.getBandwidth(90,this.levelChangedTimestamp));if(e>=.8||r>=.9*i)return Math.max(s.getBandwidthLoadingOnly(1),s.getBandwidthLoadingOnly(3),s.getBandwidthLoadingOnly(5));const n=Math.max(t.getBandwidthLoadingOnly(1),t.getBandwidthLoadingOnly(3),t.getBandwidthLoadingOnly(5));return Math.max(r,n)}notifyLevelChanged(){this.levelChangedTimestamp=performance.now()}sendBroadcastAnnouncement(e=!1){this.p2pLoaders.currentLoader.broadcastAnnouncement(e)}updatePlayback(e,t){var s;const i=this.playback.rate!==t,r=this.playback.position!==e;if(!i&&!r)return;const n=Math.abs(e-this.playback.position)/this.segmentAvgDuration>.5;r&&(this.playback.position=e),i&&0!==t&&(this.playback.rate=t),n&&(this.logger("position significantly changed"),null===(s=this.engineRequest)||void 0===s||s.markAsShouldBeStartedImmediately()),this.segmentStorage.onPlaybackUpdated(e,t),this.requestProcessQueueMicrotask(n)}updateStream(e){e===this.lastRequestedSegment.stream&&(this.logger(`update stream: ${ry(e)}`),this.requestProcessQueueMicrotask())}destroy(){var e;clearTimeout(this.randomHttpDownloadTimeout),clearTimeout(this.initialHttpDelayTimeoutId),null===(e=this.engineRequest)||void 0===e||e.abort(),this.requests.destroy(),this.p2pLoaders.destroy()}}}}),JS=o({"../../node_modules/p2p-media-loader-core/lib/segment-storage/utils.js"(){qy=(e,t)=>`${e}|${t}`,jy=e=>/Android/i.test(e),Ky=e=>/iPad|iPhone/i.test(e),Vy=e=>/Android/i.test(e)&&(/; wv\)/i.test(e)||!/Chrome|Firefox/i.test(e))}}),ZS=o({"../../node_modules/p2p-media-loader-core/lib/segment-storage/segment-memory-storage.js"(){Yy=d(Cf(),1),JS(),zy=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},Qy=1048576,Xy=class{constructor(){Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:navigator.userAgent}),Object.defineProperty(this,"segmentMemoryStorageLimit",{enumerable:!0,configurable:!0,writable:!0,value:4096}),Object.defineProperty(this,"currentStorageUsage",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"coreConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentPlayback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRequestedSegment",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentChangeCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=(0,Yy.default)("p2pml-core:segment-memory-storage"),this.logger.color="RebeccaPurple"}initialize(e,t,s){return zy(this,void 0,void 0,function*(){this.coreConfig=e,this.mainStreamConfig=t,this.secondaryStreamConfig=s,this.setMemoryStorageLimit(),this.logger("initialized")})}onPlaybackUpdated(e,t){this.currentPlayback={position:e,rate:t}}onSegmentRequested(e,t,s,i,r,n,a){this.lastRequestedSegment={streamId:t,segmentId:s,startTime:i,endTime:r,swarmId:e,streamType:n,isLiveStream:a}}storeSegment(e,t,s,i,r,n,a,o){return zy(this,void 0,void 0,function*(){this.clear(o,i.byteLength);const e=qy(t,s);if(this.cache.set(e,{data:i,segmentId:s,streamId:t,startTime:r,endTime:n,streamType:a}),this.increaseStorageUsage(i.byteLength),this.logger(`add segment: ${s} to ${t}`),!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(t)})}getSegmentData(e,t,s){return zy(this,void 0,void 0,function*(){const e=qy(t,s),i=this.cache.get(e);if(void 0!==i)return i.data})}getUsage(){if(!this.lastRequestedSegment||!this.currentPlayback)return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:this.currentStorageUsage};const e=this.currentPlayback.position;let t=0;for(const{endTime:s,data:i}of this.cache.values())e>s||(t+=i.byteLength);return{totalCapacity:this.segmentMemoryStorageLimit,usedCapacity:t/Qy}}hasSegment(e,t,s){const i=qy(t,s);return void 0!==this.cache.get(i)}getStoredSegmentIds(e,t){const s=[];for(const{segmentId:e,streamId:i}of this.cache.values())i===t&&s.push(e);return s}clear(e,t){if(!(this.currentPlayback&&this.mainStreamConfig&&this.secondaryStreamConfig&&this.coreConfig))return;if(!this.isMemoryLimitReached(t)&&!e)return;const s=new Set,i=Array.from(this.cache.values()).sort((e,t)=>e.startTime-t.startTime);for(const r of i){const{streamId:i,segmentId:n,data:a}=r,o=qy(i,n);if(this.shouldRemoveSegment(r,e,this.currentPlayback.position)&&(this.cache.delete(o),s.add(i),this.decreaseStorageUsage(a.byteLength),this.logger(`Removed segment ${n} from stream ${i}`),!this.isMemoryLimitReached(t)&&!e))break}this.sendUpdatesToAffectedStreams(s)}isMemoryLimitReached(e){return this.currentStorageUsage+e/Qy>this.segmentMemoryStorageLimit}setSegmentChangeCallback(e){this.segmentChangeCallback=e}sendUpdatesToAffectedStreams(e){0!==e.size&&e.forEach(e=>{if(!this.segmentChangeCallback)throw new Error("dispatchStorageUpdatedEvent is not set");this.segmentChangeCallback(e)})}shouldRemoveSegment(e,t,s){const{endTime:i,streamType:r}=e,n=this.getStreamTimeWindow(r,"highDemandTimeWindow");return!(s<=i)&&(!t||s>n+i)}increaseStorageUsage(e){this.currentStorageUsage+=e/Qy}decreaseStorageUsage(e){this.currentStorageUsage-=e/Qy}setMemoryStorageLimit(){var e;(null===(e=this.coreConfig)||void 0===e?void 0:e.segmentMemoryStorageLimit)?this.segmentMemoryStorageLimit=this.coreConfig.segmentMemoryStorageLimit:Vy(this.userAgent)||Ky(this.userAgent)?this.segmentMemoryStorageLimit=1024:jy(this.userAgent)&&(this.segmentMemoryStorageLimit=2048)}getStreamTimeWindow(e,t){var s;const i="main"===e?this.mainStreamConfig:this.secondaryStreamConfig;return null!==(s=null==i?void 0:i[t])&&void 0!==s?s:0}destroy(){this.cache.clear(),this.segmentChangeCallback=void 0}}}}),eE=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/websocket-client/index.js"(){Qm(),Jy=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},Zy=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},fS=class{constructor(e){var t,s,i;eS.add(this),tS.set(this,void 0),sS.set(this,"disconnected"),iS.set(this,null),rS.set(this,0),nS.set(this,null),aS.set(this,new Fm),oS.set(this,()=>{"disposed"!==Zy(this,sS,"f")&&(Jy(this,sS,"connected","f"),Jy(this,rS,0,"f"),Zy(this,aS,"f").dispatchEvent("connected"))}),lS.set(this,()=>{"disposed"!==Zy(this,sS,"f")&&(Zy(this,iS,"f")&&(Zy(this,iS,"f").onopen=null,Zy(this,iS,"f").onclose=null,Zy(this,iS,"f").onerror=null,Zy(this,iS,"f").onmessage=null,Jy(this,iS,null,"f")),Zy(this,eS,"m",cS).call(this),Zy(this,aS,"f").dispatchEvent("disconnected"))}),hS.set(this,e=>{"disposed"!==Zy(this,sS,"f")&&Zy(this,aS,"f").dispatchEvent("error",e)}),dS.set(this,e=>{"disposed"!==Zy(this,sS,"f")&&Zy(this,aS,"f").dispatchEvent("message",e.data)});const r=Math.max(100,null!==(t=e.initialDelay)&&void 0!==t?t:1e3);Jy(this,tS,{url:e.url,initialDelay:r,maxDelay:Math.max(r,null!==(s=e.maxDelay)&&void 0!==s?s:3e4),jitterMultiplier:Math.max(0,null!==(i=e.jitterMultiplier)&&void 0!==i?i:.2)},"f")}get state(){return Zy(this,sS,"f")}addEventListener(e,t){Zy(this,aS,"f").addEventListener(e,t)}removeEventListener(e,t){Zy(this,aS,"f").removeEventListener(e,t)}connect(){if("connected"!==Zy(this,sS,"f")&&"connecting"!==Zy(this,sS,"f")&&"disposed"!==Zy(this,sS,"f")){Jy(this,sS,"connecting","f"),Zy(this,eS,"m",uS).call(this);try{Jy(this,iS,new WebSocket(Zy(this,tS,"f").url),"f"),Zy(this,iS,"f").binaryType="arraybuffer",Zy(this,iS,"f").onopen=Zy(this,oS,"f"),Zy(this,iS,"f").onclose=Zy(this,lS,"f"),Zy(this,iS,"f").onerror=Zy(this,hS,"f"),Zy(this,iS,"f").onmessage=Zy(this,dS,"f")}catch(e){Jy(this,sS,"disconnected","f");const t=new ErrorEvent("error",{message:e instanceof Error?e.message:"Unknown WebSocket creation error",error:e});Zy(this,aS,"f").dispatchEvent("error",t)}}}send(e){if("connected"!==Zy(this,sS,"f")||!Zy(this,iS,"f"))throw new Error("WebSocketClient: Cannot send data when not connected");Zy(this,iS,"f").send(e)}dispose(){Jy(this,sS,"disposed","f"),Zy(this,eS,"m",uS).call(this),Zy(this,iS,"f")&&(Zy(this,iS,"f").onopen=null,Zy(this,iS,"f").onclose=null,Zy(this,iS,"f").onerror=null,Zy(this,iS,"f").onmessage=null,Zy(this,iS,"f").close(),Jy(this,iS,null,"f")),Zy(this,aS,"f").clear()}},tS=new WeakMap,sS=new WeakMap,iS=new WeakMap,rS=new WeakMap,nS=new WeakMap,aS=new WeakMap,oS=new WeakMap,lS=new WeakMap,hS=new WeakMap,dS=new WeakMap,eS=new WeakSet,cS=function(){var e;if("disposed"===Zy(this,sS,"f"))return;Jy(this,sS,"reconnecting","f");const t=Math.min(Zy(this,tS,"f").initialDelay*Math.pow(2,Zy(this,rS,"f")),Zy(this,tS,"f").maxDelay),s=t*Zy(this,tS,"f").jitterMultiplier,i=2*Math.random()*s-s,r=Math.max(0,t+i);t<Zy(this,tS,"f").maxDelay&&Jy(this,rS,(e=Zy(this,rS,"f"),++e),"f"),Jy(this,nS,setTimeout(()=>{"disposed"!==Zy(this,sS,"f")&&this.connect()},r),"f"),Zy(this,aS,"f").dispatchEvent("reconnecting")},uS=function(){null!==Zy(this,nS,"f")&&(clearTimeout(Zy(this,nS,"f")),Jy(this,nS,null,"f"))}}}),tE=o({"../../node_modules/p2p-media-loader-core/lib/webtorrent/webtorrent-socket-pool/index.js"(){eE(),Qm(),gS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},vS=class{constructor(){mS.set(this,new Map),pS.set(this,new Fm)}addEventListener(e,t){gS(this,pS,"f").addEventListener(e,t)}removeEventListener(e,t){gS(this,pS,"f").removeEventListener(e,t)}acquire(e){let t=gS(this,mS,"f").get(e);if(!t){const s=new fS({url:e});s.addEventListener("error",t=>{gS(this,pS,"f").dispatchEvent("error",t,e)}),s.connect(),t={client:s,refCount:0},gS(this,mS,"f").set(e,t)}t.refCount++;let s=!1;return{client:t.client,release:()=>{!s&&(s=!0,t.refCount--,t.refCount<=0)&&(t.refCount<0&&console.error(`[WebTorrentSocketPool] Negative refCount detected for ${e}`),gS(this,mS,"f").get(e)===t&&gS(this,mS,"f").delete(e),t.client.dispose())}}}destroy(){gS(this,pS,"f").clear();const e=Array.from(gS(this,mS,"f").values());gS(this,mS,"f").clear();for(const t of e)try{t.client.dispose()}catch(e){console.error("[WebTorrentSocketPool] Failed to dispose WebSocketClient:",e)}}},mS=new WeakMap,pS=new WeakMap}}),sE=o({"../../node_modules/p2p-media-loader-core/lib/core.js"(){XS(),yS=d(Cf(),1),mv(),Ym(),ZS(),Qm(),zf(),ty(),tE(),SS=function(e,t,s,i){return new(s||(s=Promise))(function(r,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(a,o)}l((i=i.apply(e,t||[])).next())})},ES=class e{constructor(t){Object.defineProperty(this,"eventTarget",{enumerable:!0,configurable:!0,writable:!0,value:new Fm}),Object.defineProperty(this,"manifestResponseUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streams",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"mainStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"commonCoreConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"bandwidthCalculators",{enumerable:!0,configurable:!0,writable:!0,value:{all:new om,http:new om}}),Object.defineProperty(this,"segmentStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webTorrentSocketPool",{enumerable:!0,configurable:!0,writable:!0,value:new vS}),Object.defineProperty(this,"socketPoolLogger",{enumerable:!0,configurable:!0,writable:!0,value:(0,yS.default)("p2pml-core:webtorrent-socket-pool")}),Object.defineProperty(this,"peerId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mainStreamLoader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secondaryStreamLoader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamDetails",{enumerable:!0,configurable:!0,writable:!0,value:{isLive:!1,activeLevelBitrate:0}}),Object.defineProperty(this,"storageInitPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const s=function e(t){if(xf(t)){const s={};return Object.keys(t).forEach(i=>{if(void 0!==t[i]){const r=e(t[i]);void 0!==r&&(s[i]=r)}}),s}return t}(null!=t?t:{});this.commonCoreConfig=Uf({defaultConfig:e.DEFAULT_COMMON_CORE_CONFIG,baseConfig:s}),this.mainStreamConfig=Uf({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.mainStream}),this.secondaryStreamConfig=Uf({defaultConfig:e.DEFAULT_STREAM_CONFIG,baseConfig:s,specificStreamConfig:s.secondaryStream}),this.peerId=function(e){const t=[e],s=gv-e.length;for(let e=0;e<s;e++)t.push(fv[Math.floor(Math.random()*fv.length)]);return t.join("")}(this.commonCoreConfig.trackerClientVersionPrefix),this.webTorrentSocketPool.addEventListener("error",(e,t)=>{this.socketPoolLogger(`WebSocket error for tracker url ${t}:`,e)})}getConfig(){return Object.assign(Object.assign({},Ff(this.commonCoreConfig)),{mainStream:Ff(this.mainStreamConfig),secondaryStream:Ff(this.secondaryStreamConfig)})}applyDynamicConfig(e){const{mainStream:t,secondaryStream:s}=e,i=Ff(this.mainStreamConfig),r=Ff(this.secondaryStreamConfig);this.overrideAllConfigs(e,t,s),this.processSpecificDynamicConfigParams(i,e,"main"),this.processSpecificDynamicConfigParams(r,e,"secondary")}processSpecificDynamicConfigParams(e,t,s){const i=this.getUpdatedStreamProperty("isP2PDisabled",t,s);i&&e.isP2PDisabled!==i&&this.destroyStreamLoader(s);const r=this.getUpdatedStreamProperty("isP2PUploadDisabled",t,s);if(void 0!==r&&e.isP2PUploadDisabled!==r){const e="main"===s?this.mainStreamLoader:this.secondaryStreamLoader;null==e||e.sendBroadcastAnnouncement(r)}}getUpdatedStreamProperty(e,t,s){var i;const r="main"===s?t.mainStream:t.secondaryStream;return null!==(i=null==r?void 0:r[e])&&void 0!==i?i:t[e]}addEventListener(e,t){this.eventTarget.addEventListener(e,t)}removeEventListener(e,t){this.eventTarget.removeEventListener(e,t)}setManifestResponseUrl(e){this.manifestResponseUrl=e.split("?")[0]}hasSegment(e){return!!lv(this.streams,e)}getStream(e){return this.streams.get(e)}addStreamIfNoneExists(e){this.streams.has(e.runtimeId)||this.streams.set(e.runtimeId,Object.assign(Object.assign({},e),{segments:new Map}))}updateStream(e,t,s){var i,r;const n=this.streams.get(e);if(n){if(t)for(const e of t)n.segments.has(e.runtimeId)||n.segments.set(e.runtimeId,Object.assign(Object.assign({},e),{stream:n}));if(s)for(const e of s)n.segments.delete(e);null===(i=this.mainStreamLoader)||void 0===i||i.updateStream(n),null===(r=this.secondaryStreamLoader)||void 0===r||r.updateStream(n)}}loadSegment(e,t){return SS(this,void 0,void 0,function*(){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");yield this.initializeSegmentStorage();const s=this.identifySegment(e);this.getStreamHybridLoader(s).loadSegment(s,t)})}abortSegmentLoading(e){var t,s;null===(t=this.mainStreamLoader)||void 0===t||t.abortSegmentRequest(e),null===(s=this.secondaryStreamLoader)||void 0===s||s.abortSegmentRequest(e)}updatePlayback(e,t){var s,i;null===(s=this.mainStreamLoader)||void 0===s||s.updatePlayback(e,t),null===(i=this.secondaryStreamLoader)||void 0===i||i.updatePlayback(e,t)}setActiveLevelBitrate(e){var t,s;e!==this.streamDetails.activeLevelBitrate&&(this.streamDetails.activeLevelBitrate=e,null===(t=this.mainStreamLoader)||void 0===t||t.notifyLevelChanged(),null===(s=this.secondaryStreamLoader)||void 0===s||s.notifyLevelChanged())}setIsLive(e){this.streamDetails.isLive=e}isSegmentLoadable(e){try{const t=this.identifySegment(e);return!("main"===t.stream.type&&this.mainStreamConfig.isP2PDisabled||"secondary"===t.stream.type&&this.secondaryStreamConfig.isP2PDisabled)}catch(e){return!1}}destroy(){var e,t,s,i;this.streams.clear(),null===(e=this.mainStreamLoader)||void 0===e||e.destroy(),null===(t=this.secondaryStreamLoader)||void 0===t||t.destroy(),null===(s=this.segmentStorage)||void 0===s||s.setSegmentChangeCallback(void 0),null===(i=this.segmentStorage)||void 0===i||i.destroy(),this.mainStreamLoader=void 0,this.secondaryStreamLoader=void 0,this.segmentStorage=void 0,this.manifestResponseUrl=void 0,this.streamDetails={isLive:!1,activeLevelBitrate:0},this.storageInitPromise=void 0,this.webTorrentSocketPool.destroy()}initializeSegmentStorage(){return SS(this,void 0,void 0,function*(){if(!this.segmentStorage){if(this.storageInitPromise)return this.storageInitPromise;this.storageInitPromise=(()=>SS(this,void 0,void 0,function*(){const{isLive:e}=this.streamDetails,t=this.commonCoreConfig.customSegmentStorageFactory;if(t&&"function"!=typeof t)throw new Error("Storage configuration is invalid");const s=t?t(e):new Xy;try{yield s.initialize(this.commonCoreConfig,this.mainStreamConfig,this.secondaryStreamConfig)}catch(e){throw s.destroy(),e}if(!this.storageInitPromise)return s.setSegmentChangeCallback(void 0),void s.destroy();s.setSegmentChangeCallback(e=>{this.eventTarget.dispatchEvent(`onStorageUpdated-${e}`)}),this.segmentStorage=s}))();try{yield this.storageInitPromise}finally{this.storageInitPromise=void 0}}})}identifySegment(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is undefined");const t=lv(this.streams,e);if(!t)throw new Error(`Not found segment with id: ${e}`);return t}overrideAllConfigs(e,t,s){Bf(this.commonCoreConfig,e),Bf(this.mainStreamConfig,e),Bf(this.secondaryStreamConfig,e),t&&Bf(this.mainStreamConfig,t),s&&Bf(this.secondaryStreamConfig,s)}destroyStreamLoader(e){var t,s;"main"===e?(null===(t=this.mainStreamLoader)||void 0===t||t.destroy(),this.mainStreamLoader=void 0):(null===(s=this.secondaryStreamLoader)||void 0===s||s.destroy(),this.secondaryStreamLoader=void 0)}getStreamHybridLoader(e){var t,s;return"main"===e.stream.type?(null!==(t=this.mainStreamLoader)&&void 0!==t||(this.mainStreamLoader=this.createNewHybridLoader(e)),this.mainStreamLoader):(null!==(s=this.secondaryStreamLoader)&&void 0!==s||(this.secondaryStreamLoader=this.createNewHybridLoader(e)),this.secondaryStreamLoader)}createNewHybridLoader(e){if(!this.manifestResponseUrl)throw new Error("Manifest response url is not defined");if(!this.segmentStorage)throw new Error("Segment storage is not initialized");const t="main"===e.stream.type?this.mainStreamConfig:this.secondaryStreamConfig;return new Wy(this.manifestResponseUrl,e,this.streamDetails,t,this.bandwidthCalculators,this.segmentStorage,this.webTorrentSocketPool,this.eventTarget,this.peerId)}},Object.defineProperty(ES,"DEFAULT_COMMON_CORE_CONFIG",{enumerable:!0,configurable:!0,writable:!0,value:{segmentMemoryStorageLimit:void 0,customSegmentStorageFactory:void 0,trackerClientVersionPrefix:uv}}),Object.defineProperty(ES,"DEFAULT_STREAM_CONFIG",{enumerable:!0,configurable:!0,writable:!0,value:{isP2PUploadDisabled:!1,isP2PDisabled:!1,simultaneousHttpDownloads:2,simultaneousP2PDownloads:3,preferP2PForEngineRequest:!1,highDemandTimeWindow:15,httpDownloadInitialTimeoutMs:0,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,webRtcMaxMessageSize:65535,p2pNotReceivingBytesTimeoutMs:2e3,p2pInactiveLoaderDestroyTimeoutMs:3e4,httpNotReceivingBytesTimeoutMs:3e3,httpErrorRetries:3,p2pErrorRetries:3,announceTrackers:["wss://tracker.novage.com.ua","wss://tracker.openwebtorrent.com"],rtcConfig:{iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478"}]},validateP2PSegment:void 0,validateHTTPSegment:void 0,httpRequestSetup:void 0,swarmId:void 0,p2pMaxPeers:50,p2pChurnMaxPeersMultiplier:1.5,p2pChurnCleanupIntervalMs:3e4,p2pChurnGracePeriodMs:15e3,webRtcOffersCount:5,webRtcOfferTimeoutMs:5e4,webRtcIceGatheringTimeoutMs:5e3,webRtcConnectionTimeoutMs:15e3}})}}),iE=o({"../../node_modules/p2p-media-loader-core/lib/index.js"(){sE(),If(),mv(),bS=d(Cf(),1)}}),rE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/fragment-loader.js"(){wf(),iE(),TS=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},wS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},_S=class{constructor(e,t){IS.add(this),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),LS.set(this,void 0),AS.set(this,void 0),kS.set(this,void 0),RS.set(this,void 0),CS.set(this,void 0),PS.set(this,void 0),TS(this,RS,t,"f"),TS(this,AS,()=>new e.loader(e),"f"),this.stats={aborted:!1,chunkCount:0,loading:{start:0,first:0,end:0},buffering:{start:0,first:0,end:0},parsing:{start:0,end:0},total:1,loaded:1,bwEstimate:0,retry:0}}load(e,t,s){this.context=e,this.config=t,TS(this,LS,s,"f");const{stats:i}=this,{rangeStart:r,rangeEnd:n}=e,a=rf(r,void 0!==n?n-1:void 0);TS(this,PS,sf(e.url,a),"f");const o=wS(this,RS,"f").isSegmentLoadable(wS(this,PS,"f"));if(!wS(this,RS,"f").hasSegment(wS(this,PS,"f"))||!o)return TS(this,kS,wS(this,AS,"f").call(this),"f"),wS(this,kS,"f").stats=this.stats,void wS(this,kS,"f").load(e,t,s);wS(this,RS,"f").loadSegment(wS(this,PS,"f"),{onSuccess:t=>{if(!wS(this,LS,"f"))return;TS(this,CS,t,"f");const s=wS(this,CS,"f").data.byteLength;i.loading=function(e,t,s){const i=e>0?8e3*t/e:0,r=Math.max(0,s-i);return{start:Math.max(0,r-10),first:r,end:s}}(wS(this,CS,"f").bandwidth,s,performance.now()),i.total=s,i.loaded=s;const r=wS(this,CS,"f").data.slice(0);wS(this,LS,"f").onProgress&&wS(this,LS,"f").onProgress(this.stats,e,r,void 0),wS(this,LS,"f").onSuccess({data:r,url:e.url},this.stats,e,void 0)},onError:e=>{e instanceof uf&&"aborted"===e.type&&this.stats.aborted||wS(this,IS,"m",DS).call(this,e)}})}abort(){var e,t;wS(this,kS,"f")?wS(this,kS,"f").abort():(wS(this,IS,"m",MS).call(this),null===(t=null===(e=wS(this,LS,"f"))||void 0===e?void 0:e.onAbort)||void 0===t||t.call(e,this.stats,this.context,{}))}destroy(){wS(this,kS,"f")?wS(this,kS,"f").destroy():(this.stats.aborted||wS(this,IS,"m",MS).call(this),TS(this,LS,null,"f"),this.config=null)}},LS=new WeakMap,AS=new WeakMap,kS=new WeakMap,RS=new WeakMap,CS=new WeakMap,PS=new WeakMap,IS=new WeakSet,DS=function(e){var t;const s={code:0,text:""};(e instanceof uf&&"failed"===e.type||e instanceof Error)&&(s.text=e.message),null===(t=wS(this,LS,"f"))||void 0===t||t.onError(s,this.context,null,this.stats)},MS=function(){!wS(this,CS,"f")&&wS(this,PS,"f")&&(this.stats.aborted=!0,wS(this,RS,"f").abortSegmentLoading(wS(this,PS,"f")))}}}),nE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/playlist-loader.js"(){OS=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},xS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},BS=class{constructor(e){FS.set(this,void 0),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),OS(this,FS,new e.loader(e),"f"),this.stats=xS(this,FS,"f").stats,this.context=xS(this,FS,"f").context}load(e,t,s){xS(this,FS,"f").load(e,t,s)}abort(){xS(this,FS,"f").abort()}destroy(){xS(this,FS,"f").destroy()}},FS=new WeakMap}}),aE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/segment-manager.js"(){wf(),iE(),US=class{constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.core=e}processMainManifest(e){const{levels:t,audioTracks:s}=e;for(const e of t){const{url:t,bitrate:s,maxBitrate:i,videoCodec:r,width:n,height:a}=e,o=null!=i?i:s,l=0===o,h=e.attrs["FRAME-RATE"],d=e.attrs["VIDEO-RANGE"],c=av({bitrate:o,codecs:l?void 0:r,width:l?void 0:n,height:l?void 0:a,frameRate:l?void 0:h,videoRange:l?void 0:d});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:"main",index:c})}for(const e of s){const{url:t,audioCodec:s,lang:i,channels:r,name:n}=e,a=av({bitrate:0,codecs:s,language:i,channels:r,name:n});this.core.addStreamIfNoneExists({runtimeId:Array.isArray(t)?t[0]:t,type:"secondary",index:a})}}updatePlaylist(e){const{details:{url:t,fragments:s,live:i}}=e,r=this.core.getStream(t);if(!r)return;const n=new Set(r.segments.keys()),a=[];s.forEach((e,t)=>{const{url:s,byteRange:o,sn:l,start:h,end:d}=e,[c,u]=o,f=rf(c,void 0!==u?u-1:void 0),g=sf(s,f);n.delete(g),r.segments.has(g)||a.push({runtimeId:g,url:s,externalId:i?l:t,byteRange:f,startTime:h,endTime:d})}),(a.length||n.size)&&this.core.updateStream(t,a,n.values())}}}}),oE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/engine-static.js"(){lE(),NS=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},$S=function(e,t,s,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,s):r?r.value=s:t.set(e,s),s},GS=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]])}return s}}}),lE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/engine.js"(){rE(),nE(),aE(),iE(),oE(),HS=class{static injectMixin(e){return t=e,i=class extends t{get p2pEngine(){return NS(this,s,"f")}constructor(...e){var t;const i=e[0],r=null!=i?i:{},{p2p:n}=r,a=GS(r,["p2p"]),o=new HS(n);super(Object.assign(Object.assign({},a),o.getConfigForHlsJs())),s.set(this,void 0),o.bindHls(this),$S(this,s,o,"f"),null===(t=null==n?void 0:n.onHlsJsCreated)||void 0===t||t.call(n,this)}},s=new WeakMap,i;var t,s,i}constructor(e){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"segmentManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hlsInstanceGetter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentHlsInstance",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:(0,bS.default)("p2pml-hlsjs:engine")}),Object.defineProperty(this,"updateMediaElementEventHandlers",{enumerable:!0,configurable:!0,writable:!0,value:e=>{var t;const s=null===(t=this.currentHlsInstance)||void 0===t?void 0:t.media;if(!s)return;const i="register"===e?"addEventListener":"removeEventListener";s[i]("timeupdate",this.handlePlaybackUpdate),s[i]("seeking",this.handlePlaybackUpdate),s[i]("ratechange",this.handlePlaybackUpdate)}}),Object.defineProperty(this,"handleManifestLoaded",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{const s=t.networkDetails;s instanceof XMLHttpRequest?this.core.setManifestResponseUrl(s.responseURL):s instanceof Response&&this.core.setManifestResponseUrl(s.url),this.segmentManager.processMainManifest(t)}}),Object.defineProperty(this,"handleLevelSwitching",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{t.bitrate&&this.core.setActiveLevelBitrate(t.bitrate)}}),Object.defineProperty(this,"handleLevelUpdated",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{this.currentHlsInstance&&"main"===t.details.fragments[0].type&&t.details.fragments.length>4&&(!t.details.live||this.currentHlsInstance.userConfig.liveSyncDuration||this.currentHlsInstance.userConfig.liveSyncDurationCount||this.updateLiveSyncDurationCount(t),this.currentHlsInstance.userConfig.maxBufferLength||this.currentHlsInstance.userConfig.maxMaxBufferLength||this.updateMaxBufferLength(t.details.targetduration)),this.core.setIsLive(t.details.live),this.segmentManager.updatePlaylist(t)}}),Object.defineProperty(this,"handleMediaAttached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("register")}}),Object.defineProperty(this,"handleMediaDetached",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.updateMediaElementEventHandlers("unregister")}}),Object.defineProperty(this,"handlePlaybackUpdate",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=e.target;this.core.updatePlayback(t.currentTime,t.playbackRate)}}),Object.defineProperty(this,"destroyCore",{enumerable:!0,configurable:!0,writable:!0,value:()=>this.core.destroy()}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyCore(),this.updateHlsEventsHandlers("unregister"),this.updateMediaElementEventHandlers("unregister"),this.currentHlsInstance=void 0}}),this.core=new ES(null==e?void 0:e.core),this.segmentManager=new US(this.core)}addEventListener(e,t){this.core.addEventListener(e,t)}removeEventListener(e,t){this.core.removeEventListener(e,t)}getConfigForHlsJs(){return{fLoader:this.createFragmentLoaderClass(),pLoader:this.createPlaylistLoaderClass()}}getConfig(){return{core:this.core.getConfig()}}applyDynamicConfig(e){e.core&&this.core.applyDynamicConfig(e.core)}bindHls(e){this.hlsInstanceGetter="function"==typeof e?e:()=>e}initHlsEvents(){var e;const t=null===(e=this.hlsInstanceGetter)||void 0===e?void 0:e.call(this);this.currentHlsInstance!==t&&(this.currentHlsInstance&&this.destroy(),this.currentHlsInstance=t,this.updateHlsEventsHandlers("register"),this.updateMediaElementEventHandlers("register"))}updateHlsEventsHandlers(e){const t=this.currentHlsInstance;if(!t)return;const s="register"===e?"on":"off";t[s]("hlsManifestLoaded",this.handleManifestLoaded),t[s]("hlsLevelSwitching",this.handleLevelSwitching),t[s]("hlsLevelUpdated",this.handleLevelUpdated),t[s]("hlsAudioTrackLoaded",this.handleLevelUpdated),t[s]("hlsDestroying",this.destroy),t[s]("hlsMediaAttaching",this.destroyCore),t[s]("hlsManifestLoading",this.destroyCore),t[s]("hlsMediaDetached",this.handleMediaDetached),t[s]("hlsMediaAttached",this.handleMediaAttached)}updateLiveSyncDurationCount(e){const t=e.details.targetduration,s=Math.floor(120/t),i=Math.min(e.details.fragments.length-1,s);this.currentHlsInstance&&this.currentHlsInstance.config.liveSyncDurationCount!==i&&(this.debug(`Setting liveSyncDurationCount to ${i}`),this.currentHlsInstance.config.liveSyncDurationCount=i)}updateMaxBufferLength(e){if(!this.currentHlsInstance)return;const t=this.core.getConfig(),s=Math.max(t.mainStream.highDemandTimeWindow,t.secondaryStream.highDemandTimeWindow),i=Math.max(2*e,s);this.currentHlsInstance.config.maxBufferLength>i&&(this.debug(`Setting maxBufferLength to ${i}`),this.currentHlsInstance.config.maxBufferLength=i),this.currentHlsInstance.config.maxMaxBufferLength>i&&(this.debug(`Setting maxMaxBufferLength to ${i}`),this.currentHlsInstance.config.maxMaxBufferLength=i)}createFragmentLoaderClass(){const{core:e}=this,t=this;return class extends _S{constructor(t){super(t,e)}static getEngine(){return t}}}createPlaylistLoaderClass(){const e=this;return class extends BS{constructor(t){super(t),e.initHlsEvents()}}}}}}),hE=o({"../../node_modules/p2p-media-loader-hlsjs/lib/index.js"(){lE()}}),dE=o({"src/logging.ts"(){WS={none:0,error:1,warn:2,info:3,debug:4},qS=0,jS=class{constructor(e="none"){this.level=e}level;clientId=++qS;repeats=new Map;log(e,t,s){if(!((WS[this.level]??0)<WS[e]))try{let i=0;if("error"===e||"warn"===e){const e=performance.now(),s=this.repeats.get(t);if(s&&e-s.at<5e3)return void s.suppressed++;i=s?.suppressed??0,this.repeats.size>=32&&!s&&this.repeats.delete(this.repeats.keys().next().value),this.repeats.set(t,{at:e,suppressed:0})}const r=function(e){return e.replace(/(?:https?|wss?):\/\/[^\s"'<>]+/gi,e=>{try{const t=new URL(e);return t.username="",t.password="",t.search="",t.hash="",["localhost","127.0.0.1","[::1]"].includes(t.hostname)&&(t.pathname="/[proxy]"),t.toString()}catch{return"[redacted-url]"}}).replace(/\/[^\s/?]+\/fetch\/[^\s]*/g,"/[proxy]").replace(/\b(authorization|proxy-authorization|sdk[_-]?key|session[_-]?token|access[_-]?token|refresh[_-]?token|token|key)["']?\s*[:=]\s*(?:(?:Bearer|Basic)\s+)?(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)/gi,"$1=[redacted]").replace(/\b(?:Bearer|Basic)\s+[^\s,"';}]+/gi,"[redacted-authorization]").replace(/\bkey_[A-Za-z0-9_-]+/g,"[redacted-key]").replace(/[\x00-\x1f\x7f]/g," ").slice(0,4096)}(s());console[e](`[MeshStream web-${this.clientId}] ${r}${i?` suppressed=${i}`:""}`)}catch{}}}}}),cE={};function uE(e,t){var s;t&&(s=e.userConfig,!Boolean(void 0!==s?.liveSyncDuration||void 0!==s?.liveSyncDurationCount||void 0!==s?.liveMaxLatencyDuration||void 0!==s?.liveMaxLatencyDurationCount))&&(e.config.liveSyncDurationCount=VS,e.config.liveMaxLatencyDurationCount=YS)}function fE(e,t,s=KS.liveSeedCohortCount){const i=Number.isFinite(s)?Math.max(1,Math.floor(s)):KS.liveSeedCohortCount;return function(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}(`${t}${e}`)%i===0}function gE({livePeerSchedulingActive:e,peerHasSegment:t,p2pSlotsAvailable:s,previousP2pFailures:i}){return e&&t&&s&&Number.isFinite(i)&&0===i}function mE(e,t){return void 0!==e&&Number.isFinite(e)?Math.max(0,Math.floor(e)):t}function pE(e){if(null!=e&&Number.isFinite(e)&&!(e<0))return Math.round(1e3*e)}function vE(e){if(e instanceof Error)return e.message.slice(0,200);if("string"==typeof e)return e.slice(0,200);try{return JSON.stringify(e).slice(0,200)}catch{return String(e).slice(0,200)}}function yE(e){try{e()}catch{}}h(cE,{DEFAULT_P2P_STRATEGY:()=>KS,HlsP2pClient:()=>zS,applyDefaultHlsLiveLatencyPolicy:()=>uE,isLiveSeedCohort:()=>fE,shouldUsePeerForLiveHttpRequest:()=>gE});var SE=o({"src/hls.ts"(){hE(),re(),w(),J(),Mt(),Z(),dE(),E(),W(),KS=Object.freeze({uploadSlots:4,downloadSlots:5,simultaneousP2PDownloads:3,httpDownloadInitialTimeoutMs:0,highDemandTimeWindow:15,httpDownloadTimeWindow:3e3,p2pDownloadTimeWindow:6e3,peerHighDemandTimeWindow:6,peerHttpDownloadTimeWindow:3e3,peerP2pDownloadTimeWindow:12e3,livePeerHighDemandTimeWindow:2,livePeerHttpDownloadTimeWindow:4,liveSeedCohortCount:4,liveSeedHttpDownloadTimeWindow:6,maxMessageSizeBytes:16384,p2pNotReceivingBytesTimeoutMs:2e3,webRtcConnectionTimeoutMs:15e3}),VS=4,YS=8,zS=class{logger;engine;hlsjsInstance;engineConfig;trackerCandidates;activeTrackerIndex=0;failoverInFlight=!1;disposed=!1;engineGeneration=0;swarmId;streamUrl;contentId;appId;keyId;uploadSlots;downloadSlots;reportIntervalMs;capability;reportUrl;sessionId;sessionTokenManager;startedAtMs=performance.now();listeners=new Map;eventListeners=new Set;activePeers=new Set;pagehideHandler=()=>{this.reportStats()};reportTimer;reportInFlight=!1;pendingFinalReport;hasReportedContext=!1;eventTimer;p2pEnabled;p2pReady=!1;peerWindowProfile="baseline";playbackIsLive;liveSeedCohort;hlsLivePlaylistHandler=(e,t)=>{"boolean"==typeof t.details?.live&&(this.playbackIsLive=t.details.live,uE(this.hlsjsInstance,t.details.live),this.applyPeerOptimizedWindows(this.activePeers.size>0))};stats={httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0};diagnosticState={fallbackCount:0,coldStart:{p2pDownloaded:0,httpDownloaded:0},ice:{attempts:0,successes:0,failures:0,durationMs:0}};static isSupported(){return"undefined"!=typeof RTCPeerConnection&&"undefined"!=typeof WebSocket}constructor(e){this.logger=new jS(e.logLevel),this.hlsjsInstance=e.hlsjsInstance,this.streamUrl=e.streamUrl,this.contentId=e.contentId?.trim()||void 0,this.appId=e.sdkConfig?.applicationId?.trim()||e.appId?.trim()||void 0,this.keyId=e.sdkConfig?.keyId?.trim()||void 0,this.sessionId=e.sessionId?.trim()||`web-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`,this.p2pEnabled=!1!==e.p2pEnabled,this.uploadSlots=mE(e.uploadSlots,KS.uploadSlots),this.downloadSlots=mE(e.downloadSlots,KS.downloadSlots),this.reportIntervalMs=j(e.sdkConfig?.defaults?.reportIntervalMs),this.capability=e.capability,this.sessionTokenManager=e.sessionTokenManager;const t=e.contentId?.trim()?D(e.contentId):P(e.streamUrl),s=e.sdkConfig?.defaults?.swarmBucketCount??1,i=e.sdkConfig?.defaults?.swarmBucketId??O(this.sessionId,s);this.swarmId=x(t,s,i),this.liveSeedCohort=fE(this.sessionId,this.swarmId),this.diagnosticState.playbackAuth=b(e.streamUrl,e.sdkConfig?.playbackAuth);const r=e.sdkConfig?.trackerUrls?.length?e.sdkConfig.trackerUrls:e.trackerUrls,n=I(e.trackerUrl,r,this.appId,this.swarmId,this.keyId,e.sdkConfig?.primaryTrackerUrl,{liveWindowBucket:e.liveWindowBucket?.trim()||"auto"});this.trackerCandidates=n;const a=n[0],o=u(e.originHeaders,e.originHeadersProvider,e.streamUrl);this.reportUrl=k(C(e.sdkConfig?.reportUrl,{appId:this.appId,keyId:this.keyId}))||k(R(a))||C(e.sdkConfig?.reportUrl,{appId:this.appId,keyId:this.keyId})||R(a),this.engineConfig={core:{httpRequestSetup:o,...a?{announceTrackers:[a]}:{},rtcConfig:{iceServers:e.iceServers??(e.sdkConfig?.iceServers?.length?[{urls:e.sdkConfig.iceServers}]:ee())},swarmId:this.swarmId,isP2PDisabled:!1===e.p2pEnabled,simultaneousP2PDownloads:KS.simultaneousP2PDownloads,httpDownloadInitialTimeoutMs:mE(e.httpDownloadInitialTimeoutMs,KS.httpDownloadInitialTimeoutMs),highDemandTimeWindow:KS.highDemandTimeWindow,httpDownloadTimeWindow:KS.httpDownloadTimeWindow,p2pDownloadTimeWindow:KS.p2pDownloadTimeWindow,preferP2PForEngineRequest:!0,webRtcMaxMessageSize:KS.maxMessageSizeBytes,p2pNotReceivingBytesTimeoutMs:KS.p2pNotReceivingBytesTimeoutMs,webRtcConnectionTimeoutMs:KS.webRtcConnectionTimeoutMs,customSegmentStorageFactory:ne}},this.engine=this.createEngine(a),this.engine.bindHls(this.hlsjsInstance),Object.assign(this.hlsjsInstance.config,this.engine.getConfigForHlsJs()),this.hlsjsInstance.on?.("hlsLevelLoaded",this.hlsLivePlaylistHandler);const l=this.hlsjsInstance.latestLevelDetails;l&&(this.playbackIsLive=l.live,uE(this.hlsjsInstance,l.live)),this.bindEvents(),this.logger.log("info","initialized",()=>"HLS P2P client initialized"),window.addEventListener("pagehide",this.pagehideHandler),this.startStatsReporting()}on(e,t){const s=this.listeners.get(e)??new Set;s.add(t),this.listeners.set(e,s)}off(e,t){this.listeners.get(e)?.delete(t)}addEventListener(e){this.eventListeners.add(e),yE(()=>e.onPlaybackStateChanged?.(this.p2pEnabled&&this.p2pReady?"p2p-ready":this.p2pEnabled?"connecting":"cdn-fallback")),void 0===this.eventTimer&&(this.eventTimer=window.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)yE(()=>t.onStatistics?.(e))},1e3))}removeEventListener(e){this.eventListeners.delete(e),0===this.eventListeners.size&&void 0!==this.eventTimer&&(window.clearInterval(this.eventTimer),this.eventTimer=void 0)}setP2pEnabled(e){this.p2pEnabled=e,this.engine.applyDynamicConfig({core:{isP2PDisabled:!e}}),!e&&this.p2pReady&&(this.p2pReady=!1,this.notify(e=>e.onP2pUnavailable?.("DISABLED")),this.notifyPlaybackState("cdn-fallback"))}statistics(){return{...this.stats}}diagnostics(){const e=this.currentLiveLatency(),t=this.diagnosticState.liveLatency;return{...this.diagnosticState,...this.diagnosticState.coldStart?{coldStart:{...this.diagnosticState.coldStart}}:{},...t?{liveLatency:{...t,...e||{}}}:{}}}dispose(){this.disposed=!0,void 0!==this.reportTimer&&window.clearInterval(this.reportTimer),void 0!==this.eventTimer&&window.clearInterval(this.eventTimer),window.removeEventListener("pagehide",this.pagehideHandler),this.hlsjsInstance.off?.("hlsLevelLoaded",this.hlsLivePlaylistHandler),this.reportTimer=void 0,this.eventTimer=void 0,this.reportStats(this.statistics(),!0).catch(()=>{}),this.engine.destroy(),this.listeners.clear(),this.eventListeners.clear()}getHlsConfig(){return this.engine.getConfigForHlsJs()}activateExistingHls(){const e=this.engine;e.initHlsEvents?.()}emit(e,t){for(const s of this.listeners.get(e)??[])s(t)}bindEvents(){const e=this.engine,t=this.engineGeneration;e.addEventListener("onPeerConnect",e=>{t===this.engineGeneration&&(this.activePeers.add(e.peerId),this.logger.log("info","peer-connected",()=>`peer connected peers=${this.activePeers.size}`),this.diagnosticState.ice&&(this.diagnosticState.ice.attempts+=1,this.diagnosticState.ice.successes+=1),this.stats.connectedPeers=this.activePeers.size,this.applyPeerOptimizedWindows(!0),void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.firstPeerConnectMs=Math.round(performance.now()-this.startedAtMs)),this.emit("peer-connect",e),this.notify(e=>e.onPeerCountChanged?.(this.stats.connectedPeers)),!this.p2pReady&&this.p2pEnabled&&(this.p2pReady=!0,this.notify(e=>e.onP2pReady?.()),this.notifyPlaybackState("p2p-ready")))}),e.addEventListener("onPeerClose",e=>{t===this.engineGeneration&&(this.activePeers.delete(e.peerId),this.logger.log("info","peer-closed",()=>`peer closed peers=${this.activePeers.size}`),this.stats.connectedPeers=this.activePeers.size,0===this.activePeers.size&&this.applyPeerOptimizedWindows(!1),this.emit("peer-close",e),this.notify(e=>e.onPeerCountChanged?.(this.stats.connectedPeers)),this.p2pReady&&0===this.stats.connectedPeers&&(this.p2pReady=!1,this.notify(e=>e.onP2pUnavailable?.(this.p2pEnabled?"NO_PEERS":"DISABLED")),this.notifyPlaybackState("cdn-fallback")))}),e.addEventListener("onPeerConnectError",e=>{t===this.engineGeneration&&(this.stats.peerConnectErrors+=1,this.logger.log("error","peer-connect-error",()=>`peer connection failed total=${this.stats.peerConnectErrors}`),this.diagnosticState.ice&&(this.diagnosticState.ice.attempts+=1,this.diagnosticState.ice.failures+=1),this.diagnosticState.lastPeerError=vE(e),this.diagnosticState.lastErrorAtMs=Date.now(),this.emit("segment-error",e),this.notify(e=>e.onPeerConnectError?.(this.stats.peerConnectErrors)))}),e.addEventListener("onTrackerError",e=>{t===this.engineGeneration&&(this.stats.trackerErrors+=1,this.logger.log("error","tracker-error",()=>`tracker connection failed total=${this.stats.trackerErrors}`),this.diagnosticState.lastTrackerError=vE(e),this.diagnosticState.lastErrorAtMs=Date.now(),this.emit("tracker-error",e),this.notify(e=>e.onTrackerError?.(this.stats.trackerErrors)),this.failoverTracker(e.trackerUrl))}),e.addEventListener("onSegmentError",e=>{t===this.engineGeneration&&(this.logger.log("error","segment-error",()=>"segment request failed"),this.emit("segment-error",e))}),e.addEventListener("onChunkDownloaded",(e,s,i)=>{t===this.engineGeneration&&("p2p"===s?(this.stats.p2pDownloaded+=e,void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.coldStart.p2pDownloaded+=e),this.emit("p2p-download",{bytes:e,peerId:i})):(this.stats.httpDownloaded+=e,void 0===this.diagnosticState.firstPeerConnectMs&&(this.diagnosticState.coldStart.httpDownloaded+=e),0===this.activePeers.size&&(this.diagnosticState.fallbackCount+=1),this.emit("http-download",{bytes:e}),0!==this.activePeers.size&&0!==this.stats.p2pDownloaded||this.notify(t=>t.onCdnFallback?.(e))))}),e.addEventListener("onChunkUploaded",(e,s)=>{t===this.engineGeneration&&(this.stats.p2pUploaded+=e,this.emit("p2p-upload",{bytes:e,peerId:s}))})}createEngine(e){const t=this.engineConfig.core??{},s=new HS({...this.engineConfig,core:{...t,...e?{announceTrackers:[e]}:{}}});return function(e,t){const s=e.core,i=s?.createNewHybridLoader;s&&"function"==typeof i&&(s.createNewHybridLoader=function(e){const s=i.call(this,e),r=s.loadThroughHttp,n=s.loadThroughP2P;return"function"!=typeof r||"function"!=typeof n||(s.loadThroughHttp=e=>{const i=s.p2pLoaders?.currentLoader,a=s.requests?.get?.(e),o=a?.failedAttempts?.p2pAttemptsCount??0,l=s.requests?.executingP2PCount,h=s.config?.simultaneousP2PDownloads,d="number"==typeof l&&"number"==typeof h&&l<h,c=!0===i?.isSegmentLoadedBySomeone?.(e);gE({livePeerSchedulingActive:t(),peerHasSegment:c,p2pSlotsAvailable:d,previousP2pFailures:o})?n.call(s,e):r.call(s,e)}),s})}(s,()=>!0===this.playbackIsLive&&this.p2pEnabled&&this.activePeers.size>0),s}async failoverTracker(e){if(this.disposed||this.failoverInFlight||this.trackerCandidates.length<2)return;const t=this.trackerCandidates.indexOf(e),s=(t>=0?t:this.activeTrackerIndex)+1;if(!(s>=this.trackerCandidates.length)){this.failoverInFlight=!0;try{const e=this.trackerCandidates[s];this.engineGeneration+=1,this.engine.destroy(),this.activeTrackerIndex=s,this.activePeers.clear(),this.stats.connectedPeers=0,this.p2pReady=!1,this.engine=this.createEngine(e),this.engine.bindHls(this.hlsjsInstance),Object.assign(this.hlsjsInstance.config,this.engine.getConfigForHlsJs()),this.bindEvents()}finally{this.failoverInFlight=!1}}}notify(e){for(const t of this.eventListeners)yE(()=>e(t))}notifyPlaybackState(e){this.notify(t=>t.onPlaybackStateChanged?.(e))}startStatsReporting(){this.reportUrl&&(this.reportTimer=window.setTimeout(()=>{this.reportStats().catch(()=>{}),this.reportTimer=window.setInterval(()=>{this.reportStats().catch(()=>{})},this.reportIntervalMs)},K(this.reportIntervalMs)))}applyPeerOptimizedWindows(e){const t=e?this.playbackIsLive?this.liveSeedCohort?"live-seed":"live":"generic":"baseline";this.playbackIsLive?this.diagnosticState.liveSeed={cohort:this.liveSeedCohort,active:e&&this.liveSeedCohort}:delete this.diagnosticState.liveSeed,this.peerWindowProfile!==t&&(this.peerWindowProfile=t,this.engine.applyDynamicConfig({core:"live"===t||"live-seed"===t?{highDemandTimeWindow:KS.livePeerHighDemandTimeWindow,httpDownloadTimeWindow:"live-seed"===t?KS.liveSeedHttpDownloadTimeWindow:KS.livePeerHttpDownloadTimeWindow,p2pDownloadTimeWindow:KS.peerP2pDownloadTimeWindow}:"generic"===t?{highDemandTimeWindow:KS.peerHighDemandTimeWindow,httpDownloadTimeWindow:KS.peerHttpDownloadTimeWindow,p2pDownloadTimeWindow:KS.peerP2pDownloadTimeWindow}:{highDemandTimeWindow:KS.highDemandTimeWindow,httpDownloadTimeWindow:KS.httpDownloadTimeWindow,p2pDownloadTimeWindow:KS.p2pDownloadTimeWindow}}))}async reportStats(e,t=!1){if(!this.reportUrl||void 0===this.playbackIsLive)return;const s={...e??this.stats};if(this.reportInFlight)t&&(this.pendingFinalReport=s);else{this.reportInFlight=!0;try{this.recordLiveLatency();const e=function(e,t){return{...e,...e.coldStart?{coldStart:{...e.coldStart}}:{},...e.liveLatency?{liveLatency:{...e.liveLatency}}:{},...e.liveSeed?{liveSeed:{...e.liveSeed}}:{},...e.playbackAuth?{playbackAuth:{...e.playbackAuth}}:{},...e.ice?{ice:{...e.ice}}:{},...t?{auth:{...t}}:e.auth?{auth:{...e.auth}}:{},...e.websocket?{websocket:{...e.websocket}}:{}}}(this.diagnosticState,this.sessionTokenManager?.diagnostics?.()),t=!this.hasReportedContext,i=await(this.sessionTokenManager?.getAuthorizationHeader()),r=await z(this.reportUrl,V({platform:"web",playbackMode:this.playbackIsLive?"live":"vod",runtimeMode:"mse",protocol:"hls",playerType:"hlsjs",appId:this.appId,keyId:this.keyId,sdkVersion:Q,sessionId:this.sessionId,contentId:M(this.contentId,this.streamUrl),swarmId:this.swarmId,playbackUrl:this.streamUrl,stats:s,capability:this.capability,load:{uploadSlots:this.uploadSlots,activeUploadPeers:Math.min(s.connectedPeers,this.uploadSlots),downloadSlots:this.downloadSlots,activeDownloadPeers:Math.min(s.connectedPeers,this.downloadSlots)},diagnostics:e},t),{authorizationHeader:i});r?.ok&&(this.hasReportedContext=!0)}finally{this.reportInFlight=!1;const e=this.pendingFinalReport;this.pendingFinalReport=void 0,e&&this.reportStats(e,!0)}}}currentLiveLatency(){if(!this.playbackIsLive)return;const e=pE(this.hlsjsInstance.latency),t=pE(this.hlsjsInstance.targetLatency),s=pE(this.hlsjsInstance.maxLatency);return void 0!==e&&void 0!==t&&void 0!==s?{lastLatencyMs:e,lastTargetLatencyMs:t,lastMaxLatencyMs:s}:void 0}recordLiveLatency(){const e=this.currentLiveLatency();if(!e)return;const t=this.diagnosticState.liveLatency??{samples:0,latencyDurationMs:0,targetLatencyDurationMs:0,maxLatencyDurationMs:0,overMaxLatencySamples:0};t.samples+=1,t.latencyDurationMs+=e.lastLatencyMs,t.targetLatencyDurationMs+=e.lastTargetLatencyMs,t.maxLatencyDurationMs+=e.lastMaxLatencyMs,e.lastLatencyMs>e.lastMaxLatencyMs&&(t.overMaxLatencySamples+=1),this.diagnosticState.liveLatency=t}}}});function EE(e){return e in globalThis}function bE(e,t){return e??t}var TE="https://api.meshstream.net/config-api/v1/sdk/bootstrap",wE=[1e3,2e3,5e3,1e4,3e4],IE=new Map,LE=new Map,AE=new Map;async function kE(e,t={}){const s=function(e){const t=new URL(e);t.pathname&&"/"!==t.pathname||(t.pathname="/v1/sdk/bootstrap");for(const e of["key","app_id","appId","platform","package_name","packageName","signing_cert_sha256","signingCertSha256","network_type","networkType"])t.searchParams.delete(e);return t.toString()}(e.bootstrapUrl?.trim()||TE),i=e.key?.trim(),r=e.platform?.trim()||"web";if(!i)return;const n=t.now??Date.now,a=function(e){return JSON.stringify({bootstrapUrl:e.bootstrapUrl?.trim()||TE,key:e.key?.trim(),platform:e.platform?.trim()||"web",contentId:e.contentId?.trim()||"",expectedPeers:e.expectedPeers??0})}({...e,bootstrapUrl:s,key:i,platform:r}),o=IE.get(a);if(!t.forceRefresh&&o){if(n()<o.expiresAtMs)return IE.delete(a),IE.set(a,o),o.config;n()>=o.staleUntilMs&&IE.delete(a)}const l=LE.get(a);if(l)return l;const h=async function({request:e,options:t,bootstrapUrl:s,key:i,platform:r,cacheKey:n,now:a}){try{const d=t.fetcher??fetch,c=function(e){const t={},s=e.key?.trim();s&&(t.key=s),t.platform=e.platform?.trim()||"web";const i=e.contentId?.trim();return i&&(t.contentId=i),Number.isFinite(e.expectedPeers)&&(e.expectedPeers??0)>0&&(t.expectedPeers=String(Math.floor(e.expectedPeers))),t}({key:i,platform:r,contentId:e.contentId,expectedPeers:e.expectedPeers}),u=await async function(e,t,s,i){const r=new AbortController;let n;const a=new Promise((e,t)=>{n=setTimeout(()=>{r.abort(),t(new Error(`SDK bootstrap timed out after ${i} ms`))},i)});try{return await Promise.race([e(t,{...s,signal:r.signal}),a])}finally{void 0!==n&&clearTimeout(n)}}(d,s,{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(c)},(h=t.timeoutMs,Number.isFinite(h)?Math.max(1,Math.min(3e4,Math.floor(h))):8e3));if(!u.ok)return 408===(l=u.status)||429===l||l>=500?(RE(t,"TRANSIENT_HTTP"),CE(e,t,n),PE(n,a())):(RE(t,"REJECTED"),function(e){IE.delete(e)}(n));const f={configVersion:(o=await u.json()).configVersion,appId:o.appId,applicationId:o.applicationId,homeRegion:o.homeRegion,edgeRegion:o.edgeRegion,keyId:o.keyId,keyName:o.keyName,keyEnabled:o.keyEnabled,keyPlatform:o.keyPlatform,p2pEnabled:o.p2pEnabled,ttlSeconds:o.ttlSeconds,refreshAfterSeconds:o.refreshAfterSeconds,applyMode:o.applyMode,status:o.status,quota:o.quota,accessUrl:o.accessUrl,trackerUrls:Array.isArray(o.trackerUrls)?o.trackerUrls.filter(e=>Boolean(e?.trim())):[],primaryTrackerUrl:DE(o.primaryTrackerUrl,o.trackerUrls),iceServers:_E(o.iceServers),trackerNodes:Array.isArray(o.trackerNodes)?o.trackerNodes:void 0,trackerPool:o.trackerPool,reportUrl:o.reportUrl,scheduling:o.scheduling,playbackAuth:o.playbackAuth,defaults:o.defaults},g=a()+1e3*function(e){const t=e.refreshAfterSeconds??e.ttlSeconds??60;return Number.isFinite(t)?Math.max(5,Math.min(3600,Math.floor(t))):60}(f);return function(e,t){for(IE.delete(e),IE.set(e,t);IE.size>32;){const e=IE.keys().next().value;if(void 0===e)return;IE.delete(e)}}(n,{config:f,expiresAtMs:g,staleUntilMs:g+3e5}),f}catch{return RE(t,"NETWORK"),CE(e,t,n),PE(n,a())}var o,l,h}({request:e,options:t,bootstrapUrl:s,key:i,platform:r,cacheKey:a,now:n});LE.set(a,h);try{return await h}finally{LE.get(a)===h&&LE.delete(a)}}function RE(e,t){try{e.onFailure?.(t)}catch{}}function CE(e,t,s){if(t.suppressBackgroundRetry||AE.has(s))return;const i=(async()=>{for(const s of wE){await new Promise(e=>{const t=globalThis.setTimeout(e,s);t.unref?.()});let i=!1,r=!1;if(await kE(e,{...t,forceRefresh:!0,suppressBackgroundRetry:!0,onFailure:e=>{i="NETWORK"===e||"TRANSIENT_HTTP"===e,r="REJECTED"===e,RE(t,e)}})&&!i)return;if(r||!i)return}})();AE.set(s,i),i.finally(()=>{AE.get(s)===i&&AE.delete(s)})}function PE(e,t){const s=IE.get(e);if(s&&!(t>=s.staleUntilMs))return s.config;s&&IE.delete(e)}function DE(e,t){const s=e?.trim();if(s&&Array.isArray(t))return t.some(e=>e?.trim()===s)?s:void 0}function ME(e){return!0===e?.p2pEnabled&&!1!==e.status?.effectiveP2pEnabled&&"exhausted"!==e.quota?.status&&"disabled"!==e.quota?.status&&e.trackerUrls.length>0}function _E(e){if(Array.isArray(e))return[...new Set(e.map(e=>e?.trim()).filter(e=>Boolean(e)))].filter(e=>e.startsWith("stun:")||e.startsWith("stuns:")).slice(0,3)}async function OE(e,t={}){const s=e.sdkConfig?.reportUrl?.trim();if(!s)return;const i=await async function(e,t={}){const s=e.protocol??function(e){const t=e.split("?",1)[0]?.toLowerCase()??"";return t.endsWith(".m3u8")?"hls":t.endsWith(".mpd")?"dash":t.endsWith(".mp4")?"mp4":t.endsWith(".mp3")?"mp3":void 0}(e.streamUrl);if("mp4"===s||"mp3"===s)return"vod";if("hls"!==s&&"dash"!==s)return;const i=new AbortController,r=(n=t.manifestProbeTimeoutMs,Number.isFinite(n)?Math.max(200,Math.min(5e3,Math.floor(n))):2e3);var n;let a;const o=new Promise((e,t)=>{a=globalThis.setTimeout(()=>{i.abort(),t(new Error(`fallback manifest probe timed out after ${r} ms`))},r)});try{const r=await Promise.race([FE(e,t,i.signal),o]);return"hls"===s?BE(e,t,i.signal,r):function(e){return/<MPD\b/i.test(e)?/<MPD\b[^>]*\btype\s*=\s*["']dynamic["']/i.test(e)?"live":"vod":void 0}(r)}catch{return}finally{void 0!==a&&globalThis.clearTimeout(a)}}(e,t);if(!i)return;const r=e.sessionId?.trim()||t.sessionIdFactory?.()||`web-fallback-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`,n=M(e.contentId,e.streamUrl),a=e.contentId?.trim()?D(e.contentId):P(e.streamUrl),o=e.sessionToken?.trim()||await(e.sessionTokenProvider?.());return z(s,V({platform:"web",playbackMode:i,runtimeMode:"cdn",protocol:e.protocol,playerType:e.playerType,appId:e.appId,keyId:e.keyId??e.sdkConfig?.keyId,sdkVersion:Q,sessionId:r,contentId:n,swarmId:a,playbackUrl:e.streamUrl,stats:{httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0},capability:e.capability,load:{uploadSlots:0,activeUploadPeers:0,downloadSlots:0,activeDownloadPeers:0},diagnostics:{fallbackCount:1,playbackAuth:b(e.streamUrl,e.sdkConfig?.playbackAuth)}}),{fetcher:t.fetcher,authorizationHeader:o?`Bearer ${o}`:void 0})}function xE(e,t={}){OE(e,t).catch(()=>{})}async function FE(e,t,s,i=e.streamUrl){const r=await(t.manifestFetcher??t.fetcher??fetch)(i,{method:"GET",headers:UE(i,e.streamUrl)?g(e.originHeaders,e.originHeadersProvider,i,"manifest"):{},cache:"no-store",credentials:"same-origin",signal:s});if(!r.ok)throw new Error(`fallback manifest probe failed with ${r.status}`);return r.text()}async function BE(e,t,s,i,r=0){const n=i.replace(/^\uFEFF/,"");if(!/^#EXTM3U(?:\r?\n|$)/.test(n))return;if(/#EXT-X-ENDLIST(?:\r?\n|$)/.test(n))return"vod";const a=function(e,t){const s=e.split(/\r?\n/);for(let e=0;e<s.length;e+=1)if(/^#EXT-X-STREAM-INF:/i.test(s[e]?.trim()??""))for(let i=e+1;i<s.length;i+=1){const e=s[i]?.trim()??"";if(e){if(e.startsWith("#"))break;try{return new URL(e,t).toString()}catch{return}}}}(n,e.streamUrl);return a?r>=1?void 0:BE(e,t,s,await FE(e,t,s,a),r+1):/#EXT-X-STREAM-INF:/i.test(n)?void 0:"live"}function UE(e,t){try{return new URL(e,t).origin===new URL(t).origin}catch{return!1}}E(),w(),J(),W(),Z(),E();var NE=class{generation=0;begin(){return this.generation+=1,this.generation}cancel(){this.generation+=1}isCurrent(e){return e===this.generation}assertCurrent(e){if(!this.isCurrent(e))throw new DOMException("Playback session was disposed","AbortError")}};J(),W();var $E=class{accessUrl;appId;keyId;sessionId;platform;fetcher;now;timeoutMs;token;refreshAfterMs=0;expiresAtMs=0;refreshTimer;inFlight;activeAbortController;disposed=!1;authMetrics={attempts:0,successes:0,failures:0,durationMs:0};constructor(e,t={}){var s;this.accessUrl=function(e){const t=e?.trim();if(t)try{const e=new URL(t);for(const t of HE)e.searchParams.delete(t);if("undefined"!=typeof window){const{protocol:t,hostname:s,origin:i}=window.location;if(["localhost","127.0.0.1","::1"].includes(s)&&A(e.hostname)){if("https:"===t){const t=new URL(i);return t.pathname="/access-api/v1/sdk/sessions",t.search=e.search,t.hash="",t.toString()}e.hostname=s}}return e.toString()}catch{return t}}(e.accessUrl),this.appId=e.appId.trim(),this.keyId=e.keyId?.trim()||void 0,this.sessionId=e.sessionId.trim(),this.platform=e.platform,this.fetcher=t.fetcher??globalThis.fetch.bind(globalThis),this.now=t.now??Date.now,this.timeoutMs=(s=t.timeoutMs,Number.isFinite(s)?Math.max(1,Math.min(3e4,Math.floor(s))):8e3)}async getSessionToken(){if(this.accessUrl&&this.appId&&this.sessionId&&!this.disposed)return this.token&&this.now()<this.refreshAfterMs?this.token:this.refreshToken()}async getAuthorizationHeader(){const e=await this.getSessionToken();return e?`Bearer ${e}`:void 0}async getTrackerUrl(e){const t=await this.getSessionToken();if(!this.accessUrl||t)return function(e,t){if(!e)return;const s=t?.trim();if(!s)return e;try{const t=new URL(e);return t.searchParams.set("token",s),t.toString()}catch{return e}}(e,t)??e}diagnostics(){return{...this.authMetrics}}dispose(){this.disposed=!0,this.activeAbortController?.abort(),this.activeAbortController=void 0,void 0!==this.refreshTimer&&(globalThis.clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}async refreshToken(){return this.inFlight||(this.inFlight=this.fetchSessionToken().finally(()=>{this.inFlight=void 0})),this.inFlight}async fetchSessionToken(){if(this.disposed||!this.accessUrl)return;const e=performance.now();let t=!1;this.authMetrics.attempts+=1;try{const e=this.token?function(e){const t=new URL(e);return t.pathname=t.pathname.replace(/\/?$/,"/refresh"),t.toString()}(this.accessUrl):this.accessUrl,s=new AbortController;let i;this.activeAbortController=s;const r=new Promise((e,t)=>{i=globalThis.setTimeout(()=>{s.abort(),t(new Error(`SDK access request timed out after ${this.timeoutMs} ms`))},this.timeoutMs)}),n=new Promise((e,t)=>{s.signal.addEventListener("abort",()=>{t(s.signal.reason??new Error("SDK access request aborted"))},{once:!0})});let a;try{const t=this.fetcher(e,{method:"POST",headers:this.token?{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}:{"Content-Type":"application/json"},body:this.token?void 0:JSON.stringify({appId:this.appId,keyId:this.keyId,sessionId:this.sessionId,platform:this.platform,identity:{platform:this.platform}}),cache:"no-store",signal:s.signal});a=await Promise.race([t,r,n])}finally{void 0!==i&&globalThis.clearTimeout(i),this.activeAbortController===s&&(this.activeAbortController=void 0)}if(this.disposed)return;if(!a.ok)return 401===a.status&&this.token?(this.token=void 0,this.refreshAfterMs=0,this.expiresAtMs=0,this.fetchSessionToken()):void 0;const o=await a.json();if(this.disposed)return;const l=o.sessionToken?.trim();if(!l)return;return this.token=l,this.expiresAtMs=GE(o.expiresAt),this.refreshAfterMs=GE(o.refreshAfter)||Math.max(this.now()+3e4,this.expiresAtMs-3e4),this.scheduleRefresh(),t=!0,l}catch{return}finally{this.authMetrics.durationMs+=Math.max(0,Math.round(performance.now()-e)),t?this.authMetrics.successes+=1:this.authMetrics.failures+=1}}scheduleRefresh(){if(this.disposed)return;if(void 0!==this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0),!this.token)return;const e=this.refreshAfterMs||this.expiresAtMs,t=Math.max(1,e-this.now());this.refreshTimer=globalThis.setTimeout(()=>{this.refreshToken().catch(()=>{})},t),this.refreshTimer?.unref?.()}};function GE(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.floor(1e3*e)}var HE=["app_id","appId","application_id","applicationId","tenant_id","tenantId","key","sdkKey","key_id","keyId","session_id","sessionId","platform","token"],WE="/__meshstream__/v1/",qE=new Map,jE=class{registration;messageListener;segmentProviders=new Map;originHeadersProviders=new Map;statsListeners=new Map;sessionBridgePorts=new Map;bridgeRequests=0;bridgeUnavailableResponses=0;constructor(e){this.registration=e,this.messageListener=e=>{const t=e.data;if("MESHSTREAM_SW_SEGMENT_RESULT"===t?.type&&t.sessionId){const e=this.statsListeners.get(t.sessionId);if(!e)return;const s={sessionId:t.sessionId,resourceId:t.resourceId??"",url:t.url??"",source:"p2p"===t.source?"p2p":"cdn",bytes:Number.isFinite(t.bytes)?Math.max(0,t.bytes):0,status:Number.isFinite(t.status)?t.status:200,p2pBytes:Number.isFinite(t.p2pBytes)?Math.max(0,t.p2pBytes):void 0,cdnBytes:Number.isFinite(t.cdnBytes)?Math.max(0,t.cdnBytes):void 0};try{e(s)}catch{}return}const s=e.ports?.[0];if("MESHSTREAM_SW_ORIGIN_HEADERS_REQUEST"===t?.type&&t.sessionId&&s){let e;try{e=this.originHeadersProviders.get(t.sessionId)?.({url:t.url??"",kind:(i=t.kind,"manifest"===i||"segment"===i||"key"===i||"direct-file"===i||"unknown"===i?t.kind:"unknown")})}catch{}return void s.postMessage({type:"MESHSTREAM_SW_ORIGIN_HEADERS_RESPONSE",headers:e??{}})}var i;if("MESHSTREAM_SW_SEGMENT_REQUEST"!==t?.type||!t.sessionId||!s)return;this.bridgeRequests+=1;const r=this.segmentProviders.get(t.sessionId);if(!r)return n=t.sessionId,void((qE.get(n)??0)>0||(this.bridgeUnavailableResponses+=1,s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})));var n;r({sessionId:t.sessionId,resourceId:t.resourceId??"",url:t.url??"",headers:new Headers(t.headers??{})}).then(e=>{if(!e)return this.bridgeUnavailableResponses+=1,void s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"});e.stream?function(e,t){const s=t.stream;if(!s||!Number.isFinite(t.bytes)||(t.bytes??0)<0)return void e.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"});const i=s.getReader();let r=!1;const n=(s=!1,n=!1)=>{if(r)return;r=!0,s&&i.cancel().catch(()=>{});const a=t.transferStats?.p2pBytes??t.p2pBytes,o=t.transferStats?.cdnBytes??t.cdnBytes,l=(a??0)+(o??0);e.postMessage({type:n?"MESHSTREAM_SW_SEGMENT_STREAM_ERROR":"MESHSTREAM_SW_SEGMENT_STREAM_COMPLETE",source:YE(a,o,t.source),bytes:l>0?l:t.bytes,p2pBytes:a,cdnBytes:o});try{e.close()}catch{}};e.onmessage=async t=>{const s=t.data;if("MESHSTREAM_SW_SEGMENT_STREAM_CANCEL"!==s?.type){if("MESHSTREAM_SW_SEGMENT_STREAM_PULL"===s?.type&&!r)try{const t=await i.read();if(t.done)return void n();const s=function(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}(t.value);e.postMessage({type:"MESHSTREAM_SW_SEGMENT_STREAM_CHUNK",body:s},[s])}catch{n(!0,!0)}}else n(!0)},e.postMessage({type:"MESHSTREAM_SW_SEGMENT_STREAM_START",status:t.status,statusText:t.statusText,headers:t.headers,source:t.source,bytes:t.bytes})}(s,e):e.body?s.postMessage({type:"MESHSTREAM_SW_SEGMENT_RESPONSE",status:e.status,statusText:e.statusText,headers:e.headers,source:e.source,bytes:e.bytes??e.body.byteLength,p2pBytes:e.p2pBytes,cdnBytes:e.cdnBytes,body:e.body},[e.body]):s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})}).catch(()=>{this.bridgeUnavailableResponses+=1,s.postMessage({type:"MESHSTREAM_SW_SEGMENT_UNAVAILABLE"})})},navigator.serviceWorker.addEventListener("message",this.messageListener)}async registerSession(e){const t=e.sessionId,s=this.segmentProviders.has(t);this.segmentProviders.set(t,e.segmentProvider??(async()=>{})),e.originHeadersProvider?this.originHeadersProviders.set(t,e.originHeadersProvider):this.originHeadersProviders.delete(t),s||function(e){qE.set(e,(qE.get(e)??0)+1)}(t),e.onSegmentStats&&this.statsListeners.set(t,e.onSegmentStats);const i=new MessageChannel;i.port1.onmessage=this.messageListener,i.port1.start?.(),this.closeSessionBridge(t),this.sessionBridgePorts.set(t,i.port1);try{await ZE(this.registration,{type:"MESHSTREAM_SW_REGISTER_SESSION",protocolVersion:1,sessionId:t,manifestUrl:e.manifestUrl,resourceKind:e.resourceKind,originHeaders:e.originHeaders,p2pTimeoutMs:(r=e.p2pTimeoutMs,Number.isFinite(r)?Math.max(100,Math.floor(r)):5e3)},[i.port2])}catch(e){throw this.closeSessionBridge(t),s||KE(t),this.segmentProviders.delete(t),this.originHeadersProviders.delete(t),this.statsListeners.delete(t),e}var r;const n=function(e,t){return"undefined"==typeof location?`${WE}${encodeURIComponent(e)}/${t}`:new URL(`${WE}${encodeURIComponent(e)}/${t}`,location.origin).toString()}(t,"manifest");let a=!1;return{sessionId:t,manifestUrl:n,dispose:async()=>{a||(a=!0,this.removeSession(t),this.statsListeners.delete(t),await ZE(this.registration,{type:"MESHSTREAM_SW_UNREGISTER_SESSION",protocolVersion:1,sessionId:t}))}}}dispose(){navigator.serviceWorker.removeEventListener("message",this.messageListener);for(const e of this.segmentProviders.keys())KE(e);this.segmentProviders.clear(),this.originHeadersProviders.clear(),this.statsListeners.clear();for(const e of this.sessionBridgePorts.values())VE(e);this.sessionBridgePorts.clear()}diagnostics(){return{serviceWorkerBridgeRequests:this.bridgeRequests,serviceWorkerBridgeUnavailableResponses:this.bridgeUnavailableResponses}}removeSession(e){this.closeSessionBridge(e),this.segmentProviders.delete(e)&&(this.originHeadersProviders.delete(e),KE(e))}closeSessionBridge(e){const t=this.sessionBridgePorts.get(e);t&&(this.sessionBridgePorts.delete(e),VE(t))}};function KE(e){const t=qE.get(e)??0;t<=1?qE.delete(e):qE.set(e,t-1)}function VE(e){try{e.close()}catch{}}function YE(e,t,s){return(e??0)>0&&0===(t??0)||"p2p"===s?"p2p":"cdn"}function zE(){return"undefined"!=typeof navigator&&"serviceWorker"in navigator&&!("undefined"!=typeof isSecureContext&&!isSecureContext)}async function QE(e={}){if(!zE())throw new Error("MeshStream Service Worker requires a secure context and navigator.serviceWorker");const t=e.registration??await navigator.serviceWorker.register(e.url??"/meshstream-sw.js",e.scope?{scope:e.scope}:void 0),s=e.readyTimeoutMs??1e4,i=await async function(e){return function(e,t){return new Promise((s,i)=>{const r=setTimeout(()=>i(new Error("Service Worker activation timed out")),t);e.then(e=>{clearTimeout(r),s(e)},e=>{clearTimeout(r),i(e)})})}(navigator.serviceWorker.ready,e)}(s);return await async function(e,t){!navigator.serviceWorker.controller&&t.active&&await new Promise((t,s)=>{const i=setTimeout(()=>{navigator.serviceWorker.removeEventListener("controllerchange",r),s(new Error("MeshStream Service Worker controller claim timed out"))},e),r=()=>{clearTimeout(i),navigator.serviceWorker.removeEventListener("controllerchange",r),t()};navigator.serviceWorker.addEventListener("controllerchange",r,{once:!0}),navigator.serviceWorker.controller&&r()})}(s,i),await JE(t,s),new jE(t)}async function XE(e){const t=!e.serviceWorker,s=e.serviceWorker??await async function(){if(!zE()||!navigator.serviceWorker.controller)return;const e=await navigator.serviceWorker.ready;try{return await JE(e,750),new jE(e)}catch{return}}();if(!s)return;const i=await s.registerSession({sessionId:e.sessionId??(r="sw",`${r}-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`),manifestUrl:e.manifestUrl,resourceKind:e.resourceKind,originHeaders:e.originHeaders,originHeadersProvider:e.originHeadersProvider,p2pTimeoutMs:e.p2pTimeoutMs,segmentProvider:e.segmentProvider,onSegmentStats:e.onSegmentStats});var r;if(!t)return i;const n=i.dispose;return{sessionId:i.sessionId,manifestUrl:i.manifestUrl,dispose:async()=>{try{await n()}finally{s.dispose()}}}}async function JE(e,t){const s=navigator.serviceWorker.controller??e.active??e.waiting??e.installing;if(!s)throw new Error("MeshStream Service Worker has no active worker");await new Promise((e,i)=>{const r=new MessageChannel,n=()=>{try{r.port1.close()}catch{}},a=setTimeout(()=>{n(),i(new Error("MeshStream Service Worker handshake timed out"))},t);r.port1.onmessage=t=>{clearTimeout(a),n(),"MESHSTREAM_SW_READY"===t.data?.type?e():i(new Error("Invalid MeshStream Service Worker handshake"))},s.postMessage({type:"MESHSTREAM_SW_PING",protocolVersion:1},[r.port2])})}async function ZE(e,t,s=[]){const i=navigator.serviceWorker.controller??e.active??e.waiting??e.installing;if(!i)throw new Error("MeshStream Service Worker is not active");await new Promise((e,r)=>{const n=new MessageChannel,a=()=>{try{n.port1.close()}catch{}},o=setTimeout(()=>{a(),r(new Error("MeshStream Service Worker session acknowledgement timed out"))},2e3);n.port1.onmessage=t=>{clearTimeout(o),a(),"MESHSTREAM_SW_SESSION_READY"===t.data?.type||"MESHSTREAM_SW_SESSION_REMOVED"===t.data?.type?e():r(new Error("Invalid MeshStream Service Worker session acknowledgement"))},i.postMessage(t,[n.port2,...s])})}re(),E(),Mt();var eb=1048576,tb=8388608,sb=class e{swarmId;core;trackerCandidates;createCore;streamIdFactory;manifestUrl;resourceKind;requestTimeoutMs;playbackIsLive;manifestRequestSetup;originHeaders;originHeadersProvider;streams=new Map;segmentIdsByRequestKey=new Map;playbackPositionsByRuntimeId=new Map;completedSources=new Map;eventListeners=new Set;startedAtMs=performance.now();eventTimer;p2pReady=!1;stats={httpDownloaded:0,p2pDownloaded:0,p2pUploaded:0,httpSegmentDownloadSuccesses:0,httpSegmentDownloadFailures:0,p2pSegmentDownloadSuccesses:0,p2pSegmentDownloadFailures:0,p2pSegmentUploadSuccesses:0,p2pSegmentUploadFailures:0,connectedPeers:0,peerConnectErrors:0,trackerErrors:0};pendingSegmentLoads=new Map;directChunks=new Map;directFile;disposed=!1;peerCount=0;peerInfoHashes=new Set;trackerErrors=0;lastTrackerError;peerConnectErrors=0;firstPeerConnectMs;fallbackCount=0;lastPeerError;lastErrorAtMs;ice={attempts:0,successes:0,failures:0,durationMs:0};peerSegmentAnnouncements=0;peerAnnouncedSegments=0;peerHttpLoadingSegments=0;p2pAttempts=0;httpAttempts=0;p2pErrors=0;httpErrors=0;p2pUploaded=0;p2pSegmentUploadSuccesses=0;p2pSegmentUploadFailures=0;lastLoadedBytes=0;segmentRequests=0;runtimeIdMisses=0;segmentLoadSuccesses=0;segmentLoadTimeouts=0;indexedSegments=0;activeTrackerIndex=0;failoverInFlight=!1;coreReady=Promise.resolve();coreGeneration=0;coreRebuildInFlight;coreRebuildGeneration;lastCoreRebuildAttemptAtMs=0;p2pEnabled=!0;directFileLoadQueue=Promise.resolve();hasIssuedCoreLoad=!1;constructor(e,t,s,i){this.swarmId=e.swarmId,this.manifestUrl=new URL(e.manifestUrl,globalThis.location?.href??"http://localhost/").toString(),this.resourceKind="direct-file"===e.resourceKind?"direct-file":"hls","direct-file"===this.resourceKind&&(this.playbackIsLive=!1),this.requestTimeoutMs=ub(e.requestTimeoutMs),this.streamIdFactory=i,this.originHeaders=e.originHeaders,this.originHeadersProvider=e.originHeadersProvider,this.manifestRequestSetup=u(e.originHeaders,e.originHeadersProvider,e.manifestUrl),this.trackerCandidates=[...new Set([e.trackerUrl,...e.trackerUrls??[]].map(e=>e?.trim()).filter(e=>Boolean(e)))],this.createCore=s,this.core=t,this.bindCoreEvents()}bindCoreEvents(){const e=this.core,t=this.coreGeneration;e.setManifestResponseUrl(this.manifestUrl),e.addEventListener("onSegmentLoaded",e=>{if(t!==this.coreGeneration)return;this.lastLoadedBytes=e.bytesLength;const s="p2p"===e.downloadSource?"p2p":"cdn";this.completedSources.set(e.segment.runtimeId,s),"p2p"===s?(this.stats.p2pDownloaded+=e.bytesLength,this.stats.p2pSegmentDownloadSuccesses+=1):(this.stats.httpDownloaded+=e.bytesLength,this.stats.httpSegmentDownloadSuccesses+=1,0===this.peerCount&&(this.fallbackCount+=1),this.notify(t=>t.onCdnFallback?.(e.bytesLength)))}),e.addEventListener("onSegmentStart",e=>{t===this.coreGeneration&&("p2p"===e.downloadSource?this.p2pAttempts+=1:this.httpAttempts+=1)}),e.addEventListener("onSegmentError",e=>{t===this.coreGeneration&&("p2p"===e.downloadSource?(this.p2pErrors+=1,this.stats.p2pSegmentDownloadFailures+=1):(this.httpErrors+=1,this.stats.httpSegmentDownloadFailures+=1))}),e.addEventListener("onChunkUploaded",e=>{t===this.coreGeneration&&(this.p2pUploaded+=e,this.p2pSegmentUploadSuccesses+=1,this.stats.p2pUploaded+=e,this.stats.p2pSegmentUploadSuccesses+=1)}),e.addEventListener("onPeerConnect",e=>{t===this.coreGeneration&&(this.ice.attempts+=1,this.ice.successes+=1,this.peerCount+=1,this.peerInfoHashes.add(e.infoHash),this.stats.connectedPeers=this.peerCount,this.notify(e=>e.onPeerCountChanged?.(this.peerCount)),!this.p2pReady&&this.p2pEnabled&&(this.firstPeerConnectMs??=this.elapsedSinceStartMs(),this.p2pReady=!0,this.notify(e=>e.onP2pReady?.()),this.notifyPlaybackState("p2p-ready")))}),e.addEventListener("onPeerClose",e=>{t===this.coreGeneration&&(this.peerCount=Math.max(0,this.peerCount-1),this.peerInfoHashes.delete(e.infoHash),this.stats.connectedPeers=this.peerCount,this.notify(e=>e.onPeerCountChanged?.(this.peerCount)),this.p2pReady&&0===this.peerCount&&this.notifyUnavailable(this.p2pEnabled?"NO_PEERS":"DISABLED"))}),e.addEventListener("onTrackerError",e=>{t===this.coreGeneration&&(this.trackerErrors+=1,this.stats.trackerErrors=this.trackerErrors,this.lastTrackerError=String(e.error?.message??e.error??"tracker request failed").slice(0,240),this.notify(e=>e.onTrackerError?.(this.trackerErrors)),this.notifyUnavailable("TRACKER_ERROR"),this.failoverTracker(e.trackerUrl))}),e.addEventListener("onPeerConnectError",e=>{t===this.coreGeneration&&(this.peerConnectErrors+=1,this.stats.peerConnectErrors=this.peerConnectErrors,this.ice.attempts+=1,this.ice.failures+=1,this.lastPeerError=function(e){if(e instanceof Error)return e.message.slice(0,240);if("string"==typeof e)return e.slice(0,240);try{return JSON.stringify(e??"peer connection failed").slice(0,240)}catch{return String(e??"peer connection failed").slice(0,240)}}(e),this.lastErrorAtMs=Date.now(),this.notify(e=>e.onPeerConnectError?.(this.peerConnectErrors)))}),e.addEventListener("onPeerSegmentsAnnouncement",(e,s,i,r,n)=>{t===this.coreGeneration&&(this.peerSegmentAnnouncements+=1,this.peerAnnouncedSegments=Number(r)||0,this.peerHttpLoadingSegments=Number(n)||0)})}static async create(t){const s=await Promise.resolve().then(()=>($o(),_t)),i=ub(t.requestTimeoutMs),r={swarmId:t.swarmId,rtcConfig:{iceServers:t.iceServers??(t.sdkConfig?.iceServers?.length?[{urls:t.sdkConfig.iceServers}]:ee())},httpRequestSetup:u(t.originHeaders,t.originHeadersProvider,t.manifestUrl),customSegmentStorageFactory:ne,httpDownloadInitialTimeoutMs:Math.min(3e3,i),highDemandTimeWindow:0,httpDownloadTimeWindow:0,p2pDownloadTimeWindow:15e3,preferP2PForEngineRequest:!0,simultaneousP2PDownloads:3,webRtcMaxMessageSize:16384,p2pNotReceivingBytesTimeoutMs:2e3,webRtcConnectionTimeoutMs:15e3},n=e=>{const t=new s.Core({...r,announceTrackers:[e]});return t.setIsLive(!1),t},a=n(t.trackerUrl);return new e(t,a,n,s.generateStreamShortId)}async failoverTracker(e){if(this.disposed||this.failoverInFlight||this.trackerCandidates.length<2)return;const t=this.trackerCandidates.indexOf(e),s=(t>=0?t:this.activeTrackerIndex)+1;if(!(s>=this.trackerCandidates.length)){this.failoverInFlight=!0;try{this.coreGeneration+=1,this.core.destroy(),this.activeTrackerIndex=s,this.peerCount=0,this.peerInfoHashes.clear(),this.core=this.createCore(this.trackerCandidates[s]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild(),await this.coreReady}finally{this.failoverInFlight=!1}}}async rebuildCoreState(e=this.coreGeneration){const t=this.core;"direct-file"!==this.resourceKind?await this.indexPlaylist(this.manifestUrl,new Set,void 0,t,e):this.rebuildDirectFileStream(t,e)}scheduleCoreRebuild(){const e=this.coreGeneration;if(this.coreRebuildInFlight&&this.coreRebuildGeneration===e)return this.coreRebuildInFlight;const t=this.rebuildCoreState(e).catch(()=>{});return this.coreRebuildInFlight=t,this.coreRebuildGeneration=e,t.finally(()=>{this.coreRebuildInFlight===t&&(this.coreRebuildInFlight=void 0,this.coreRebuildGeneration=void 0)}),t}async ensureCoreState(){if(this.disposed)return;if(this.coreRebuildInFlight)return void await this.coreRebuildInFlight;const e=Date.now();e-this.lastCoreRebuildAttemptAtMs<1e3||(this.lastCoreRebuildAttemptAtMs=e,await this.scheduleCoreRebuild())}async initialize(){"direct-file"!==this.resourceKind?await this.indexPlaylist(this.manifestUrl,new Set):await this.initializeDirectFile()}createSegmentProvider(){return e=>this.provideSegment(e)}addEventListener(e){this.eventListeners.add(e),fb(()=>e.onPlaybackStateChanged?.(this.p2pEnabled&&this.p2pReady?"p2p-ready":this.p2pEnabled?"connecting":"cdn-fallback")),void 0===this.eventTimer&&(this.eventTimer=globalThis.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)fb(()=>t.onStatistics?.(e))},1e3))}removeEventListener(e){this.eventListeners.delete(e),0===this.eventListeners.size&&void 0!==this.eventTimer&&(globalThis.clearInterval(this.eventTimer),this.eventTimer=void 0)}setP2pEnabled(e){if(this.disposed||this.p2pEnabled===e)return;const t=this.peerCount>0;if(this.p2pEnabled=e,this.hasIssuedCoreLoad=!1,this.coreGeneration+=1,this.core.destroy(),this.peerCount=0,this.peerInfoHashes.clear(),this.stats.connectedPeers=0,this.completedSources.clear(),t&&this.notify(e=>e.onPeerCountChanged?.(0)),!e)return this.notifyUnavailable("DISABLED"),void(this.coreReady=Promise.resolve());this.core=this.createCore(this.trackerCandidates[this.activeTrackerIndex]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild()}diagnostics(){return{p2pEnabled:this.p2pEnabled,directFileReady:Boolean(this.directFile),connectedPeers:this.peerCount,peerInfoHashes:[...this.peerInfoHashes].sort(),trackerErrors:this.trackerErrors,lastTrackerError:this.lastTrackerError,peerConnectErrors:this.peerConnectErrors,firstPeerConnectMs:this.firstPeerConnectMs,fallbackCount:this.fallbackCount,lastPeerError:this.lastPeerError,lastErrorAtMs:this.lastErrorAtMs,ice:{...this.ice},peerSegmentAnnouncements:this.peerSegmentAnnouncements,peerAnnouncedSegments:this.peerAnnouncedSegments,peerHttpLoadingSegments:this.peerHttpLoadingSegments,p2pAttempts:this.p2pAttempts,httpAttempts:this.httpAttempts,p2pErrors:this.p2pErrors,httpErrors:this.httpErrors,p2pUploaded:this.p2pUploaded,p2pSegmentUploadSuccesses:this.p2pSegmentUploadSuccesses,p2pSegmentUploadFailures:this.p2pSegmentUploadFailures,lastLoadedBytes:this.lastLoadedBytes,segmentRequests:this.segmentRequests,runtimeIdMisses:this.runtimeIdMisses,segmentLoadSuccesses:this.segmentLoadSuccesses,segmentLoadTimeouts:this.segmentLoadTimeouts,indexedSegments:this.indexedSegments}}statistics(){return{...this.stats}}isLive(){return!0===this.playbackIsLive}isPlaybackModeKnown(){return void 0!==this.playbackIsLive}dispose(){this.disposed||(this.disposed=!0,void 0!==this.eventTimer&&globalThis.clearInterval(this.eventTimer),this.eventTimer=void 0,this.streams.clear(),this.segmentIdsByRequestKey.clear(),this.playbackPositionsByRuntimeId.clear(),this.peerInfoHashes.clear(),this.completedSources.clear(),this.pendingSegmentLoads.clear(),this.directChunks.clear(),this.directFile=void 0,this.core.destroy(),this.eventListeners.clear())}notifyUnavailable(e){(this.p2pReady||"TRACKER_ERROR"===e||"DISABLED"===e)&&(this.p2pReady=!1,this.notify(t=>t.onP2pUnavailable?.(e)),this.notifyPlaybackState("cdn-fallback"))}notify(e){for(const t of this.eventListeners)fb(()=>e(t))}notifyPlaybackState(e){this.notify(t=>t.onPlaybackStateChanged?.(e))}elapsedSinceStartMs(){return Math.max(0,Math.round(performance.now()-this.startedAtMs))}async provideSegment(e){if(!this.p2pEnabled)return;if("direct-file"===this.resourceKind&&this.isLargeDirectFileRange(e))return this.loadSegmentResponse(e);const t=`${e.url}|${e.headers.get("range")??""}`;let s=this.pendingSegmentLoads.get(t);s||(s=this.loadSegmentResponse(e).finally(()=>{this.pendingSegmentLoads.get(t)===s&&this.pendingSegmentLoads.delete(t)}),this.pendingSegmentLoads.set(t,s));const i=await s;return i?function(e){return e.body?{...e,body:e.body.slice(0)}:e}(i):void 0}async loadSegmentResponse(e){if(this.disposed)return;if(this.segmentRequests+=1,"direct-file"===this.resourceKind)return this.loadDirectFileRange(e);await this.coreReady,await this.resetInitialCoreRequestWindow();let t=this.segmentIdsByRequestKey.get(ab(e.url,e.headers));if(t&&this.core.isSegmentLoadable(t)||(await this.ensureCoreState(),t=this.segmentIdsByRequestKey.get(ab(e.url,e.headers))),!t||!this.core.isSegmentLoadable(t))return void(this.runtimeIdMisses+=1);const s=this.core,i=await this.loadSegmentFromCore(s,t,this.requestTimeoutMs);if(!i)return void(this.segmentLoadTimeouts+=1);this.segmentLoadSuccesses+=1;const r=ob(e.headers.get("range")),n=this.completedSources.get(t)??"p2p",a={"content-length":String(i.byteLength),"content-type":"application/octet-stream"};return r&&(a["content-range"]=`bytes ${r.start}-${r.start+i.byteLength-1}/*`),{body:i,status:r?206:200,headers:a,source:n}}async initializeDirectFile(){const e=await this.fetchDirectFileMetadata("HEAD");let t=function(e){if(!e.ok||!/\bbytes\b/i.test(e.headers.get("accept-ranges")??""))return;const t=hb(e.headers.get("content-length"));return t?{contentLength:t,contentType:db(e)}:void 0}(e);if(!t&&(e.ok||405===e.status||501===e.status)){await cb(e);const s=await this.fetchDirectFileMetadata("GET");if(206!==s.status)throw await cb(s),new Error(`Direct media Range probe failed with ${s.status}`);if(t=function(e){const t=/^bytes\s+0-0\/(\d+)$/i.exec(e.headers.get("content-range")?.trim()??""),s=hb(t?.[1]??null);return s?{contentLength:s,contentType:db(e)}:void 0}(s),await cb(s),!t)throw new Error("Direct media P2P requires a valid Content-Range response header")}if(!t)throw new Error(`Direct media metadata request failed with ${e.status}`);this.directFile={contentLength:t.contentLength,contentType:t.contentType,streamId:"direct-file",streamIndex:this.streamIdFactory({bitrate:0,format:"direct-file",contentLength:t.contentLength})},this.rebuildDirectFileStream(this.core,this.coreGeneration)}async fetchDirectFileMetadata(e){const t="undefined"!=typeof AbortController?new AbortController:void 0,s=t?globalThis.setTimeout(()=>t.abort(),Math.min(this.requestTimeoutMs,5e3)):void 0;try{return await fetch(this.createDirectFileMetadataRequest(e,t?.signal))}catch(e){if(t?.signal.aborted)throw new Error("Direct media metadata request timed out");throw e}finally{void 0!==s&&globalThis.clearTimeout(s)}}createDirectFileMetadataRequest(e,t){const s=new Headers;for(const[e,t]of Object.entries(g(this.originHeaders,this.originHeadersProvider,this.manifestUrl,"direct-file")))try{s.set(e,t)}catch{}return"GET"===e?s.set("range","bytes=0-0"):s.delete("range"),new Request(this.manifestUrl,{method:e,headers:s,signal:t})}rebuildDirectFileStream(e,t){const s=this.directFile;s&&!this.disposed&&t===this.coreGeneration&&e===this.core&&(e.addStreamIfNoneExists({runtimeId:s.streamId,type:"main",index:s.streamIndex}),e.setIsLive(!1),e.updateStream(s.streamId,this.directChunks.values()),this.indexedSegments=this.directChunks.size)}async loadDirectFileRange(e){const t=this.directFile;if(!t||new URL(e.url,this.manifestUrl).toString()!==this.manifestUrl)return;const s=lb(e.headers.get("range"),t.contentLength);if(!s)return;if(s.end-s.start+1>tb)return this.streamDirectFileRange(s,t);await this.coreReady;const i=Math.floor(s.start/eb),r=Math.floor(s.end/eb),n=[];for(let e=i;e<=r;e+=1){const t=await this.loadDirectFileChunk(e);if(!t)return;n.push(t)}const a=function(e,t){const s=new Uint8Array(t.end-t.start+1);let i=0;for(const{segment:r,data:n}of e){const e=r.byteRange;if(!e)return;const a=Math.max(t.start,e.start),o=Math.min(t.end,e.end);if(o<a)continue;const l=a-e.start,h=o-a+1;if(l+h>n.byteLength||i+h>s.byteLength)return;s.set(new Uint8Array(n,l,h),i),i+=h}return i===s.byteLength?s.buffer:void 0}(n,s);if(!a||a.byteLength!==s.end-s.start+1)return;const o=function(e,t){let s=0,i=0;for(const r of e){const e=r.segment.byteRange;if(!e)continue;const n=Math.max(t.start,e.start),a=Math.min(t.end,e.end);if(a<n)continue;const o=a-n+1;"p2p"===r.source?s+=o:i+=o}return{p2pBytes:s,cdnBytes:i}}(n,s);return{body:a,status:206,headers:{"accept-ranges":"bytes","content-length":String(a.byteLength),"content-range":`bytes ${s.start}-${s.end}/${t.contentLength}`,"content-type":t.contentType},source:o.p2pBytes===a.byteLength?"p2p":"cdn",p2pBytes:o.p2pBytes,cdnBytes:o.cdnBytes}}isLargeDirectFileRange(e){const t=this.directFile;if(!t)return!1;const s=lb(e.headers.get("range"),t.contentLength);return Boolean(s&&s.end-s.start+1>tb)}streamDirectFileRange(e,t){const s={p2pBytes:0,cdnBytes:0};let i=Math.floor(e.start/eb);const r=Math.floor(e.end/eb);let n=!1;return{stream:new ReadableStream({pull:async t=>{if(n||i>r)return void t.close();const a=await this.loadDirectFileChunk(i);if(i+=1,!a?.segment.byteRange)return void t.error(new Error("Direct media chunk is unavailable"));const o=Math.max(e.start,a.segment.byteRange.start),l=Math.min(e.end,a.segment.byteRange.end),h=o-a.segment.byteRange.start,d=l-o+1;if(d<=0||h+d>a.data.byteLength)return void t.error(new Error("Direct media chunk range is invalid"));const c=new Uint8Array(a.data,h,d).slice();"p2p"===a.source?s.p2pBytes+=c.byteLength:s.cdnBytes+=c.byteLength,t.enqueue(c)},cancel:()=>{n=!0}}),bytes:e.end-e.start+1,status:206,headers:{"accept-ranges":"bytes","content-length":String(e.end-e.start+1),"content-range":`bytes ${e.start}-${e.end}/${t.contentLength}`,"content-type":t.contentType},source:"cdn",transferStats:s}}async loadDirectFileChunk(e){const t=this.ensureDirectFileChunk(e);return this.enqueueDirectFileLoad(async()=>{await this.resetInitialCoreRequestWindow();let e=this.core;if(e.isSegmentLoadable(t.runtimeId)||(await this.ensureCoreState(),e=this.core),!e.isSegmentLoadable(t.runtimeId))return void(this.runtimeIdMisses+=1);const s=await this.loadSegmentFromCore(e,t.runtimeId,this.requestTimeoutMs);if(s&&s.byteLength===t.byteRange.end-t.byteRange.start+1)return this.segmentLoadSuccesses+=1,{segment:t,data:s,source:this.completedSources.get(t.runtimeId)??"cdn"};this.segmentLoadTimeouts+=1})}async enqueueDirectFileLoad(e){const t=this.directFileLoadQueue.then(e,e);return this.directFileLoadQueue=t.then(()=>{},()=>{}),t}async resetInitialCoreRequestWindow(){this.disposed||this.hasIssuedCoreLoad||(this.hasIssuedCoreLoad=!0,this.coreGeneration+=1,this.core.destroy(),this.peerCount=0,this.peerInfoHashes.clear(),this.completedSources.clear(),this.core=this.createCore(this.trackerCandidates[this.activeTrackerIndex]),this.bindCoreEvents(),this.coreReady=this.scheduleCoreRebuild(),await this.coreReady)}ensureDirectFileChunk(e){const t=this.directFile;if(!t)throw new Error("Direct media metadata is unavailable");const s=this.directChunks.get(e);if(s)return this.directChunks.delete(e),this.directChunks.set(e,s),s;const i=[];for(;this.directChunks.size>=256;){const e=this.directChunks.entries().next();if(e.done)break;this.directChunks.delete(e.value[0]),i.push(e.value[1].runtimeId),this.completedSources.delete(e.value[1].runtimeId),this.playbackPositionsByRuntimeId.delete(e.value[1].runtimeId)}const r=e*eb,n=Math.min(r+eb-1,t.contentLength-1),a={runtimeId:`${this.manifestUrl}|${r}-${n}`,externalId:e,url:this.manifestUrl,byteRange:{start:r,end:n},startTime:e,endTime:e+1};return this.directChunks.set(e,a),this.playbackPositionsByRuntimeId.set(a.runtimeId,e),this.core.addStreamIfNoneExists({runtimeId:t.streamId,type:"main",index:t.streamIndex}),this.core.updateStream(t.streamId,[a],i),this.indexedSegments=this.directChunks.size,a}loadSegmentFromCore(e,t,s){return new Promise(i=>{let r=!1;const n=e=>{r||(r=!0,clearTimeout(a),i(e))},a=globalThis.setTimeout(()=>{e.abortSegmentLoading(t),n(void 0)},s);try{const s=this.playbackPositionsByRuntimeId.get(t)??-1,i={onSuccess:e=>n(e.data),onError:()=>n(void 0)};e.updatePlayback(s,1),e.loadSegment(t,i)}catch{n(void 0)}})}async refreshPlaylists(){const e=Date.now(),t=[...this.streams.values()].filter(t=>t.isLive&&e-t.lastLoadedAtMs>=2e3).map(e=>e.url);await Promise.all(t.map(e=>this.indexPlaylist(e,new Set)))}async indexPlaylist(e,t,s,i=this.core,r=this.coreGeneration){const n=new URL(e,this.manifestUrl).toString();if(t.has(n)||this.disposed||r!==this.coreGeneration||i!==this.core)return;t.add(n);const a="undefined"!=typeof AbortController?new AbortController:void 0,o=a?globalThis.setTimeout(()=>a.abort(),5e3):void 0,l=await(this.manifestRequestSetup?.(n,void 0,a?.signal,void 0));let h;try{h=await fetch(l??new Request(n,{signal:a?.signal}))}finally{void 0!==o&&globalThis.clearTimeout(o)}if(!h.ok)return;const d=await h.text();if(this.disposed||r!==this.coreGeneration||i!==this.core)return;const c=function(e,t,s,i){const r=e.split(/\r?\n/),n=[],a=[];let o,l,h=0,d=0,c=0,u=0,f=0,g=!0;for(let e=0;e<r.length;e+=1){const s=r[e].trim();if(!s)continue;if(s.startsWith("#EXT-X-MEDIA-SEQUENCE:")){d=Number(s.slice(22))||0,c=d;continue}if("#EXT-X-ENDLIST"===s){g=!1;continue}if(s.startsWith("#EXTINF:")){u=Number(s.slice(8).split(",")[0])||0;continue}if(s.startsWith("#EXT-X-BYTERANGE:")){l=nb(s.slice(17));continue}if(s.startsWith("#EXT-X-STREAM-INF:")){o=rb(s.slice(18));continue}if(s.startsWith("#EXT-X-MEDIA:")){const e=rb(s.slice(13));e.URI&&n.push({url:new URL(e.URI,t).toString(),index:i({bitrate:0,codecs:e.CODECS,language:e.LANGUAGE,channels:e.CHANNELS,name:e.NAME})});continue}if(s.startsWith("#"))continue;const m=new URL(s,t).toString();if(o){n.push({url:m,index:ib(o,i)}),o=void 0;continue}const p=l?{start:l.offset??h,end:(l.offset??h)+l.length-1}:void 0;p&&(h=p.end+1),l=void 0;const v=p?`${m}|${p.start}-${p.end}`:m;a.push({runtimeId:v,url:m,externalId:c,byteRange:p,startTime:f,endTime:f+u}),c+=1,f+=u}return{children:n,segments:a,isLive:g}}(d,n,0,this.streamIdFactory);if(c.children.length)await Promise.all(c.children.map(e=>this.indexPlaylist(e.url,t,e,i,r)));else if(!this.disposed&&r===this.coreGeneration&&i===this.core){i.addStreamIfNoneExists({runtimeId:n,type:"main",index:s?.index??this.streamIdFactory({bitrate:0})}),this.playbackIsLive=c.isLive,i.setIsLive(c.isLive),i.updateStream(n,c.segments),this.streams.set(n,{url:n,isLive:c.isLive,lastLoadedAtMs:Date.now()});for(const e of c.segments)this.segmentIdsByRequestKey.set(ab(e.url,e.byteRange),e.runtimeId),this.playbackPositionsByRuntimeId.set(e.runtimeId,e.startTime);this.indexedSegments=this.segmentIdsByRequestKey.size}}};function ib(e,t){const s=e.RESOLUTION?.split("x");return t({bitrate:Number(e["AVERAGE-BANDWIDTH"]??e.BANDWIDTH)||0,codecs:e.CODECS,width:Number(s?.[0])||void 0,height:Number(s?.[1])||void 0,frameRate:e["FRAME-RATE"],videoRange:e["VIDEO-RANGE"]})}function rb(e){const t={};for(const s of e.matchAll(/([A-Z0-9-]+)=("[^"]*"|[^,]*)/g))t[s[1]]=s[2].replace(/^"|"$/g,"");return t}function nb(e){const[t,s]=e.split("@"),i=Number(t);if(!Number.isFinite(i)||i<=0)return;const r=void 0===s?void 0:Number(s);return{length:i,...Number.isFinite(r)?{offset:r}:{}}}function ab(e,t){const s=t instanceof Headers?ob(t.get("range")):t;return s?`${e}|${s.start}-${s.end}`:e}function ob(e){const t=/^bytes=(\d+)-(\d+)$/.exec(e??"");if(t)return{start:Number(t[1]),end:Number(t[2])}}function lb(e,t){const s=/^bytes=(\d+)-(\d*)$/i.exec(e?.trim()??"");if(!s)return;const i=Number(s[1]);if(!Number.isSafeInteger(i)||i<0||i>=t)return;const r=s[2]?Number(s[2]):t-1;return!Number.isSafeInteger(r)||r<i?void 0:{start:i,end:Math.min(r,t-1)}}function hb(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function db(e){return e.headers.get("content-type")?.split(";")[0]?.trim()||"video/mp4"}async function cb(e){try{await(e.body?.cancel())}catch{}}function ub(e){return Number.isFinite(e)?Math.max(100,Math.floor(e)):5e3}function fb(e){try{e()}catch{}}function gb(e,t=!1){if(t&&!e)return"SDK_CONFIG_PENDING";switch(e?.status?.reason){case"KEY_P2P_DISABLED":return"KEY_P2P_DISABLED";case"QUOTA_EXHAUSTED":return"QUOTA_EXHAUSTED";case"QUOTA_DISABLED":return"QUOTA_DISABLED";default:return"SDK_CONFIG_UNAVAILABLE"}}W(),Z();var mb=class{key;url;video;options;ownsHlsInstance;hls;p2p;serviceWorkerClient;serviceWorkerSession;serviceWorkerP2pEngine;serviceWorkerStats={};serviceWorkerReportUrl;serviceWorkerReportTimer;serviceWorkerReportInFlight=!1;serviceWorkerReportTask;serviceWorkerTeardownTask;serviceWorkerHasReportedContext=!1;serviceWorkerTrackerUrl;serviceWorkerAppId;serviceWorkerKeyId;serviceWorkerSwarmId;serviceWorkerUploadSlots=0;serviceWorkerDownloadSlots=0;serviceWorkerPagehideHandler=()=>{this.reportServiceWorkerStats()};sessionId="";sessionTokenManager;mode="unsupported";p2pEnabledOverride;eventListeners=new Set;p2pListenerBindings=new Map;fallbackStatsTimer;cdnStats={};p2pStatsCdnBaseline={};cdnStatsHls;cdnFragLoadingHandler=()=>{this.cdnStats.httpAttempts=(this.cdnStats.httpAttempts??0)+1};cdnFragLoadedHandler=(e,t)=>{const s=t,i=Number(s?.stats?.loaded);Number.isFinite(i)&&i>0&&(this.cdnStats.httpDownloaded=(this.cdnStats.httpDownloaded??0)+i,this.cdnStats.lastLoadedBytes=i),this.cdnStats.httpSegmentDownloadSuccesses=(this.cdnStats.httpSegmentDownloadSuccesses??0)+1};cdnFragLoadErrorHandler=()=>{this.cdnStats.httpSegmentDownloadFailures=(this.cdnStats.httpSegmentDownloadFailures??0)+1,this.cdnStats.httpErrors=(this.cdnStats.httpErrors??0)+1};playbackState="idle";lifecycle=new NE;startPromise;startResult;bootstrapUpgradeTask;constructor(e){this.key=e.key?.trim()||"",this.url=e.url.trim(),this.video=e.video,this.options=e,this.ownsHlsInstance=!e.hlsjsInstance}get p2pClient(){return this.p2p}get playbackMode(){return this.mode}start(){if(this.startResult)return Promise.resolve(this.startResult);if(this.startPromise)return this.startPromise;this.setPlaybackState("initializing");const e=this.startInternal(this.lifecycle.begin());return this.startPromise=e,e.then(t=>{this.startPromise===e&&(this.startResult=t)}).finally(()=>{this.startPromise===e&&(this.startPromise=void 0)}).catch(()=>{}),e}async startInternal(e){if(!this.options.key?.trim())throw new Error("MeshStreamHlsPlayer requires key");if(!this.url)throw new Error("MeshStreamHlsPlayer requires url");this.teardown();const t=this.options.dependencies??{},s=this.effectiveP2pEnabled(),i=await async function(e,t,s={},i=0){const r=Promise.resolve().then(()=>e(t,s)).catch(()=>{}),n=(a=i,Number.isFinite(a)?Math.max(0,Math.min(2e3,Math.floor(a))):0);var a;let o;const l=new Promise(e=>{o=setTimeout(()=>e({timedOut:!0}),n),o.unref?.()});try{return await Promise.race([r.then(e=>({config:e,timedOut:!1})),l.then(e=>({...e,pending:r}))])}finally{void 0!==o&&clearTimeout(o)}}(t.loadSdkConfig??kE,{bootstrapUrl:this.options.bootstrapUrl,key:this.options.key,platform:"web",contentId:(r=this.options.contentId,n=this.url,r?.trim()||P(n))},void 0,0);var r,n;const a=i.config;this.lifecycle.assertCurrent(e);const o=a?.applicationId?.trim()||this.key,l=a?.keyId?.trim()||void 0,h=`web-${globalThis.crypto?.randomUUID?.()??Math.random().toString(36).slice(2)}`;this.sessionId=h,this.sessionTokenManager=a?.accessUrl?new $E({accessUrl:a.accessUrl,appId:o,keyId:l,sessionId:h,platform:"web"}):void 0;const d=Eb(this.options.mimeType,this.url);if(d&&this.options.hlsjsInstance)throw new Error("hlsjsInstance can only be used with HLS playback");const c=(t.detectCapability??(()=>function(e={}){const t=e.protocol??"hls",s=e.userAgent??("undefined"==typeof navigator?"":navigator.userAgent),i=function(e){const t=e.toLowerCase();return t.includes("edg/")?"edge":t.includes("firefox/")?"firefox":t.includes("chrome/")||t.includes("crios/")||t.includes("chromium/")?"chrome":t.includes("safari/")&&t.includes("version/")?"safari":"unknown"}(s),r=function(e){const t=e.toLowerCase();return t.includes("iphone")||t.includes("ipad")||t.includes("ipod")?"ios":t.includes("android")?"android":t.includes("mac os x")||t.includes("macintosh")?"macos":t.includes("windows")?"windows":"unknown"}(s),n=bE(e.hasWebSocket,EE("WebSocket"))&&bE(e.hasRtcPeerConnection,EE("RTCPeerConnection")||EE("webkitRTCPeerConnection"))&&bE(e.hasRtcDataChannel,function(){const e=globalThis,t=e.RTCPeerConnection??e.webkitRTCPeerConnection;return"function"==typeof t?.prototype?.createDataChannel}()),a=bE(e.hasMediaSource,EE("MediaSource")||EE("ManagedMediaSource")),o=bE(e.hasSecureContext,"undefined"==typeof isSecureContext||isSecureContext),l=bE(e.hasServiceWorker,"undefined"!=typeof navigator&&"serviceWorker"in navigator)&&o;if(!n)return{supported:!1,reason:"WEBRTC_UNSUPPORTED",recommendedMode:"cdn",browser:i,os:r,mseSupported:a,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o};if("hls"===t&&!a){const e="safari"===i&&"ios"===r;return{supported:!1,reason:e?"SAFARI_HLS_MSE_UNSUPPORTED":"MSE_UNSUPPORTED",recommendedMode:e?"native-hls-cdn":"cdn",browser:i,os:r,mseSupported:!1,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o}}return{supported:!0,recommendedMode:"p2p",browser:i,os:r,mseSupported:a,webrtcSupported:n,serviceWorkerSupported:l,secureContext:o}}({protocol:bb(this.options.mimeType,this.url)??"hls"})))(),u=this.options.transportPreference??"auto";if(d)return this.startDirectFilePlayback(c,a,i.timedOut,t,o,l,u,s,e);if("cdn"===u)return this.startCdnFallback(c,a,t,e,"P2P_DISABLED");if(!c.supported){const s={appId:o,keyId:l,streamUrl:this.url,contentId:this.options.contentId,protocol:"hls",playerType:"native-hls-cdn"===c.recommendedMode?"native":"hlsjs",sdkConfig:a,sessionId:h,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,capability:c};if(t.reportFallback?await t.reportFallback({...s,sessionToken:await(this.sessionTokenManager?.getSessionToken())}):xE({...s,sessionTokenProvider:()=>this.sessionTokenManager?.getSessionToken()}),this.lifecycle.assertCurrent(e),!this.options.hlsjsInstance&&"mse"!==u&&("service-worker"===u||"MSE_UNSUPPORTED"===c.reason||"SAFARI_HLS_MSE_UNSUPPORTED"===c.reason)){const s=await this.startServiceWorkerFallback(c,a,i.timedOut,t,e);if(s.playback)return s.playback}return this.startCdnFallback(c,a,t,e,"CAPABILITY_UNSUPPORTED")}if("service-worker"===u){const s=await this.startServiceWorkerFallback(c,a,i.timedOut,t,e);return s.playback?s.playback:this.startCdnFallback(c,a,t,e,s.fallbackReason??"P2P_INITIALIZATION_FAILED")}if(!1===s)return this.startCdnFallback(c,a,t,e,"P2P_DISABLED");if(!ME(a))return this.startCdnFallback(c,a,t,e,gb(a,i.timedOut),i.pending);const g=I(void 0,a.trackerUrls,o,this.options.contentId?.trim()?`${D(this.options.contentId)}-b${a.defaults?.swarmBucketId??0}`:F(this.url,h,a.defaults?.swarmBucketCount,a.defaults?.swarmBucketId),l,a.primaryTrackerUrl),m=(await Promise.all(g.map(e=>this.sessionTokenManager?this.sessionTokenManager.getTrackerUrl(e):Promise.resolve(e)))).filter(e=>Boolean(e?.trim()));this.lifecycle.assertCurrent(e);const p=m[0];if(!p)return this.startCdnFallback(c,a,t,e,"TRACKER_UNAVAILABLE");const v=this.options.hlsjsInstance??await(t.createHls??vb)(this.options.hlsConfig);let y;this.lifecycle.isCurrent(e)||(this.options.hlsjsInstance||v.destroy(),this.lifecycle.assertCurrent(e)),this.options.hlsjsInstance||this.options.onHlsCreated?.(v);try{y=await(t.createP2pClient??Sb)({hlsjsInstance:v,streamUrl:this.url,sdkConfig:{...a,trackerUrls:m},appId:o,sessionId:h,trackerUrl:p,networkType:this.options.networkType,liveWindowBucket:this.options.liveWindowBucket,p2pEnabled:s??a?.p2pEnabled,contentId:this.options.contentId,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,httpDownloadInitialTimeoutMs:this.options.httpDownloadInitialTimeoutMs,uploadSlots:a?.defaults?.uploadSlots,downloadSlots:a?.defaults?.downloadSlots,iceServers:this.options.iceServers,capability:c,logLevel:this.options.logLevel,sessionTokenManager:this.sessionTokenManager}),Object.assign(v.config,y.getHlsConfig()),f(v.config,this.options.originHeaders,this.options.originHeadersProvider),this.lifecycle.isCurrent(e)||(y?.dispose(),this.options.hlsjsInstance||v.destroy(),this.lifecycle.assertCurrent(e))}catch(s){if(y?.dispose(),this.options.hlsjsInstance||v.destroy(),!this.lifecycle.isCurrent(e))throw s;return this.startCdnFallback(c,a,t,e,"P2P_INITIALIZATION_FAILED")}return this.options.hlsjsInstance?this.hls=v:this.attachHls(v,this.url),this.p2pStatsCdnBaseline={...this.cdnStats},this.unbindCdnStats(),this.p2p=y,this.stopFallbackStatsNotifications(),this.bindEventListeners(y),this.mode="p2p-hls",this.setPlaybackState("connecting"),{mode:this.mode,capability:c,sdkConfig:a}}statistics(){if(this.p2p){const e=this.p2p.statistics();return q({...e,httpDownloaded:(this.p2pStatsCdnBaseline.httpDownloaded??0)+(e.httpDownloaded??0),httpAttempts:(this.p2pStatsCdnBaseline.httpAttempts??0)+(e.httpAttempts??0),httpErrors:(this.p2pStatsCdnBaseline.httpErrors??0)+(e.httpErrors??0),httpSegmentDownloadSuccesses:(this.p2pStatsCdnBaseline.httpSegmentDownloadSuccesses??0)+(e.httpSegmentDownloadSuccesses??0),httpSegmentDownloadFailures:(this.p2pStatsCdnBaseline.httpSegmentDownloadFailures??0)+(e.httpSegmentDownloadFailures??0),lastLoadedBytes:e.lastLoadedBytes??this.p2pStatsCdnBaseline.lastLoadedBytes})}const e=this.serviceWorkerP2pEngine?.diagnostics();return q({...this.cdnStats,...this.serviceWorkerStats,connectedPeers:e?.connectedPeers??0,trackerErrors:e?.trackerErrors??0,peerConnectErrors:e?.peerConnectErrors??0,p2pAttempts:e?.p2pAttempts??0,httpAttempts:e?.httpAttempts??this.cdnStats.httpAttempts??0,p2pErrors:e?.p2pErrors??0,httpErrors:e?.httpErrors??this.cdnStats.httpErrors??0,p2pUploaded:e?.p2pUploaded??0,p2pSegmentUploadSuccesses:e?.p2pSegmentUploadSuccesses??0,p2pSegmentUploadFailures:e?.p2pSegmentUploadFailures??0,lastLoadedBytes:e?.lastLoadedBytes??this.cdnStats.lastLoadedBytes??0})}diagnostics(){return this.p2p?this.p2p.diagnostics():{...this.serviceWorkerClient?.diagnostics(),...this.serviceWorkerP2pEngine?.diagnostics()}}qoe(){const e=this.statistics(),t=this.diagnostics();return function(e,t,s){const i=Math.max(0,t.p2pDownloaded),r=Math.max(0,t.httpDownloaded),n=i+r;return{state:e,downloadedBytes:n,p2pDownloadedBytes:i,cdnDownloadedBytes:r,p2pDownloadRatio:n>0?i/n:0,connectedPeers:Math.max(0,t.connectedPeers),...void 0!==s.firstPeerConnectMs?{firstPeerConnectMs:s.firstPeerConnectMs}:{},fallbackCount:Math.max(0,s.fallbackCount??0),...s.coldStart?{coldStartCdnBytes:Math.max(0,s.coldStart.httpDownloaded)}:{},...void 0!==s.liveLatency?.lastLatencyMs?{liveLatencyMs:Math.max(0,s.liveLatency.lastLatencyMs)}:{},...void 0!==s.liveLatency?.lastTargetLatencyMs?{liveTargetLatencyMs:Math.max(0,s.liveLatency.lastTargetLatencyMs)}:{},...void 0!==s.liveLatency?.lastMaxLatencyMs?{liveMaxLatencyMs:Math.max(0,s.liveLatency.lastMaxLatencyMs),...void 0!==s.liveLatency.lastLatencyMs?{liveLatencyOverMax:s.liveLatency.lastLatencyMs>s.liveLatency.lastMaxLatencyMs}:{}}:{}}}(this.resolveQoePlaybackState(e,t),e,t)}setP2pEnabled(e){this.p2pEnabledOverride=e,this.p2p?.setP2pEnabled(e),this.serviceWorkerP2pEngine?.setP2pEnabled(e),e||this.setPlaybackState("cdn-fallback")}addEventListener(e){this.eventListeners.add(e);try{e.onPlaybackStateChanged?.(this.playbackState)}catch{}return this.p2p?.addEventListener(e),this.serviceWorkerP2pEngine?.addEventListener(e),"unsupported"===this.mode||this.p2p||this.serviceWorkerP2pEngine||this.startFallbackStatsNotifications(),()=>this.removeEventListener(e)}dispose(){this.serviceWorkerTeardownTask||(this.lifecycle.cancel(),this.bootstrapUpgradeTask=void 0,this.startPromise=void 0,this.startResult=void 0,this.serviceWorkerP2pEngine&&this.serviceWorkerReportUrl?(this.stopServiceWorkerReporting(),this.serviceWorkerTeardownTask=this.flushServiceWorkerReport().catch(()=>{}).finally(()=>this.teardown())):this.teardown(),this.setPlaybackState("disposed"))}teardown(){this.stopServiceWorkerReporting(),this.stopFallbackStatsNotifications(),this.unbindCdnStats();for(const e of Object.keys(this.cdnStats))delete this.cdnStats[e];this.p2p?.dispose(),this.p2pListenerBindings.clear();const e=this.serviceWorkerSession,t=this.serviceWorkerClient;e?e.dispose().catch(()=>{}).finally(()=>t?.dispose()):t?.dispose(),this.serviceWorkerP2pEngine?.dispose(),this.ownsHlsInstance&&this.hls?.destroy(),this.sessionTokenManager?.dispose(),this.p2p=void 0,this.p2pStatsCdnBaseline={},this.serviceWorkerSession=void 0,this.serviceWorkerClient=void 0,this.serviceWorkerP2pEngine=void 0,this.serviceWorkerStats={},this.serviceWorkerReportUrl=void 0,this.serviceWorkerTrackerUrl=void 0,this.serviceWorkerAppId=void 0,this.serviceWorkerKeyId=void 0,this.serviceWorkerSwarmId=void 0,this.serviceWorkerUploadSlots=0,this.serviceWorkerDownloadSlots=0,this.serviceWorkerHasReportedContext=!1,this.hls=void 0,this.sessionTokenManager=void 0,this.mode="unsupported"}startServiceWorkerReporting(e){const t=e?.applicationId?.trim()||this.key,s=e?.keyId?.trim();if(this.serviceWorkerAppId=t,this.serviceWorkerKeyId=s,this.serviceWorkerSwarmId=this.resolveServiceWorkerSwarmId(e),this.serviceWorkerUploadSlots=this.serviceWorkerP2pEngine?pb(e?.defaults?.uploadSlots,4):0,this.serviceWorkerDownloadSlots=this.serviceWorkerP2pEngine?pb(e?.defaults?.downloadSlots,5):0,this.serviceWorkerReportUrl=k(C(e?.reportUrl,{appId:t,keyId:s}))??k(R(this.serviceWorkerTrackerUrl)),!this.serviceWorkerReportUrl)return;const i=j(e?.defaults?.reportIntervalMs);if("undefined"!=typeof window){window.addEventListener("pagehide",this.serviceWorkerPagehideHandler);const e=()=>{this.reportServiceWorkerStats(),this.serviceWorkerReportTimer=window.setInterval(()=>{this.reportServiceWorkerStats()},i)};this.serviceWorkerReportTimer=window.setTimeout(e,K(i))}}bindEventListeners(e){for(const t of this.eventListeners){const s={...t,onStatistics:()=>t.onStatistics?.(this.statistics())};this.p2pListenerBindings.set(t,s),e.addEventListener(s)}}bindServiceWorkerEventListeners(e){for(const t of this.eventListeners)e.addEventListener(t)}completeFallbackStart(e,t,s){this.setPlaybackState("p2p-hls"===this.mode||"sw-hls-p2p"===this.mode?"connecting":"cdn-fallback");const i=function(e){switch(e){case"CAPABILITY_UNSUPPORTED":return"UNSUPPORTED";case"P2P_DISABLED":return"DISABLED";case"SDK_CONFIG_PENDING":default:return;case"SDK_CONFIG_UNAVAILABLE":return"CONFIG_UNAVAILABLE";case"KEY_P2P_DISABLED":return"KEY_P2P_DISABLED";case"QUOTA_EXHAUSTED":return"QUOTA_EXHAUSTED";case"QUOTA_DISABLED":return"QUOTA_DISABLED";case"TRACKER_UNAVAILABLE":return"TRACKER_ERROR";case"P2P_INITIALIZATION_FAILED":return"INITIALIZATION_FAILED"}}(s);if(i)for(const e of this.eventListeners)try{e.onP2pUnavailable?.(i)}catch{}return this.p2p||this.serviceWorkerP2pEngine||this.startFallbackStatsNotifications(),{mode:this.mode,capability:e,sdkConfig:t,fallbackReason:s}}startFallbackStatsNotifications(){void 0===this.fallbackStatsTimer&&0!==this.eventListeners.size&&(this.fallbackStatsTimer=globalThis.setInterval(()=>{const e=this.statistics();for(const t of this.eventListeners)try{t.onStatistics?.(e)}catch{}},1e3),this.fallbackStatsTimer.unref?.())}stopFallbackStatsNotifications(){void 0!==this.fallbackStatsTimer&&(globalThis.clearInterval(this.fallbackStatsTimer),this.fallbackStatsTimer=void 0)}removeEventListener(e){if(!this.eventListeners.delete(e))return;const t=this.p2pListenerBindings.get(e);t&&(this.p2p?.removeEventListener(t),this.p2pListenerBindings.delete(e)),this.serviceWorkerP2pEngine?.removeEventListener(e),0===this.eventListeners.size&&this.stopFallbackStatsNotifications()}setPlaybackState(e){if(this.playbackState!==e){this.playbackState=e;for(const t of this.eventListeners)try{t.onPlaybackStateChanged?.(e)}catch{}}}resolveQoePlaybackState(e,t){return"connecting"!==this.playbackState?this.playbackState:e.connectedPeers>0?"p2p-ready":void 0===t.firstPeerConnectMs?"connecting":"cdn-fallback"}stopServiceWorkerReporting(){void 0!==this.serviceWorkerReportTimer&&"undefined"!=typeof window&&window.clearInterval(this.serviceWorkerReportTimer),"undefined"!=typeof window&&window.removeEventListener("pagehide",this.serviceWorkerPagehideHandler),this.serviceWorkerReportTimer=void 0}async flushServiceWorkerReport(){await this.serviceWorkerReportTask,await this.reportServiceWorkerStats()}reportServiceWorkerStats(){if(!this.serviceWorkerReportUrl||!this.serviceWorkerP2pEngine?.isPlaybackModeKnown())return Promise.resolve();if(this.serviceWorkerReportTask)return this.serviceWorkerReportTask;this.serviceWorkerReportInFlight=!0;const e=(async()=>{try{const e=this.statistics(),t=this.serviceWorkerP2pEngine?.diagnostics(),s=await z(this.serviceWorkerReportUrl,V({platform:"web",playbackMode:!0===this.serviceWorkerP2pEngine?.isLive()?"live":"vod",runtimeMode:"service-worker",protocol:bb(this.options.mimeType,this.url)??"hls",playerType:Eb(this.options.mimeType,this.url)||this.canPlayNativeHls()?"native":"hlsjs",sdkVersion:Q,appId:this.serviceWorkerAppId,keyId:this.serviceWorkerKeyId,sessionId:this.sessionId,contentId:M(this.options.contentId,this.url),swarmId:this.serviceWorkerSwarmId??this.resolveServiceWorkerSwarmId(void 0),playbackUrl:this.url,stats:e,load:{uploadSlots:this.serviceWorkerUploadSlots,activeUploadPeers:Math.min(e.connectedPeers,this.serviceWorkerUploadSlots),downloadSlots:this.serviceWorkerDownloadSlots,activeDownloadPeers:Math.min(e.connectedPeers,this.serviceWorkerDownloadSlots)},diagnostics:{fallbackCount:t?.fallbackCount??(e.httpDownloaded>0&&0===e.p2pDownloaded?1:0),firstPeerConnectMs:t?.firstPeerConnectMs,ice:t?.ice,auth:this.sessionTokenManager?.diagnostics(),...t?.trackerErrors?{lastTrackerError:`tracker-errors:${t.trackerErrors}`}:{},...t?.lastPeerError?{lastPeerError:t.lastPeerError}:t?.peerConnectErrors?{lastPeerError:`peer-connect-errors:${t.peerConnectErrors}`}:{},...t?.lastErrorAtMs?{lastErrorAtMs:t.lastErrorAtMs}:{}}},!this.serviceWorkerHasReportedContext),{authorizationHeader:await(this.sessionTokenManager?.getAuthorizationHeader())});s?.ok&&(this.serviceWorkerHasReportedContext=!0)}catch{}})();return this.serviceWorkerReportTask=e,e.finally(()=>{this.serviceWorkerReportTask===e&&(this.serviceWorkerReportTask=void 0,this.serviceWorkerReportInFlight=!1)}),e}async startDirectFilePlayback(e,t,s,i,r,n,a,o,l){if("cdn"===a||"mse"===a||!1===o)return this.startDirectFileCdnFallback(e,t,l,"P2P_DISABLED");if(!e.supported){this.lifecycle.assertCurrent(l);const s={appId:r,keyId:n,streamUrl:this.url,contentId:this.options.contentId,protocol:bb(this.options.mimeType,this.url)??"mp4",playerType:"native",sdkConfig:t,sessionId:this.sessionId,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,capability:e};return i.reportFallback?await i.reportFallback({...s,sessionToken:await(this.sessionTokenManager?.getSessionToken())}):xE({...s,sessionTokenProvider:()=>this.sessionTokenManager?.getSessionToken()}),this.lifecycle.assertCurrent(l),this.startDirectFileCdnFallback(e,t,l,"CAPABILITY_UNSUPPORTED")}const h=this.options.serviceWorker;if(!(i.isServiceWorkerSupported??zE)())return this.startDirectFileCdnFallback(e,t,l,"CAPABILITY_UNSUPPORTED");let d,c,u,f;try{!1!==h?.autoRegister&&(d=await(i.registerServiceWorker??QE)({url:h?.url,scope:h?.scope,readyTimeoutMs:h?.readyTimeoutMs}),this.lifecycle.isCurrent(l)||(d.dispose(),this.lifecycle.assertCurrent(l))),h?.segmentProvider||(f=await this.createServiceWorkerP2pEngine(t,l,s),u=f.engine),c=await(i.createServiceWorkerSession??XE)({serviceWorker:d,manifestUrl:this.url,resourceKind:"direct-file",originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,p2pTimeoutMs:h?.p2pTimeoutMs,segmentProvider:h?.segmentProvider??u?.createSegmentProvider(),onSegmentStats:e=>this.recordServiceWorkerSegmentStats(e)}),this.lifecycle.isCurrent(l)||(u?.dispose(),d?.dispose(),c?.dispose().catch(()=>{}),this.lifecycle.assertCurrent(l))}catch(s){if(u?.dispose(),d?.dispose(),!this.lifecycle.isCurrent(l))throw s;return this.startDirectFileCdnFallback(e,t,l,"P2P_INITIALIZATION_FAILED")}return c?(this.serviceWorkerClient=d,this.serviceWorkerSession=c,this.serviceWorkerP2pEngine=u,u&&(this.stopFallbackStatsNotifications(),this.bindServiceWorkerEventListeners(u)),this.startServiceWorkerReporting(t),this.video.src=c.manifestUrl,await this.autoplay(),this.lifecycle.assertCurrent(l),this.mode=u?"sw-direct-p2p":"sw-direct-cdn",this.completeFallbackStart(e,t,f?.fallbackReason)):(u?.dispose(),d?.dispose(),this.startDirectFileCdnFallback(e,t,l,"P2P_INITIALIZATION_FAILED"))}async startDirectFileCdnFallback(e,t,s,i){return this.lifecycle.assertCurrent(s),c(this.options.originHeaders,this.options.originHeadersProvider)?(this.mode="unsupported",this.completeFallbackStart(e,t,i)):(this.video.src=this.url,this.mode="cdn-direct",await this.autoplay(),this.lifecycle.assertCurrent(s),this.completeFallbackStart(e,t,i))}recordServiceWorkerSegmentStats(e){const t=e.status>=200&&e.status<400,s=Math.min(e.bytes,Math.max(0,e.p2pBytes??("p2p"===e.source?e.bytes:0))),i=Math.min(e.bytes-s,Math.max(0,e.cdnBytes??("cdn"===e.source?e.bytes:0)));t?(s>0&&(this.serviceWorkerStats.p2pDownloaded=(this.serviceWorkerStats.p2pDownloaded??0)+s,this.serviceWorkerStats.p2pSegmentDownloadSuccesses=(this.serviceWorkerStats.p2pSegmentDownloadSuccesses??0)+1),i>0&&(this.serviceWorkerStats.httpDownloaded=(this.serviceWorkerStats.httpDownloaded??0)+i,this.serviceWorkerStats.httpSegmentDownloadSuccesses=(this.serviceWorkerStats.httpSegmentDownloadSuccesses??0)+1)):"p2p"===e.source?this.serviceWorkerStats.p2pSegmentDownloadFailures=(this.serviceWorkerStats.p2pSegmentDownloadFailures??0)+1:this.serviceWorkerStats.httpSegmentDownloadFailures=(this.serviceWorkerStats.httpSegmentDownloadFailures??0)+1;try{this.options.serviceWorker?.onSegmentStats?.(e)}catch{}}async startServiceWorkerFallback(e,t,s,i,r){const n=this.options.serviceWorker,a=i.isServiceWorkerSupported??zE;if(!n&&!1===e.serviceWorkerSupported)return{fallbackReason:"CAPABILITY_UNSUPPORTED"};if(!a())return{fallbackReason:"CAPABILITY_UNSUPPORTED"};const o=i.hlsIsSupported??yb,l=await o();if(this.lifecycle.assertCurrent(r),!l&&!this.canPlayNativeHls()&&!this.options.loadExternalHls)return{fallbackReason:"CAPABILITY_UNSUPPORTED"};let h,d,c,u;try{n?.autoRegister&&(h=await(i.registerServiceWorker??QE)({url:n.url,scope:n.scope,readyTimeoutMs:n.readyTimeoutMs}),this.lifecycle.isCurrent(r)||(h.dispose(),this.lifecycle.assertCurrent(r))),n?.segmentProvider||(u=await this.createServiceWorkerP2pEngine(t,r,s),c=u.engine),d=await(i.createServiceWorkerSession??XE)({serviceWorker:h,manifestUrl:this.url,resourceKind:"hls",originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,p2pTimeoutMs:n?.p2pTimeoutMs,segmentProvider:n?.segmentProvider??c?.createSegmentProvider(),onSegmentStats:e=>this.recordServiceWorkerSegmentStats(e)}),this.lifecycle.isCurrent(r)||(c?.dispose(),h?.dispose(),d?.dispose().catch(()=>{}),this.lifecycle.assertCurrent(r))}catch(e){if(c?.dispose(),h?.dispose(),!this.lifecycle.isCurrent(r))throw e;return{fallbackReason:"P2P_INITIALIZATION_FAILED"}}if(!d)return c?.dispose(),h?.dispose(),{fallbackReason:"P2P_INITIALIZATION_FAILED"};if(this.serviceWorkerClient=h,this.serviceWorkerSession=d,this.serviceWorkerP2pEngine=c,c&&(this.stopFallbackStatsNotifications(),this.bindServiceWorkerEventListeners(c)),this.startServiceWorkerReporting(t),this.options.loadExternalHls)await this.options.loadExternalHls(d.manifestUrl),this.lifecycle.assertCurrent(r),await this.autoplay(),this.lifecycle.assertCurrent(r);else if(l){const e=await(i.createHls??vb)(this.options.hlsConfig);this.lifecycle.isCurrent(r)||(e.destroy(),this.lifecycle.assertCurrent(r)),this.options.onHlsCreated?.(e),this.attachHls(e,d.manifestUrl)}else this.video.src=d.manifestUrl,await this.autoplay(),this.lifecycle.assertCurrent(r);return this.mode=c?"sw-hls-p2p":"sw-hls-cdn",{playback:this.completeFallbackStart(e,t,u?.fallbackReason)}}async createServiceWorkerP2pEngine(e,t,s=!1){if(!1===this.effectiveP2pEnabled())return{fallbackReason:"P2P_DISABLED"};if(!ME(e))return{fallbackReason:gb(e,s)};const i=e?.applicationId?.trim()||this.key,r=e?.keyId?.trim()||void 0,n=this.resolveServiceWorkerSwarmId(e),a=I(void 0,e?.trackerUrls,i,n,r,e?.primaryTrackerUrl),o=(await Promise.all(a.map(e=>this.sessionTokenManager?this.sessionTokenManager.getTrackerUrl(e):Promise.resolve(e)))).filter(e=>Boolean(e?.trim()));this.lifecycle.assertCurrent(t);const l=o[0];if(!l)return{fallbackReason:"TRACKER_UNAVAILABLE"};let h;this.serviceWorkerTrackerUrl=l;try{return h=await sb.create({manifestUrl:this.url,resourceKind:Eb(this.options.mimeType,this.url)?"direct-file":"hls",swarmId:n,trackerUrl:l,trackerUrls:o,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,iceServers:this.options.iceServers,sdkConfig:e,requestTimeoutMs:this.options.serviceWorker?.p2pTimeoutMs}),this.lifecycle.isCurrent(t)||(h.dispose(),this.lifecycle.assertCurrent(t)),await h.initialize(),this.lifecycle.isCurrent(t)||(h.dispose(),this.lifecycle.assertCurrent(t)),{engine:h}}catch(e){if(h?.dispose(),!this.lifecycle.isCurrent(t))throw e;return{fallbackReason:"P2P_INITIALIZATION_FAILED"}}}resolveServiceWorkerSwarmId(e){const t=e?.defaults?.swarmBucketCount,s=e?.defaults?.swarmBucketId;return this.options.contentId?.trim()?x(D(this.options.contentId),t??1,s??0):F(this.url,this.sessionId,t,s)}async startCdnFallback(e,t,s,i,r,n){if(this.lifecycle.assertCurrent(i),this.options.loadExternalHls)return c(this.options.originHeaders,this.options.originHeadersProvider)?(this.mode="unsupported",this.completeFallbackStart(e,t,r)):(await this.options.loadExternalHls(this.url),this.mode="cdn-hls",await this.autoplay(),this.lifecycle.assertCurrent(i),this.completeFallbackStart(e,t,r));if(this.options.hlsjsInstance){this.hls=this.options.hlsjsInstance,this.bindCdnStats(this.hls),this.mode="cdn-hls";const a=this.completeFallbackStart(e,t,r);return this.scheduleHlsP2pUpgrade(n,e,s,i),a}if(!c(this.options.originHeaders,this.options.originHeadersProvider)&&"native-hls-cdn"===e.recommendedMode)return this.video.src=this.url,this.mode="native-hls-cdn",await this.autoplay(),this.lifecycle.assertCurrent(i),this.completeFallbackStart(e,t,r);const a=s.hlsIsSupported??yb;if(await a()){this.lifecycle.assertCurrent(i);const a=await(s.createHls??vb)(this.options.hlsConfig);this.lifecycle.isCurrent(i)||(a.destroy(),this.lifecycle.assertCurrent(i)),this.options.onHlsCreated?.(a),this.bindCdnStats(a),f(a.config,this.options.originHeaders,this.options.originHeadersProvider),this.attachHls(a,this.url),this.mode="cdn-hls";const o=this.completeFallbackStart(e,t,r);return this.scheduleHlsP2pUpgrade(n,e,s,i),o}return this.mode="unsupported",this.completeFallbackStart(e,t,r)}scheduleHlsP2pUpgrade(e,t,s,i){if(!e||!1===this.effectiveP2pEnabled()||!t.supported)return;const r=e.then(e=>{if(e)return this.upgradeExistingHlsSession(e,t,s,i)}).catch(()=>{});this.bootstrapUpgradeTask=r}async upgradeExistingHlsSession(e,t,s,i){if(!this.lifecycle.isCurrent(i)||"cdn-hls"!==this.mode||this.p2p||!this.hls)return;if(!ME(e))return;const r=e.applicationId?.trim()||this.key,n=e.keyId?.trim()||void 0,a=e.accessUrl?new $E({accessUrl:e.accessUrl,appId:r,keyId:n,sessionId:this.sessionId,platform:"web"}):void 0,o=this.sessionTokenManager;this.sessionTokenManager=a,o?.dispose();const l=I(void 0,e.trackerUrls,r,this.options.contentId?.trim()?`${D(this.options.contentId)}-b${e.defaults?.swarmBucketId??0}`:F(this.url,this.sessionId,e.defaults?.swarmBucketCount,e.defaults?.swarmBucketId),n,e.primaryTrackerUrl),h=(await Promise.all(l.map(e=>this.sessionTokenManager?this.sessionTokenManager.getTrackerUrl(e):Promise.resolve(e)))).filter(e=>Boolean(e?.trim()));this.lifecycle.assertCurrent(i);const d=h[0];if(!d||!this.hls)return;let c;try{if(c=await(s.createP2pClient??Sb)({hlsjsInstance:this.hls,streamUrl:this.url,sdkConfig:{...e,trackerUrls:h},appId:r,sessionId:this.sessionId,trackerUrl:d,networkType:this.options.networkType,liveWindowBucket:this.options.liveWindowBucket,p2pEnabled:this.effectiveP2pEnabled()??e.p2pEnabled,contentId:this.options.contentId,originHeaders:this.options.originHeaders,originHeadersProvider:this.options.originHeadersProvider,httpDownloadInitialTimeoutMs:this.options.httpDownloadInitialTimeoutMs,uploadSlots:e.defaults?.uploadSlots,downloadSlots:e.defaults?.downloadSlots,iceServers:this.options.iceServers,capability:t,logLevel:this.options.logLevel,sessionTokenManager:this.sessionTokenManager}),Object.assign(this.hls.config,c.getHlsConfig()),f(this.hls.config,this.options.originHeaders,this.options.originHeadersProvider),c.activateExistingHls?.(),!this.lifecycle.isCurrent(i))return void c.dispose()}catch{return void c?.dispose()}this.p2pStatsCdnBaseline={...this.cdnStats},this.unbindCdnStats(),this.p2p=c,this.stopFallbackStatsNotifications(),this.bindEventListeners(c),this.mode="p2p-hls",this.setPlaybackState("connecting"),this.startResult&&(this.startResult={...this.startResult,mode:this.mode,sdkConfig:e})}bindCdnStats(e){this.unbindCdnStats(),this.cdnStatsHls=e,e.on("hlsFragLoading",this.cdnFragLoadingHandler),e.on("hlsFragLoaded",this.cdnFragLoadedHandler),e.on("hlsFragLoadError",this.cdnFragLoadErrorHandler)}unbindCdnStats(){this.cdnStatsHls&&(this.cdnStatsHls.off?.("hlsFragLoading",this.cdnFragLoadingHandler),this.cdnStatsHls.off?.("hlsFragLoaded",this.cdnFragLoadedHandler),this.cdnStatsHls.off?.("hlsFragLoadError",this.cdnFragLoadErrorHandler),this.cdnStatsHls=void 0)}attachHls(e,t){this.hls=e,e.on("hlsManifestParsed",()=>{this.autoplay()}),e.loadSource(t),e.attachMedia(this.video)}async autoplay(){!1!==this.options.autoplay&&await this.video.play().catch(()=>{})}canPlayNativeHls(){return""!==this.video.canPlayType("application/vnd.apple.mpegurl")}effectiveP2pEnabled(){return this.p2pEnabledOverride??this.options.p2pEnabled}};function pb(e,t){return void 0!==e&&Number.isFinite(e)?Math.max(0,Math.floor(e)):t}async function vb(e){return new((await Promise.resolve().then(()=>(tf(),Go))).default)(e)}async function yb(){return(await Promise.resolve().then(()=>(tf(),Go))).default.isSupported()}async function Sb(e){return new((await Promise.resolve().then(()=>(SE(),cE))).HlsP2pClient)(e)}function Eb(e,t){return void 0!==bb(e,t)}function bb(e,t){if("mp4"===e||"mp3"===e)return e;try{const e=new URL(t).pathname.toLowerCase();if(e.endsWith(".mp4"))return"mp4";if(e.endsWith(".mp3"))return"mp3"}catch{const e=t.trim().toLowerCase().split("?")[0]??"";if(e.endsWith(".mp4"))return"mp4";if(e.endsWith(".mp3"))return"mp3"}}export{mb as MeshStreamHlsPlayer};
|