PageSourceSearch

https://limewire.com/build/workers/upload-entry-worker-web.worker-B-_eEOYp.js

js limewire.com collected 2026-09-24 08:25:49 UTC 944,376 bytes, 541 lines download raw bytes

1var oP=Object.defineProperty;var b0=ot=>{throw TypeError(ot)};var cP=(ot,Ke,mt)=>Ke in ot?oP(ot,Ke,{enumerable:!0,configurable:!0,writable:!0,value:mt}):ot[Ke]=mt;var Lt=(ot,Ke,mt)=>cP(ot,typeof Ke!="symbol"?Ke+"":Ke,mt),E0=(ot,Ke,mt)=>Ke.has(ot)||b0("Cannot "+mt);var ve=(ot,Ke,mt)=>(E0(ot,Ke,"read from private field"),mt?mt.call(ot):Ke.get(ot)),Fn=(ot,Ke,mt)=>Ke.has(ot)?b0("Cannot add the same private member more than once"):Ke instanceof WeakSet?Ke.add(ot):Ke.set(ot,mt),ma=(ot,Ke,mt,sn)=>(E0(ot,Ke,"write to private field"),sn?sn.call(ot,mt):Ke.set(ot,mt),mt);(function(){"use strict";var ar,vn,rn,fi,hi,rc,Vt;const ot=r=>{const{baseDelay:e=250,minDelay:t=0,maxDelay:n=1/0,maxRetryCount:i=1/0}=r||{};return s=>{if(!(s>i-1))return Math.max(t,Math.min(n,s&&e*Math.pow(2,s-1)))}},Ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",mt=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Ke.length;r++)mt[Ke.charCodeAt(r)]=r;const sn=r=>{let e=r.length*.75,t=0,n,i,s,a;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const o=new ArrayBuffer(e),c=new Uint8Array(o);for(let l=0;l<r.length;l+=4)n=mt[r.charCodeAt(l)],i=mt[r.charCodeAt(l+1)],s=mt[r.charCodeAt(l+2)],a=mt[r.charCodeAt(l+3)],c[t++]=n<<2|i>>4,c[t++]=(i&15)<<4|s>>2,c[t++]=(s&3)<<6|a&63;return o},an=r=>{const e=new Uint8Array(r),t=e.length;let n="";for(let i=0;i<t;i+=3)n+=Ke[e[i]>>2],n+=Ke[(e[i]&3)<<4|e[i+1]>>4],n+=Ke[(e[i+1]&15)<<2|e[i+2]>>6],n+=Ke[e[i+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},T0=r=>{if(!r)return"";let e=r.replace(/-/g,"+").replace(/_/g,"/");const t=4-e.length%4;return t!==4&&(e+="=".repeat(t)),e},on=()=>{let r,e;const t=new Promise((n,i)=>{r=n,e=i});if(!r||!e)throw new Error("Missing Resolvers");return{promise:t,resolve:r,reject:e}},S0=(...r)=>{const e=r.reduce((n,i)=>n+i.length,0),t=new Uint8Array(e);return r.forEach((n,i)=>{const s=r.slice(0,i).reduce((a,o)=>a+o.length,0);t.set(n,s)}),t},pa=()=>{},Tt=r=>({ok:!0,value:r}),pe=r=>({ok:!1,error:r}),wt=(r,e)=>r instanceof Error?r:typeof DOMException=="function"&&r instanceof DOMException?new Error(`DOMException: ${r.name} ${r.message}`):(typeof e=="function"?e(r):e)||new Error(`${r}`),oc=new WeakMap,os=(r,...e)=>{const t=e.filter(i=>i instanceof AbortSignal);if(!t.length)return;const n=oc.get(r)||new WeakSet;oc.set(r,n);for(const i of t){if(r.signal.aborted)break;if(n.has(i))continue;const s=()=>{r.abort(i.reason),i.removeEventListener("abort",s),oc.delete(r),n.delete(i)};i.aborted?s():(n.add(i),i.addEventListener("abort",s))}},nf=(...r)=>{const e=r.filter(n=>n instanceof AbortSignal);if(!e.length)return;if(typeof AbortSignal.any=="function")return AbortSignal.any(e);const t=new AbortController;return os(t,...e),t.signal};class Dr extends Error{constructor(e,t){super(e.message),this.underlyingError=e,this.response=t}}const sf=async(r,e)=>typeof r=="function"?r(e):r,cc=async(r,e,t)=>{if(typeof r=="number")return r;if(typeof r=="function")return r==null?void 0:r(e,t);if(Array.isArray(r))return r[e]},C0=r=>{if(typeof r=="string")return r;if(r instanceof URL)return r.href;if(r instanceof Request)return r.url;throw new Error("Couldn't get url from input")},I0=(r,e)=>{const{init:t,inspect:n,retry:i,timeout:s}=e||{},{promise:a,resolve:o}=on(),c=new AbortController,l=h=>{o(h),d!==null&&clearTimeout(d),c.signal.aborted||c.abort(h)},u=async h=>{const p=h&&!h.ok&&h.error||null,m=await sf(t,p)||{};os(c,m.signal);const A=await fetch(r,{...m}).then(Tt);return await(n==null?void 0:n(A.value,p))||A};let d=null,f=0;return s&&(d=setTimeout(()=>l(pe(new Dr(new Error(`The extended-fetch timeout of ${s}ms has been exceeded`)))),s)),c.signal.addEventListener("abort",()=>{const{reason:h}=c.signal;l(pe(new Dr(wt(h,new Error(`Extended-fetch aborted: ${h}`)))))}),(async()=>{let h=null;try{for(;!c.signal.aborted&&(h=await u(h).catch(A=>pe(new Dr(wt(A,new Error(`Extended-fetch fetch error: ${A}`))))),!h.ok);){const p=await cc(i,f,h.error).catch(()=>null);if(typeof p!="number")break;const m=Math.max(0,p);m&&await new Promise(A=>setTimeout(A,m)),f++}l(h||pe(new Dr(new Error("No extended-fetch result"))))}catch(p){l(pe(new Dr(new Error(`Extended-fetch error: ${p}`))))}})(),a},ga=(...r)=>{const e={};for(const t of r){if(!t)continue;const n=new Headers(t);for(const[i,s]of n.entries())e[i]=s}return e},af=r=>r instanceof TypeError,B0=r=>new TypeError(wt(r).message),x0=r=>{const{onStalled:e,timeout:t}=r;let n=null;const i=()=>{n!==null&&(clearTimeout(n),n=null)};return{extend:()=>{t&&(i(),n=setTimeout(()=>{e==null||e(),i()},t))},clear:i}},lc=r=>!!r&&r.status>=400&&r.status<500,P0=(r,e,t,n)=>{const{body:i=null,headers:s={},method:a="GET",responseType:o,signal:c,withCredentials:l=!1,progressStall:u=0}=e||{},{promise:d,resolve:f}=on();try{const h=new XMLHttpRequest,{extend:p,clear:m}=x0({timeout:u,onStalled:()=>{h.abort(),A(pe(new or(new Error(`XHR Stalled. (${(u/1e3).toFixed(2)} seconds)`),h)))}}),A=w=>{m(),f(w)},g=()=>A(pe(new or(new DOMException("Aborted","AbortError"))));{const{onAbort:w,onError:b,onLoad:k,onLoadEnd:S,onLoadStart:x,onProgress:B,onTimeout:I}=t||{};w&&h.addEventListener("abort",C=>{w(C)}),b&&h.addEventListener("error",C=>{b(C)}),k&&h.addEventListener("load",C=>{k(C)}),S&&h.addEventListener("loadend",C=>{S(C)}),x&&h.addEventListener("loadstart",C=>{x(C)}),B&&h.addEventListener("progress",C=>{B(C)}),I&&h.addEventListener("timeout",C=>{I(C)})}{const{onAbort:w,onError:b,onLoad:k,onLoadEnd:S,onLoadStart:x,onProgress:B,onTimeout:I}=n||{};w&&h.upload.addEventListener("abort",C=>{w(C)}),b&&h.upload.addEventListener("error",C=>{b(C)}),k&&h.upload.addEventListener("load",C=>{k(C)}),S&&h.upload.addEventListener("loadend",C=>{S(C)}),x&&h.upload.addEventListener("loadstart",C=>{x(C)}),B&&h.upload.addEventListener("progress",C=>{B(C)}),I&&h.upload.addEventListener("timeout",C=>{I(C)})}if(c){const w=()=>{h.abort(),c.removeEventListener("abort",w),g()};c.aborted?w():c.addEventListener("abort",w)}u&&(h.addEventListener("progress",p),h.upload.addEventListener("progress",p)),h.addEventListener("load",()=>{A(Tt(h))}),h.addEventListener("error",()=>{A(pe(new or(new Error("XHR Error"))))}),h.addEventListener("timeout",()=>{A(pe(new or(new Error("XHR Timeout"))))});
1try{h.open(a,r,!0),s&&new Headers(s).forEach((b,k)=>{h.setRequestHeader(k,b)}),h.withCredentials=l,o&&(h.responseType=o),h.send(i)}catch(w){A(pe(new or(wt(w,new Error(`XHR open / send error: ${w}`)))))}}catch(h){f(pe(new or(wt(h,new Error(`XHR error: ${h}`)))))}return d};class or extends Error{constructor(e,t){super(e.message),this.underlyingError=e,this.xhr=t}}const v0=async(r,e)=>typeof r=="function"?r(e):r,_0=async(r,e,t)=>{if(typeof r=="number")return r;if(typeof r=="function")return r==null?void 0:r(e,t);if(Array.isArray(r))return r[e]},F0=async(r,e)=>{const{init:t,inspect:n,retry:i,timeout:s,downloadCallbacks:a,uploadCallbacks:o}=e||{},{promise:c,resolve:l}=on(),u=new AbortController,d=m=>{l(m),h!==null&&clearTimeout(h),u.signal.aborted||u.abort(m)},f=async m=>{const A=m&&!m.ok&&m.error||null,g=await v0(t,A)||{};os(u,g.signal);const w=await P0(r,{...g},a,o);return w.ok&&await(n==null?void 0:n(w.value,A))||w};let h=null,p=0;return s&&(h=setTimeout(()=>d(pe(new or(new Error(`The xhr-fetch timeout of ${s}ms has been exceeded`)))),s)),u.signal.addEventListener("abort",()=>{const{reason:m}=u.signal;d(pe(new or(wt(m,new Error(`Xhr-fetch aborted: ${m}`)))))}),(async()=>{let m=null;try{for(;!u.signal.aborted&&(m=await f(m).catch(w=>pe(new or(wt(w,new Error(`Xhr-fetch error: ${w}`))))),!m.ok);){const A=await _0(i,p,m.error).catch(()=>null);if(typeof A!="number")break;const g=Math.max(0,A);g&&await new Promise(w=>setTimeout(w,g)),p++}d(m||pe(new or(new Error("No xhr-fetch result"))))}catch(A){d(pe(new or(new Error(`Xhr-fetch error: ${A}`))))}})(),c},R0=r=>{try{const{response:e}=r;if(e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||e instanceof ArrayBuffer||e instanceof ReadableStream||typeof e=="string")return e}catch{}return null},D0=r=>{const e={};try{r.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(i=>{const s=i.split(": "),a=s.shift(),o=s.join(": ");a&&(e[a]=o)})}catch{}return e},M0=r=>{try{if(r instanceof Blob||r instanceof FormData||r instanceof URLSearchParams||r instanceof ArrayBuffer||typeof r=="string")return r}catch{}return null},U0=r=>{try{return new Response(R0(r),{headers:D0(r),status:r.status,statusText:r.statusText})}catch{return new Response(null)}},of=r=>{const{xhr:e}=r,t=e&&e.status!==0?r.underlyingError:B0(r.underlyingError.message);return new Dr(t,e?U0(e):void 0)},O0=async(r,e)=>{const t=await sf(r,e?of(e):null)||{};return{body:M0(t.body),headers:t.headers,method:t.method,signal:t.signal,withCredentials:t.credentials!=="omit"}},N0=async(r,e,t)=>await cc(r,e,of(t));class Rn extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.response=n}}const Q0=r=>!!r&&typeof r=="object"&&typeof r.code=="string"&&typeof r.error=="string"&&Object.keys(r).length===2,Aa=async r=>r.json().then(e=>{if(Q0(e)){const t=e.code==="undefined"?"Undefined Error":e.code;return new Rn(e.error,t,r)}return new Rn(r.statusText,`Status: ${r.status} | Data: ${JSON.stringify(e)}`,r)}).catch(e=>new Rn(`Error: ${wt(e).message}`,`Status: ${r.status}`,r)),wa=r=>r.then(Tt).catch(e=>{if(e instanceof Response)return Aa(e).then(pe);if(e instanceof Error){const t=e.response;return t instanceof Response?Aa(t).then(pe):pe(new Rn(e.message,`Error: ${e.name}`))}return pe(new Rn(`${String(e)}`,"Unexpected Error"))}),L0="http://backend.limewire.localhost".replace(/\/+$/,"");let z0=class{constructor(e={}){this.configuration=e}set config(e){this.configuration=e}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:L0}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||cf}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return typeof e=="function"?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return typeof e=="function"?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}};function cf(r,e=""){return Object.keys(r).map(t=>lf(t,r[t],e)).filter(t=>t.length>0).join("&")}function lf(r,e,t=""){const n=t+(t.length?`[${r}]`:r);if(e instanceof Array){const i=e.map(s=>encodeURIComponent(String(s))).join(`&${encodeURIComponent(n)}=`);return`${encodeURIComponent(n)}=${i}`}if(e instanceof Set){const i=Array.from(e);return lf(r,i,t)}return e instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?cf(e,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`}
1const W0=["csrf_invalid"],V0=[403],H0="x-csrf-token",G0=async r=>{if(r.ok||!V0.includes(r.status))return!1;const e=await Aa(r.clone());return uc(e)&&e},uc=r=>r instanceof Rn&&W0.includes(r.code),Y0=["invalid_access_token","invalid_refresh_token"],K0=[401],q0="authorization",j0=async r=>{if(r.ok||!K0.includes(r.status))return!1;const e=await Aa(r.clone());return X0(e)&&e},X0=r=>r instanceof Rn&&Y0.includes(r.code),uf={credentials:"include"},J0=[r=>uc(r.underlyingError)],df=async(r,e,t)=>(typeof r=="function"?await r(e||"",t):r)||{},ff=(r,...e)=>{const{post:t,pre:n,init:i,inspect:s}=r||{},a=[n,...e.map(({pre:u})=>u)],o=[t,...e.map(({post:u})=>u)],c=[i,...e.map(({init:u})=>u)],l=[s,...e.map(({inspect:u})=>u)];return{...r,async pre(u){let d=u;for(const f of a)typeof f=="function"&&(d=await f(d)||d);return d},async post(u,d){let f=u;for(const h of o)typeof h=="function"&&(f=await h(f,d)||f);return f},async init(u,d){let f=d||{};for(const h of c){const p=await df(h,u,f);f={...f,...p,signal:nf(f.signal,p.signal),headers:ga(f.headers,p.headers)}}return f}
1,async inspect(u,d){let f=Tt(u);for(const h of l)if(typeof h=="function"){if(!f.ok)break;f=await h(f.value,d)||f}return f}}},$0=(r,e,...t)=>{const{retry:n,timeout:i,authFetcher:s,csrfFetcher:a}=e,{init:o,inspect:c}=ff({basePath:"",...e},...t);return{timeout:i,retry:(l,u)=>{if(!n)return;const{response:d}=u,f=!!J0.some(h=>h(u));if(!(lc(d)&&!f))return cc(n,l,u)},init:async l=>{const u=await o(r),d=s&&await s.getAuthToken(),f=a&&(uc(l==null?void 0:l.underlyingError)?await a.getFetchedCsrfToken():await a.getCsrfToken()||await a.getFetchedCsrfToken());return{...uf,...u,headers:ga(u.headers,!!d&&{[q0]:`Bearer ${d}`},!!f&&{[H0]:f})}},inspect:async(l,u)=>{const d=await c(l,u);if(!d.ok)return pe(d.error);const{value:f}=d;if(f.status>=200&&f.status<300)return d;const h=s&&await j0(f);if(h)return await s.invalidateAuthToken({response:f,error:h}),pe(new Dr(h,f));const p=a&&await G0(f);return p?(await a.invalidateCsrfToken({response:f,error:p}),pe(new Dr(p,f))):pe(new Dr(new Error(`Response returned an error code: ${f.status}`),f))}}},dc=(r,e,...t)=>{const{basePath:n}=e,{pre:i,post:s}=ff(e,...t),a=new z0({basePath:n,async fetchApi(c,l){const u=await i(c);let d=new Request(u);const f=await I0(u,$0(u,{...e,init:l},{init:uf},e,{init(p,m){d=new Request(p,m||{})}})),h=await s(f,d);if(!h.ok){const{response:p}=h.error;if(p)return p;throw h.error}return h.value}});return new r(a)},Z0="http://backend.limewire.localhost".replace(/\/+$/,"");class eb{constructor(e={}){this.configuration=e}set config(e){this.configuration=e}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:Z0}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||hf}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const e=this.configuration.apiKey;if(e)return typeof e=="function"?e:()=>e}get accessToken(){const e=this.configuration.accessToken;if(e)return typeof e=="function"?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const tb=new eb,tc=class tc{constructor(e=tb){this.configuration=e,this.fetchApi=async(t,n)=>{let i={url:t,init:n};for(const a of this.middleware)a.pre&&(i=await a.pre({fetch:this.fetchApi,...i})||i);let s;try{s=await(this.configuration.fetchApi||fetch)(i.url,i.init)}catch(a){for(const o of this.middleware)o.onError&&(s=await o.onError({fetch:this.fetchApi,url:i.url,init:i.init,error:a,response:s?s.clone():void 0})||s);if(s===void 0)throw a instanceof Error?new sb(a,"The request failed and the interceptors did not return an alternative response"):a}for(const a of this.middleware)a.post&&(s=await a.post({fetch:this.fetchApi,url:i.url,init:i.init,response:s.clone()})||s);return s},this.middleware=e.middleware}withMiddleware(...e){const t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){const t=e.map(n=>({pre:n}));return this.withMiddleware(...t)}withPostMiddleware(...e){const t=e.map(n=>({post:n}));return this.withMiddleware(...t)}isJsonMime(e){return e?tc.jsonRegex.test(e):!1}async request(e,t){const{url:n,init:i}=await this.createFetchParams(e,t),s=await this.fetchApi(n,i);if(s&&s.status>=200&&s.status<300)return s;throw new ib(s,"Response returned an error code")}async createFetchParams(e,t){let n=this.configuration.basePath+e.path;e.query!==void 0&&Object.keys(e.query).length!==0&&(n+="?"+this.configuration.queryParamsStringify(e.query));const i=Object.assign({},this.configuration.headers,e.headers);
1Object.keys(i).forEach(u=>i[u]===void 0?delete i[u]:{});const s=typeof t=="function"?t:async()=>t,a={method:e.method,headers:i,body:e.body,credentials:this.configuration.credentials},o={...a,...await s({init:a,context:e})};let c;nb(o.body)||o.body instanceof URLSearchParams||rb(o.body)?c=o.body:this.isJsonMime(i["Content-Type"])?c=JSON.stringify(o.body):c=o.body;const l={...o,body:c};return{url:n,init:l}}clone(){const e=this.constructor,t=new e(this.configuration);return t.middleware=this.middleware.slice(),t}};tc.jsonRegex=new RegExp("^(:?application/json|[^;/ 	]+/[^;/ 	]+[+]json)[ 	]*(:?;.*)?$","i");let ya=tc;function rb(r){return typeof Blob<"u"&&r instanceof Blob}function nb(r){return typeof FormData<"u"&&r instanceof FormData}class ib extends Error{constructor(e,t){super(t),this.response=e,this.name="ResponseError"}}class sb extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}}class Mr extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}function hf(r,e=""){return Object.keys(r).map(t=>mf(t,r[t],e)).filter(t=>t.length>0).join("&")}function mf(r,e,t=""){const n=t+(t.length?`[${r}]`:r);if(e instanceof Array){const i=e.map(s=>encodeURIComponent(String(s))).join(`&${encodeURIComponent(n)}=`);return`${encodeURIComponent(n)}=${i}`}if(e instanceof Set){const i=Array.from(e);return mf(r,i,t)}return e instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?hf(e,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`}class mi{constructor(e,t=n=>n){this.raw=e,this.transformer=t}async value(){return this.transformer(await this.raw.json())}}class pf{constructor(e){this.raw=e}async value(){}}function ab(r){return r==null?r:{encryptedPrivateKey:r.encryptedPrivateKey,encryptedByKeyType:r.encryptedByKeyType,encryptedByKeyId:r.encryptedByKeyId}}function ob(r){return cb(r)}function cb(r,e){return r==null?r:{eTag:r.ETag,partNumber:r.PartNumber,size:r.Size==null?void 0:r.Size}}function lb(r){return r==null?r:{ETag:r.eTag,PartNumber:r.partNumber,Size:r.size}}function ub(r){return db(r)}function db(r,e){return r==null?r:{method:r.method,url:r.url}}function lP(r){return r}function uP(r){return r}function fc(r){return r==null?r:{time:r.time,increment:r.increment}}function fb(r){return r==null?r:{parts:r.parts.map(lb)}}function hb(r){return mb(r)}function mb(r,e){return r==null?r:{resultS3Url:r.resultS3Url}}function dP(r){return r}function fP(r){return r}function pb(r){return r==null?r:{id:r.id,mediaType:r.mediaType,type:r.type}}function hP(r){return r}function mP(r){return r}function gf(r){return r==null?r:{id:r.id,originalSharingBucketId:r.originalSharingBucketId,s3Status:r.s3Status,itemType:r.itemType,mediaType:r.mediaType,size:r.size,nameEncrypted:r.nameEncrypted,sha1Encrypted:r.sha1Encrypted,baseFileEncryptionKeyId:r.baseFileEncryptionKeyId,ephemeralPublicKey:r.ephemeralPublicKey,metadata:r.metadata,previews:r.previews==null?void 0:r.previews.map(pb),nsfw:r.nsfw,createdDate:r.createdDate.toISOString(),lastModifiedTimestamp:fc(r.lastModifiedTimestamp),deleted:r.deleted}}function gb(r){return Ab(r)}function Ab(r,e){return r==null?r:{uploadId:r.uploadId,key:r.key}}function wb(r){return yb(r)}function yb(r,e){return r==null?r:{method:r.method,url:r.url,resultS3Url:r.resultS3Url}}function bb(r){return r==null?r:{id:r.id,ownerId:r.ownerId,clientDeviceId:r.clientDeviceId,ownerNick:r.ownerNick,sharingStatus:r.sharingStatus,sharingPermission:r.sharingPermission,sharingId:r.sharingId,primaryEncryptionKeyId:r.primaryEncryptionKeyId,contentItemIds:r.contentItemIds,totalFileSize:r.totalFileSize,name:r.name,createdDate:r.createdDate.toISOString(),lastModifiedTimestamp:fc(r.lastModifiedTimestamp),deleted:r.deleted,expiresAt:r.expiresAt==null?null:r.expiresAt.toISOString(),downloadCounter:r.downloadCounter,publicDownloadCounter:r.publicDownloadCounter,pinned:r.pinned}}function Eb(r){return r==null?r:{id:r.id,publicKey:r.publicKey,privateKeys:r.privateKeys.map(ab),encryptedPassphrase:r.encryptedPassphrase,passphraseWrappedPrivateKey:r.passphraseWrappedPrivateKey,deleted:r.deleted,createdDate:r.createdDate.toISOString(),lastModifiedTimestamp:fc(r.lastModifiedTimestamp)}}function Af(r){return r==null?r:{sharingBucket:bb(r.sharingBucket),contentItem:gf(r.contentItem),fileEncryptionKey:Eb(r.fileEncryptionKey),metadataId:r.metadataId}}function kb(r){return r==null?r:{logEventType:r.logEventType,sharingBucketId:r.sharingBucketId,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),size:r.size}}function Tb(r){return r==null?r:{sharingBucketId:r.sharingBucketId,contentItem:gf(r.contentItem)}}function Sb(r){return Cb(r)}function Cb(r,e){return r==null?r:{sharingBucketId:r.sharingBucketId,contentItemId:r.contentItemId}}function Ib(r){return Bb(r)}function Bb(r,e){return r==null?r:{parts:r.parts.map(ob)}}function xb(r){return r==null?r:{logEventType:r.logEventType,sharingBucketId:r.sharingBucketId,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),size:r.size}}function Pb(r){if(r==null)return r;switch(r.logEventType){case"DownloadLogEvent":return kb(r);case"UploadLogEvent":return xb(r);default:throw new Error(`No variant of LogEventRequestInner exists with 'logEventType=${r.logEventType}'`)}}class vb extends ya{async logEventRaw(e,t){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/logs",method:"POST",headers:i,query:n,body:e.logEventRequestInner.map(Pb)},t);return new pf(s)}async logEvent(e={},t){await this.logEventRaw(e,t)}}class wf extends ya{async abortUploadRaw(e,t){if(e.uploadId==null)throw new Mr("uploadId",'Required parameter "uploadId" was null or undefined when calling abortUpload().');
1if(e.key==null)throw new Mr("key",'Required parameter "key" was null or undefined when calling abortUpload().');const n={};e.key!=null&&(n.key=e.key);const i={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/multipart/{uploadId}".replace("{uploadId}",encodeURIComponent(String(e.uploadId))),method:"DELETE",headers:i,query:n},t);return new pf(s)}async abortUpload(e,t){await this.abortUploadRaw(e,t)}async completeMultipartUploadRaw(e,t){if(e.uploadId==null)throw new Mr("uploadId",'Required parameter "uploadId" was null or undefined when calling completeMultipartUpload().');if(e.key==null)throw new Mr("key",'Required parameter "key" was null or undefined when calling completeMultipartUpload().');const n={};e.key!=null&&(n.key=e.key);const i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/multipart/{uploadId}/complete".replace("{uploadId}",encodeURIComponent(String(e.uploadId))),method:"POST",headers:i,query:n,body:fb(e.completeMultipartUploadRequest)},t);return new mi(s,a=>hb(a))}async completeMultipartUpload(e,t){return await(await this.completeMultipartUploadRaw(e,t)).value()}async createMultipartFileUploadRaw(e,t){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/multipart",method:"POST",headers:i,query:n,body:Af(e.createUploadRequest)},t);return new mi(s,a=>gb(a))}async createMultipartFileUpload(e={},t){return await(await this.createMultipartFileUploadRaw(e,t)).value()}async createSingleFileUploadRaw(e,t){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/single",method:"POST",headers:i,query:n,body:Af(e.createUploadRequest)},t);return new mi(s,a=>wb(a))}async createSingleFileUpload(e={},t){return await(await this.createSingleFileUploadRaw(e,t)).value()}async finishContentItemRaw(e,t){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload",method:"POST",headers:i,query:n,body:Tb(e.finishUploadRequest)},t);return new mi(s,a=>Sb(a))}async finishContentItem(e={},t){return await(await this.finishContentItemRaw(e,t)).value()}async listPartsRaw(e,t){if(e.uploadId==null)throw new Mr("uploadId",'Required parameter "uploadId" was null or undefined when calling listParts().');if(e.key==null)throw new Mr("key",'Required parameter "key" was null or undefined when calling listParts().');const n={};e.key!=null&&(n.key=e.key);const i={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/multipart/{uploadId}".replace("{uploadId}",encodeURIComponent(String(e.uploadId))),method:"GET",headers:i,query:n},t);return new mi(s,a=>Ib(a))}async listParts(e,t){return await(await this.listPartsRaw(e,t)).value()}async signPartRaw(e,t){if(e.uploadId==null)throw new Mr("uploadId",'Required parameter "uploadId" was null or undefined when calling signPart().');if(e.key==null)throw new Mr("key",'Required parameter "key" was null or undefined when calling signPart().');if(e.partNumber==null)throw new Mr("partNumber",'Required parameter "partNumber" was null or undefined when calling signPart().');const n={};e.key!=null&&(n.key=e.key);const i={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(i.Authorization=`Bearer ${o}`)}const s=await this.request({path:"/sharing/upload/s3/multipart/{uploadId}/{partNumber}".replace("{uploadId}",encodeURIComponent(String(e.uploadId))).replace("{partNumber}",encodeURIComponent(String(e.partNumber))),method:"GET",headers:i,query:n},t);return new mi(s,a=>ub(a))}async signPart(e,t){return await(await this.signPartRaw(e,t)).value(
1)}}const et=4294967295,Le=65535,Ir=255,hc=8,mc=9,yf=0,bf=99,Ef=67324752,pc=134695760,kf=pc,gc=33639248,Tf=101010256,Ac=101075792,Sf=117853008,Ur=22,cs=20,ls=56,_b=Ur+cs+ls,Cf=12,If=20,ba=4,wc=1,Bf=39169,xf=10,Pf=1,yc=21589,Fb=28789,Rb=25461,vf=6534,_f=30837,Ff=30805,bc=1,Db=6,Mb=2,Ub=4,Ob=6,Ec=8,kc=2048,Ea=16,Tc=1,Sc=2,Cc=4,Ic=32,Rf=61440,us=16384,ds=73,ka=420,Ta=2048,Sa=1024,Ca=512,Nb=20,Df=45,Mf=51,Ia="/",Dn=30,Bc=10,pi=14,gi=18,Uf=new Date(2107,11,31),Of=new Date(1980,0,1),Z=void 0,fs=1/0,cn="undefined",ln="function",Qb="object",Lb=64;let Nf=2;try{typeof navigator!=cn&&navigator.hardwareConcurrency&&(Nf=navigator.hardwareConcurrency)}catch{}const zb={workerURI:"./core/web-worker-wasm.js",wasmURI:"./core/streams/zlib-wasm/zlib-streams.wasm",chunkSize:64*1024,maxWorkers:Nf,terminateWorkerTimeout:5e3,useWebWorkers:!0,useCompressionStream:!0,CompressionStream:typeof CompressionStream!=cn&&CompressionStream,DecompressionStream:typeof DecompressionStream!=cn&&DecompressionStream},Qf=Object.assign({},zb);function Lf(){return Qf}function zf(r){return Math.max(r.chunkSize,Lb)}function Ba(r){const{baseURI:e,chunkSize:t,maxWorkers:n,terminateWorkerTimeout:i,useCompressionStream:s,useWebWorkers:a,CompressionStream:o,DecompressionStream:c,CompressionStreamZlib:l,DecompressionStreamZlib:u,workerURI:d,wasmURI:f}=r;cr("baseURI",e),cr("wasmURI",f),cr("workerURI",d),cr("chunkSize",t),cr("maxWorkers",n),cr("terminateWorkerTimeout",i),cr("useCompressionStream",s),cr("useWebWorkers",a),cr("CompressionStream",o),cr("DecompressionStream",c),cr("CompressionStreamZlib",l),cr("DecompressionStreamZlib",u)}function cr(r,e){e!==Z&&(Qf[r]=e)}function Wb(r){const e=`
vendor: 17,345 bytes, line 1
1(t=>{"function"==typeof define&&define.amd?define(t):t()})(function(){"use strict";const{Array:t,Object:e,Number:n,Math:s,Error:r,Uint8Array:o,Uint16Array:i,Uint32Array:c,Int32Array:a,Map:h,DataView:f,Promise:l,TextEncoder:u,crypto:w,postMessage:p,TransformStream:d,ReadableStream:y,WritableStream:m,CompressionStream:g,DecompressionStream:S}=self,b=void 0,v="undefined",k="function",z=[];for(let t=0;256>t;t++){let e=t;for(let t=0;8>t;t++)1&e?e=e>>>1^3988292384:e>>>=1;z[t]=e}class C{constructor(t){this.t=t||-1}append(t){let e=0|this.t;for(let n=0,s=0|t.length;s>n;n++)e=e>>>8^z[255&(e^t[n])];this.t=e}get(){return~this.t}}class A extends d{constructor(){let t;const e=new C;super({transform(t,n){e.append(t),n.enqueue(t)},flush(){const n=new o(4);new f(n.buffer).setUint32(0,e.get()),t.value=n}}),t=this}}const x={concat(t,e){if(0===t.length||0===e.length)return t.concat(e);const n=t[t.length-1],s=x.o(n);return 32===s?t.concat(e):x.i(e,s,0|n,t.slice(0,t.length-1))},h(t){const e=t.length;if(0===e)return 0;const n=t[e-1];return 32*(e-1)+x.o(n)},l(t,e){if(32*t.length<e)return t;const n=(t=t.slice(0,s.ceil(e/32))).length;return e&=31,n>0&&e&&(t[n-1]=x.u(e,t[n-1]&2147483648>>e-1,1)),t},u:(t,e,n)=>32===t?e:(n?0|e:e<<32-t)+1099511627776*t,o:t=>s.round(t/1099511627776)||32,i(t,e,n,s){for(void 0===s&&(s=[]);e>=32;e-=32)s.push(n),n=0;if(0===e)return s.concat(t);for(let r=0;r<t.length;r++)s.push(n|t[r]>>>e),n=t[r]<<32-e;const r=t.length?t[t.length-1]:0,o=x.o(r);return s.push(x.u(e+o&31,e+o>32?n:s.pop(),1)),s}},I={bytes:{p(t){const e=x.h(t)/8,n=new o(e);let s;for(let r=0;e>r;r++)3&r||(s=t[r/4]),n[r]=s>>>24,s<<=8;return n},m(t){const e=[];let n,s=0;for(n=0;n<t.length;n++)s=s<<8|t[n],3&~n||(e.push(s),s=0);return 3&n&&e.push(x.u(8*(3&n),s)),e}}},R=class{constructor(t){const e=this;e.blockSize=512,e.S=[1732584193,4023233417,2562383102,271733878,3285377520],e.v=[1518500249,1859775393,2400959708,3395469782],t?(e.k=t.k.slice(0),e.C=t.C.slice(0),e.A=t.A):e.reset()}reset(){const t=this;return t.k=t.S.slice(0),t.C=[],t.A=0,t}update(t){const e=this;"string"==typeof t&&(t=I.I.m(t));const n=e.C=x.concat(e.C,t),s=e.A,o=e.A=s+x.h(t);if(o>9007199254740991)throw new r("Cannot hash more than 2^53 - 1 bits");const i=new c(n);let a=0;for(let t=e.blockSize+s-(e.blockSize+s&e.blockSize-1);o>=t;t+=e.blockSize)e.R(i.subarray(16*a,16*(a+1))),a+=1;return n.splice(0,16*a),e}P(){const t=this;let e=t.C;const n=t.k;e=x.concat(e,[x.u(1,1)]);for(let t=e.length+2;15&t;t++)e.push(0);for(e.push(s.floor(t.A/4294967296)),e.push(0|t.A);e.length;)t.R(e.splice(0,16));return t.reset(),n}U(t,e,n,s){return t>19?t>39?t>59?t>79?void 0:e^n^s:e&n|e&s|n&s:e^n^s:e&n|~e&s}V(t,e){return e<<t|e>>>32-t}R(e){const n=this,r=n.k,o=t(80);for(let t=0;16>t;t++)o[t]=e[t];let i=r[0],c=r[1],a=r[2],h=r[3],f=r[4];for(let t=0;79>=t;t++){16>t||(o[t]=n.V(1,o[t-3]^o[t-8]^o[t-14]^o[t-16]));const e=n.V(5,i)+n.U(t,c,a,h)+f+o[t]+n.v[s.floor(t/20)]|0;f=h,h=a,a=n.V(30,c),c=i,i=e}r[0]=r[0]+i|0,r[1]=r[1]+c|0,r[2]=r[2]+a|0,r[3]=r[3]+h|0,r[4]=r[4]+f|0}},P={getRandomValues(t){const e=new c(t.buffer),n=t=>{let e=987654321;const n=4294967295;return()=>(e=36969*(65535&e)+(e>>16)&n,(((e<<16)+(t=18e3*(65535&t)+(t>>16)&n)&n)/4294967296+.5)*(s.random()>.5?1:-1))};for(let r,o=0;o<t.length;o+=4){const t=n(4294967296*(r||s.random()));r=987654071*t(),e[o/4]=4294967296*t()|0}return t}},U={importKey:t=>new U.M(I.bytes.m(t)),_(t,e,n,s){if(n=n||1e4,0>s||0>n)throw new r("invalid params to pbkdf2");const o=1+(s>>5)<<2;let i,c,a,h,l;const u=new ArrayBuffer(o),w=new f(u);let p=0;const d=x;for(e=I.bytes.m(e),l=1;(o||1)>p;l++){for(i=c=t.encrypt(d.concat(e,[l])),a=1;n>a;a++)for(c=t.encrypt(c),h=0;h<c.length;h++)i[h]^=c[h];for(a=0;(o||1)>p&&a<i.length;a++)w.setInt32(p,i[a]),p+=4}return u.slice(0,s/8)},M:class{constructor(t){const e=this,n=e.B=R,s=[[],[]];e.D=[new n,new n];const r=e.D[0].blockSize/32;t.length>r&&(t=(new n).update(t).P());for(let e=0;r>e;e++)s[0][e]=909522486^t[e],s[1][e]=1549556828^t[e];e.D[0].update(s[0]),e.D[1].update(s[1]),e.W=new n(e.D[0])}reset(){const t=this;t.W=new t.B(t.D[0]),t.K=!1}update(t){this.K=!0,this.W.update(t)}digest(){const t=this,e=t.W.P(),n=new t.B(t.D[1]).update(e).P();return t.reset(),n}encrypt(t){if(this.K)throw new r("encrypt on already updated hmac called!");return this.update(t),this.digest(t)}}},V=typeof w!=v&&typeof w.getRandomValues==k,M="Invalid password",_="Invalid signature",B="zipjs-abort-check-password";function D(t){return V?w.getRandomValues(t):P.getRandomValues(t)}const W=16,K={name:"PBKDF2"},E=e.assign({hash:{name:"HMAC"}},K),L=e.assign({iterations:1e3,hash:{name:"SHA-1"}},K),O=["deriveBits"],T=[8,12,16],j=[16,24,32],H=10,Z=[0,0,0,0],F=typeof w!=v,N=F&&w.subtle,q=F&&typeof N!=v,G=I.bytes,J=class{constructor(t){const e=this;e.L=[[[],[],[],[],[]],[[],[],[],[],[]]],e.L[0][0][0]||e.O();const n=e.L[0][4],s=e.L[1],o=t.length;let i,c,a,h=1;if(4!==o&&6!==o&&8!==o)throw new r("invalid aes key size");for(e.v=[c=t.slice(0),a=[]],i=o;4*o+28>i;i++){let t=c[i-1];(i%o===0||8===o&&i%o===4)&&(t=n[t>>>24]<<24^n[t>>16&255]<<16^n[t>>8&255]<<8^n[255&t],i%o===0&&(t=t<<8^t>>>24^h<<24,h=h<<1^283*(h>>7))),c[i]=c[i-o]^t}for(let t=0;i;t++,i--){const e=c[3&t?i:i-4];a[t]=4>=i||4>t?e:s[0][n[e>>>24]]^s[1][n[e>>16&255]]^s[2][n[e>>8&255]]^s[3][n[255&e]]}}encrypt(t){return this.T(t,0)}decrypt(t){return this.T(t,1)}O(){const t=this.L[0],e=this.L[1],n=t[4],s=e[4],r=[],o=[];let i,c,a,h;for(let t=0;256>t;t++)o[(r[t]=t<<1^283*(t>>7))^t]=t;for(let f=i=0;!n[f];f^=c||1,i=o[i]||1){let o=i^i<<1^i<<2^i<<3^i<<4;o=o>>8^255&o^99,n[f]=o,s[o]=f,h=r[a=r[c=r[f]]];let l=16843009*h^65537*a^257*c^16843008*f,u=257*r[o]^16843008*o;for(let n=0;4>n;n++)t[n][f]=u=u<<24^u>>>8,e[n][o]=l=l<<24^l>>>8}for(let n=0;5>n;n++)t[n]=t[n].slice(0),e[n]=e[n].slice(0)}T(t,e){if(4!==t.length)throw new r("invalid aes block size");const n=this.v[e],s=n.length/4-2,o=[0,0,0,0],i=this.L[e],c=i[0],a=i[1],h=i[2],f=i[3],l=i[4];let u,w,p,d=t[0]^n[0],y=t[e?3:1]^n[1],m=t[2]^n[2],g=t[e?1:3]^n[3],S=4;for(let t=0;s>t;t++)u=c[d>>>24]^a[y>>16&255]^h[m>>8&255]^f[255&g]^n[S],w=c[y>>>24]^a[m>>16&255]^h[g>>8&255]^f[255&d]^n[S+1],p=c[m>>>24]^a[g>>16&255]^h[d>>8&255]^f[255&y]^n[S+2],g=c[g>>>24]^a[d>>16&255]^h[y>>8&255]^f[255&m]^n[S+3],S+=4,d=u,y=w,m=p;for(let t=0;4>t;t++)o[e?3&-t:t]=l[d>>>24]<<24^l[y>>16&255]<<16^l[m>>8&255]<<8^l[255&g]^n[S++],u=d,d=y,y=m,m=g,g=u;return o}},Q=class{constructor(t,e){this.j=t,this.H=e,this.Z=e}reset(){this.Z=this.H}update(t){return this.F(this.j,t,this.Z)}N(t){if(255&~(t>>24))t+=1<<24;else{let e=t>>16&255,n=t>>8&255,s=255&t;255===e?(e=0,255===n?(n=0,255===s?s=0:++s):++n):++e,t=0,t+=e<<16,t+=n<<8,t+=s}return t}q(t){0===(t[0]=this.N(t[0]))&&(t[1]=this.N(t[1]))}F(t,e,n){let s;if(!(s=e.length))return[];const r=x.h(e);for(let r=0;s>r;r+=4){this.q(n);const s=t.encrypt(n);e[r]^=s[0],e[r+1]^=s[1],e[r+2]^=s[2],e[r+3]^=s[3]}return x.l(e,r)}},X=U.M;let Y=F&&q&&typeof N.importKey==k,$=F&&q&&typeof N.deriveBits==k;class tt extends d{constructor({password:t,rawPassword:n,signed:s,encryptionStrength:i,checkPasswordOnly:c}){super({start(){e.assign(this,{ready:new l(t=>this.G=t),password:rt(t,n),signed:s,J:i-1,pending:new o})},async transform(t,e){const n=this,{password:s,J:i,G:a,ready:h}=n;s?(await(async(t,e,n,s)=>{const o=await st(t,e,n,it(s,0,T[e])),i=it(s,T[e]);if(o[0]!=i[0]||o[1]!=i[1])throw new r(M)})(n,i,s,it(t,0,T[i]+2)),t=it(t,T[i]+2),c?e.error(new r(B)):a()):await h;const f=new o(t.length-H-(t.length-H)%W);e.enqueue(nt(n,t,f,0,H,!0))},async flush(t){const{signed:e,X:n,Y:s,pending:i,ready:c}=this;if(s&&n){await c;const a=it(i,0,i.length-H),h=it(i,i.length-H);let f=new o;if(a.length){const t=at(G,a);s.update(t);const e=n.update(t);f=ct(G,e)}if(e){const t=it(ct(G,s.digest()),0,H);for(let e=0;H>e;e++)if(t[e]!=h[e])throw new r(_)}t.enqueue(f)}}})}}class et extends d{constructor({password:t,rawPassword:n,encryptionStrength:s}){let r;super({start(){e.assign(this,{ready:new l(t=>this.G=t),password:rt(t,n),J:s-1,pending:new o})},async transform(t,e){const n=this,{password:s,J:r,G:i,ready:c}=n;let a=new o;s?(a=await(async(t,e,n)=>{const s=D(new o(T[e]));return ot(s,await st(t,e,n,s))})(n,r,s),i()):await c;const h=new o(a.length+t.length-t.length%W);h.set(a,0),e.enqueue(nt(n,t,h,a.length,0))},async flush(t){const{X:e,Y:n,pending:s,ready:i}=this;if(n&&e){await i;let c=new o;if(s.length){const t=e.update(at(G,s));n.update(t),c=ct(G,t)}r.signature=ct(G,n.digest()).slice(0,H),t.enqueue(ot(c,r.signature))}}}),r=this}}function nt(t,e,n,s,r,i){const{X:c,Y:a,pending:h}=t,f=e.length-r;let l;for(h.length&&(e=ot(h,e),n=((t,e)=>{if(e&&e>t.length){const n=t;(t=new o(e)).set(n,0)}return t})(n,f-f%W)),l=0;f-W>=l;l+=W){const t=at(G,it(e,l,l+W));i&&a.update(t);const r=c.update(t);i||a.update(r),n.set(ct(G,r),l+s)}return t.pending=it(e,l),n}async function st(n,s,r,i){n.password=null;const c=await(async(t,e,n,s,r)=>{if(!Y)return U.importKey(e);try{return await N.importKey("raw",e,n,!1,r)}catch{return Y=!1,U.importKey(e)}})(0,r,E,0,O),a=await(async(t,e,n)=>{if(!$)return U._(e,t.salt,L.iterations,n);try{return await N.deriveBits(t,e,n)}catch{return $=!1,U._(e,t.salt,L.iterations,n)}})(e.assign({salt:i},L),c,8*(2*j[s]+2)),h=new o(a),f=at(G,it(h,0,j[s])),l=at(G,it(h,j[s],2*j[s])),u=it(h,2*j[s]);return e.assign(n,{keys:{key:f,$:l,passwordVerification:u},X:new Q(new J(f),t.from(Z)),Y:new X(l)}),u}function rt(t,e){return e===b?(t=>{if(typeof u==v){const e=new o((t=unescape(encodeURIComponent(t))).length);for(let n=0;n<e.length;n++)e[n]=t.charCodeAt(n);return e}return(new u).encode(t)})(t):e}function ot(t,e){let n=t;return t.length+e.length&&(n=new o(t.length+e.length),n.set(t,0),n.set(e,t.length)),n}function it(t,e,n){return t.subarray(e,n)}function ct(t,e){return t.p(e)}function at(t,e){return t.m(e)}class ht extends d{constructor({password:t,passwordVerification:n,checkPasswordOnly:s}){super({start(){e.assign(this,{password:t,passwordVerification:n}),wt(this,t)},transform(t,e){const n=this;if(n.password){const e=lt(n,t.subarray(0,12));if(n.password=null,e.at(-1)!=n.passwordVerification)throw new r(M);t=t.subarray(12)}s?e.error(new r(B)):e.enqueue(lt(n,t))}})}}class ft extends d{constructor({password:t,passwordVerification:n}){super({start(){e.assign(this,{password:t,passwordVerification:n}),wt(this,t)},transform(t,e){const n=this;let s,r;if(n.password){n.password=null;const e=D(new o(12));e[11]=n.passwordVerification,s=new o(t.length+e.length),s.set(ut(n,e),0),r=12}else s=new o(t.length),r=0;s.set(ut(n,t),r),e.enqueue(s)}})}}function lt(t,e){const n=new o(e.length);for(let s=0;s<e.length;s++)n[s]=dt(t)^e[s],pt(t,n[s]);return n}function ut(t,e){const n=new o(e.length);for(let s=0;s<e.length;s++)n[s]=dt(t)^e[s],pt(t,e[s]);return n}function wt(t,n){const s=[305419896,591751049,878082192];e.assign(t,{keys:s,tt:new C(s[0]),et:new C(s[2])});for(let e=0;e<n.length;e++)pt(t,n.charCodeAt(e))}function pt(t,e){let[n,r,o]=t.keys;t.tt.append([e]),n=~t.tt.get(),r=mt(s.imul(mt(r+yt(n)),134775813)+1),t.et.append([r>>>24]),o=~t.et.get(),t.keys=[n,r,o]}function dt(t){const e=2|t.keys[2];return yt(s.imul(e,1^e)>>>8)}function yt(t){return 255&t}function mt(t){return 4294967295&t}class gt extends d{constructor(t,{chunkSize:e,nt:n,CompressionStream:s}){super({});const{compressed:r,encrypted:o,useCompressionStream:i,zipCrypto:c,signed:a,level:h}=t,l=this;let u,w,p=super.readable;o&&!c||!a||(u=new A,p=kt(p,u)),r&&(p=vt(p,i,{level:h,chunkSize:e},s,n,s)),o&&(c?p=kt(p,new ft(t)):(w=new et(t),p=kt(p,w))),bt(l,p,()=>{let t;o&&!c&&(t=w.signature),o&&!c||!a||(t=new f(u.value.buffer).getUint32(0)),l.signature=t})}}class St extends d{constructor(t,{chunkSize:e,st:n,DecompressionStream:s}){super({});const{zipCrypto:o,encrypted:i,signed:c,signature:a,compressed:h,useCompressionStream:l,rt:u}=t;let w,p,d=super.readable;i&&(o?d=kt(d,new ht(t)):(p=new tt(t),d=kt(d,p))),h&&(d=vt(d,l,{chunkSize:e,rt:u},s,n,s)),i&&!o||!c||(w=new A,d=kt(d,w)),bt(this,d,()=>{if((!i||o)&&c){const t=new f(w.value.buffer);if(a!=t.getUint32(0,!1))throw new r(_)}})}}function bt(t,n,s){n=kt(n,new d({flush:s})),e.defineProperty(t,"readable",{get:()=>n})}function vt(t,e,n,s,r,o){const i=e&&s?s:r||o,c=n.rt?"deflate64-raw":"deflate-raw";try{t=kt(t,new i(c,n))}catch(s){if(!e)throw s;if(r)t=kt(t,new r(c,n));else{if(!o)throw s;t=kt(t,new o(c,n))}}return t}function kt(t,e){return t.pipeThrough(e)}const zt="data",Ct="close";class At extends d{constructor(t,n){super({});const s=this,{codecType:o}=t;let i;o.startsWith("deflate")?i=gt:o.startsWith("inflate")&&(i=St),s.outputSize=0;let c=0;const a=new i(t,n),h=super.readable,f=new d({transform(t,e){t&&t.length&&(c+=t.length,e.enqueue(t))},flush(){e.assign(s,{inputSize:c})}}),l=new d({transform(e,n){if(e&&e.length&&(n.enqueue(e),s.outputSize+=e.length,t.outputSize!==b&&s.outputSize>t.outputSize))throw new r("Invalid uncompressed size")},flush(){const{signature:t}=a;e.assign(s,{signature:t,inputSize:c})}});e.defineProperty(s,"readable",{get:()=>h.pipeThrough(f).pipeThrough(a).pipeThrough(l)})}}class xt extends d{constructor(t){let e;super({transform:function n(s,r){if(e){const t=new o(e.length+s.length);t.set(e),t.set(s,e.length),s=t,e=null}s.length>t?(r.enqueue(s.slice(0,t)),n(s.slice(t),r)):e=s},flush(t){e&&e.length&&t.enqueue(e)}})}}const It=new h,Rt=new h;let Pt,Ut,Vt,Mt,_t,Bt=0;async function Dt(t){try{const{options:e,config:s}=t;if(!e.useCompressionStream)try{await self.initModule(t.config)}catch{e.useCompressionStream=!0}s.CompressionStream=self.CompressionStream,s.DecompressionStream=self.DecompressionStream;const r={highWaterMark:1},o=t.readable||new y({async pull(t){const e=new l(t=>It.set(Bt,t));Wt({type:"pull",messageId:Bt}),Bt=(Bt+1)%n.MAX_SAFE_INTEGER;const{value:s,done:r}=await e;t.enqueue(s),r&&t.close()}},r),i=t.writable||new m({async write(t){let e;const s=new l(t=>e=t);Rt.set(Bt,e),Wt({type:zt,value:t,messageId:Bt}),Bt=(Bt+1)%n.MAX_SAFE_INTEGER,await s}},r),c=new At(e,s);Pt=new AbortController;const{signal:a}=Pt;await o.pipeThrough(c).pipeThrough(new xt(s.chunkSize)).pipeTo(i,{signal:a,preventClose:!0,preventAbort:!0}),await i.getWriter().close();const{signature:h,inputSize:f,outputSize:u}=c;Wt({type:Ct,result:{signature:h,inputSize:f,outputSize:u}})}catch(t){t.outputSize=0,Kt(t)}}function Wt(t){let{value:e}=t;if(e)if(e.length)try{e=new o(e),t.value=e.buffer,p(t,[t.value])}catch{p(t)}else p(t);else p(t)}function Kt(t=new r("Unknown error")){const{message:e,stack:n,code:s,name:o,outputSize:i}=t;p({error:{message:e,stack:n,code:s,name:o,outputSize:i}})}function Et(t,e,n={}){const i="number"==typeof n.level?n.level:-1,c="number"==typeof n.ot?n.ot:65536,a="number"==typeof n.it?n.it:65536;return new d({start(){let n;if(this.ct=Vt(c),this.in=Vt(a),this.it=a,this.ht=new o(c),t?(this.ft=Ut.deflate_process,this.lt=Ut.deflate_last_consumed,this.ut=Ut.deflate_end,this.wt=Ut.deflate_new(),n="gzip"===e?Ut.deflate_init_gzip(this.wt,i):"deflate-raw"===e?Ut.deflate_init_raw(this.wt,i):Ut.deflate_init(this.wt,i)):"deflate64-raw"===e?(this.ft=Ut.inflate9_process,this.lt=Ut.inflate9_last_consumed,this.ut=Ut.inflate9_end,this.wt=Ut.inflate9_new(),n=Ut.inflate9_init_raw(this.wt)):(this.ft=Ut.inflate_process,this.lt=Ut.inflate_last_consumed,this.ut=Ut.inflate_end,this.wt=Ut.inflate_new(),n="deflate-raw"===e?Ut.inflate_init_raw(this.wt):"gzip"===e?Ut.inflate_init_gzip(this.wt):Ut.inflate_init(this.wt)),0!==n)throw new r("init failed:"+n)},transform(e,n){try{const i=e,a=new o(_t.buffer),h=this.ft,f=this.lt,l=this.ct,u=this.ht;let w=0;for(;w<i.length;){const e=s.min(i.length-w,32768);this.in&&this.it>=e||(this.in&&Mt&&Mt(this.in),this.in=Vt(e),this.it=e),a.set(i.subarray(w,w+e),this.in);const o=h(this.wt,this.in,e,l,c,0),p=16777215&o;if(p&&(u.set(a.subarray(l,l+p),0),n.enqueue(u.slice(0,p))),!t){const t=o>>24&255,e=128&t?t-256:t;if(0>e)throw new r("process error:"+e)}const d=f(this.wt);if(0===d)break;w+=d}}catch(t){this.ut&&this.wt&&this.ut(this.wt),this.in&&Mt&&Mt(this.in),this.ct&&Mt&&Mt(this.ct),n.error(t)}},flush(e){try{const n=new o(_t.buffer),s=this.ft,i=this.ct,a=this.ht;for(;;){const o=s(this.wt,0,0,i,c,4),h=16777215&o,f=o>>24&255;if(!t){const t=128&f?f-256:f;if(0>t)throw new r("process error:"+t)}if(h&&(a.set(n.subarray(i,i+h),0),e.enqueue(a.slice(0,h))),1===f||0===h)break}}catch(t){e.error(t)}finally{if(this.ut&&this.wt){const t=this.ut(this.wt);0!==t&&e.error(new r("end error:"+t))}this.in&&Mt&&Mt(this.in),this.ct&&Mt&&Mt(this.ct)}}})}addEventListener("message",({data:t})=>{const{type:e,messageId:n,value:s,done:r}=t;try{if("start"==e&&Dt(t),e==zt){const t=It.get(n);It.delete(n),t({value:new o(s),done:r})}if("ack"==e){const t=Rt.get(n);Rt.delete(n),t()}e==Ct&&Pt.abort()}catch(t){Kt(t)}});class Lt{constructor(t="deflate",e){return Et(!0,t,e)}}class Ot{constructor(t="deflate",e){return Et(!1,t,e)}}let Tt=!1;self.initModule=async t=>{try{const e=await(async(t,{baseURI:e})=>{if(!Tt){let n,s;try{try{s=new URL(t,e)}catch{}const r=await fetch(s);n=await r.arrayBuffer()}catch(e){if(!t.startsWith("data:application/wasm;base64,"))throw e;n=(t=>{const e=t.split(",")[1],n=atob(e),s=n.length,r=new o(s);for(let t=0;s>t;++t)r[t]=n.charCodeAt(t);return r.buffer})(t)}(t=>{if(Ut=t,({malloc:Vt,free:Mt,memory:_t}=Ut),"function"!=typeof Vt||"function"!=typeof Mt||!_t)throw Ut=Vt=Mt=_t=null,new r("Invalid WASM module")})((await WebAssembly.instantiate(n)).instance.exports),Tt=!0}})(t.wasmURI,t);return t.nt=Lt,t.st=Ot,e}catch{}}});
1
2`;r({workerURI:t=>{const n="text/javascript";if(t){const i=new Blob([e],{type:n});return URL.createObjectURL(i)}return"data:"+n+","+encodeURIComponent(e)}})}const Wf=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e&1?e=e>>>1^3988292384:e=e>>>1;Wf[r]=e}class xa{constructor(e){this.crc=e||-1}append(e){let t=this.crc|0;for(let n=0,i=e.length|0;n<i;n++)t=t>>>8^Wf[(t^e[n])&255];this.crc=t}get(){return~this.crc}}class Vf extends TransformStream{constructor(){let e;const t=new xa;super({transform(n,i){t.append(n),i.enqueue(n)},flush(){const n=new Uint8Array(4);new DataView(n.buffer).setUint32(0,t.get()),e.value=n}}),e=this}}function Pa(r){if(typeof TextEncoder==cn){r=unescape(encodeURIComponent(r));const e=new Uint8Array(r.length);for(let t=0;t<e.length;t++)e[t]=r.charCodeAt(t);return e}else return new TextEncoder().encode(r)}const zt={concat(r,e){if(r.length===0||e.length===0)return r.concat(e);const t=r[r.length-1],n=zt.getPartial(t);return n===32?r.concat(e):zt._shiftRight(e,n,t|0,r.slice(0,r.length-1))},bitLength(r){const e=r.length;if(e===0)return 0;const t=r[e-1];return(e-1)*32+zt.getPartial(t)},clamp(r,e){if(r.length*32<e)return r;r=r.slice(0,Math.ceil(e/32));const t=r.length;return e=e&31,t>0&&e&&(r[t-1]=zt.partial(e,r[t-1]&2147483648>>e-1,1)),r},partial(r,e,t){return r===32?e:(t?e|0:e<<32-r)+r*1099511627776},getPartial(r){return Math.round(r/1099511627776)||32},_shiftRight(r,e,t,n){for(n===void 0&&(n=[]);e>=32;e-=32)n.push(t),t=0;if(e===0)return n.concat(r);for(let a=0;a<r.length;a++)n.push(t|r[a]>>>e),t=r[a]<<32-e;const i=r.length?r[r.length-1]:0,s=zt.getPartial(i);return n.push(zt.partial(e+s&31,e+s>32?t:n.pop(),1)),n}},va={bytes:{fromBits(r){const t=zt.bitLength(r)/8,n=new Uint8Array(t);let i;for(let s=0;s<t;s++)(s&3)===0&&(i=r[s/4]),n[s]=i>>>24,i<<=8;return n},toBits(r){const e=[];let t,n=0;for(t=0;t<r.length;t++)n=n<<8|r[t],(t&3)===3&&(e.push(n),n=0);return t&3&&e.push(zt.partial(8*(t&3),n)),e}}},Hf={};Hf.sha1=class{constructor(r){const e=this;e.blockSize=512,e._init=[1732584193,4023233417,2562383102,271733878,3285377520],e._key=[1518500249,1859775393,2400959708,3395469782],r?(e._h=r._h.slice(0),e._buffer=r._buffer.slice(0),e._length=r._length):e.reset()}reset(){const r=this;return r._h=r._init.slice(0),r._buffer=[],r._length=0,r}update(r){const e=this;typeof r=="string"&&(r=va.utf8String.toBits(r));const t=e._buffer=zt.concat(e._buffer,r),n=e._length,i=e._length=n+zt.bitLength(r);if(i>9007199254740991)throw new Error("Cannot hash more than 2^53 - 1 bits");const s=new Uint32Array(t);let a=0;for(let o=e.blockSize+n-(e.blockSize+n&e.blockSize-1);o<=i;o+=e.blockSize)e._block(s.subarray(16*a,16*(a+1))),a+=1;return t.splice(0,16*a),e}finalize(){const r=this;let e=r._buffer;const t=r._h;e=zt.concat(e,[zt.partial(1,1)]);for(let n=e.length+2;n&15;n++)e.push(0);for(e.push(Math.floor(r._length/4294967296)),e.push(r._length|0);e.length;)r._block(e.splice(0,16));return r.reset(),t}_f(r,e,t,n){if(r<=19)return e&t|~e&n;if(r<=39)return e^t^n;if(r<=59)return e&t|e&n|t&n;if(r<=79)return e^t^n}_S(r,e){return e<<r|e>>>32-r}_block(r){const e=this,t=e._h,n=Array(80);for(let l=0;l<16;l++)n[l]=r[l];let i=t[0],s=t[1],a=t[2],o=t[3],c=t[4];for(let l=0;l<=79;l++){l>=16&&(n[l]=e._S(1,n[l-3]^n[l-8]^n[l-14]^n[l-16]));const u=e._S(5,i)+e._f(l,s,a,o)+c+n[l]+e._key[Math.floor(l/20)]|0;c=o,o=a,a=e._S(30,s),s=i,i=u}t[0]=t[0]+i|0,t[1]=t[1]+s|0,t[2]=t[2]+a|0,t[3]=t[3]+o|0,t[4]=t[4]+c|0}};const Gf={};Gf.aes=class{constructor(r){const e=this;e._tables=[[[],[],[],[],[]],[[],[],[],[],[]]],e._tables[0][0][0]||e._precompute();const t=e._tables[0][4],n=e._tables[1],i=r.length;let s,a,o,c=1;if(i!==4&&i!==6&&i!==8)throw new Error("invalid aes key size");for(e._key=[a=r.slice(0),o=[]],s=i;s<4*i+28;s++){let l=a[s-1];(s%i===0||i===8&&s%i===4)&&(l=t[l>>>24]<<24^t[l>>16&255]<<16^t[l>>8&255]<<8^t[l&255],s%i===0&&(l=l<<8^l>>>24^c<<24,c=c<<1^(c>>7)*283)),a[s]=a[s-i]^l}for(let l=0;s;l++,s--){const u=a[l&3?s:s-4];s<=4||l<4?o[l]=u:o[l]=n[0][t[u>>>24]]^n[1][t[u>>16&255]]^n[2][t[u>>8&255]]^n[3][t[u&255]]}}encrypt(r){return this._crypt(r,0)}decrypt(r){return this._crypt(r,1)}_precompute(){const r=this._tables[0],e=this._tables[1],t=r[4],n=e[4],i=[],s=[];let a,o,c,l;
2for(let u=0;u<256;u++)s[(i[u]=u<<1^(u>>7)*283)^u]=u;for(let u=a=0;!t[u];u^=o||1,a=s[a]||1){let d=a^a<<1^a<<2^a<<3^a<<4;d=d>>8^d&255^99,t[u]=d,n[d]=u,l=i[c=i[o=i[u]]];let f=l*16843009^c*65537^o*257^u*16843008,h=i[d]*257^d*16843008;for(let p=0;p<4;p++)r[p][u]=h=h<<24^h>>>8,e[p][d]=f=f<<24^f>>>8}for(let u=0;u<5;u++)r[u]=r[u].slice(0),e[u]=e[u].slice(0)}_crypt(r,e){if(r.length!==4)throw new Error("invalid aes block size");const t=this._key[e],n=t.length/4-2,i=[0,0,0,0],s=this._tables[e],a=s[0],o=s[1],c=s[2],l=s[3],u=s[4];let d=r[0]^t[0],f=r[e?3:1]^t[1],h=r[2]^t[2],p=r[e?1:3]^t[3],m=4,A,g,w;for(let b=0;b<n;b++)A=a[d>>>24]^o[f>>16&255]^c[h>>8&255]^l[p&255]^t[m],g=a[f>>>24]^o[h>>16&255]^c[p>>8&255]^l[d&255]^t[m+1],w=a[h>>>24]^o[p>>16&255]^c[d>>8&255]^l[f&255]^t[m+2],p=a[p>>>24]^o[d>>16&255]^c[f>>8&255]^l[h&255]^t[m+3],m+=4,d=A,f=g,h=w;for(let b=0;b<4;b++)i[e?3&-b:b]=u[d>>>24]<<24^u[f>>16&255]<<16^u[h>>8&255]<<8^u[p&255]^t[m++],A=d,d=f,f=h,h=p,p=A;return i}};const Vb={getRandomValues(r){const e=new Uint32Array(r.buffer),t=n=>{let i=987654321;const s=4294967295;return function(){return i=36969*(i&65535)+(i>>16)&s,n=18e3*(n&65535)+(n>>16)&s,(((i<<16)+n&s)/4294967296+.5)*(Math.random()>.5?1:-1)}};for(let n=0,i;n<r.length;n+=4){const s=t((i||Math.random())*4294967296);i=s()*987654071,e[n/4]=s()*4294967296|0}return r}},Yf={};Yf.ctrGladman=class{constructor(r,e){this._prf=r,this._initIv=e,this._iv=e}reset(){this._iv=this._initIv}update(r){return this.calculate(this._prf,r,this._iv)}incWord(r){if((r>>24&255)===255){let e=r>>16&255,t=r>>8&255,n=r&255;e===255?(e=0,t===255?(t=0,n===255?n=0:++n):++t):++e,r=0,r+=e<<16,r+=t<<8,r+=n}else r+=1<<24;return r}incCounter(r){(r[0]=this.incWord(r[0]))===0&&(r[1]=this.incWord(r[1]))}calculate(r,e,t){let n;if(!(n=e.length))return[];const i=zt.bitLength(e);for(let s=0;s<n;s+=4){this.incCounter(t);const a=r.encrypt(t);e[s]^=a[0],e[s+1]^=a[1],e[s+2]^=a[2],e[s+3]^=a[3]}return zt.clamp(e,i)}};const Mn={importKey(r){return new Mn.hmacSha1(va.bytes.toBits(r))},pbkdf2(r,e,t,n){if(t=t||1e4,n<0||t<0)throw new Error("invalid params to pbkdf2");const i=(n>>5)+1<<2;let s,a,o,c,l;const u=new ArrayBuffer(i),d=new DataView(u);let f=0;const h=zt;for(e=va.bytes.toBits(e),l=1;f<(i||1);l++){for(s=a=r.encrypt(h.concat(e,[l])),o=1;o<t;o++)for(a=r.encrypt(a),c=0;c<a.length;c++)s[c]^=a[c];for(o=0;f<(i||1)&&o<s.length;o++)d.setInt32(f,s[o]),f+=4}return u.slice(0,n/8)}};Mn.hmacSha1=class{constructor(r){const e=this,t=e._hash=Hf.sha1,n=[[],[]];e._baseHash=[new t,new t];const i=e._baseHash[0].blockSize/32;r.length>i&&(r=new t().update(r).finalize());for(let s=0;s<i;s++)n[0][s]=r[s]^909522486,n[1][s]=r[s]^1549556828;e._baseHash[0].update(n[0]),e._baseHash[1].update(n[1]),e._resultHash=new t(e._baseHash[0])}reset(){const r=this;r._resultHash=new r._hash(r._baseHash[0]),r._updated=!1}update(r){const e=this;e._updated=!0,e._resultHash.update(r)}digest(){const r=this,e=r._resultHash.finalize(),t=new r._hash(r._baseHash[1]).update(e).finalize();return r.reset(),t}encrypt(r){if(this._updated)throw new Error("encrypt on already updated hmac called!");return this.update(r),this.digest(r)}};const Hb=typeof crypto!=cn&&typeof crypto.getRandomValues==ln,Kf="Invalid password",qf="Invalid signature",xc="zipjs-abort-check-password";function jf(r){return Hb?crypto.getRandomValues(r):Vb.getRandomValues(r)}const Ai=16,Gb="raw",Xf={name:"PBKDF2"},Yb={name:"HMAC"},Kb="SHA-1",qb=Object.assign({hash:Yb},Xf),Pc=Object.assign({iterations:1e3,hash:{name:Kb}},Xf),jb=["deriveBits"],hs=[8,12,16],ms=[16,24,32],un=10,Xb=[0,0,0,0],_a=typeof crypto!=cn,ps=_a&&crypto.subtle,Jf=_a&&typeof ps!=cn,Br=va.bytes,Jb=Gf.aes,$b=Yf.ctrGladman,Zb=Mn.hmacSha1;let $f=_a&&Jf&&typeof ps.importKey==ln,Zf=_a&&Jf&&typeof ps.deriveBits==ln;class eE extends TransformStream{constructor({password:e,rawPassword:t,signed:n,encryptionStrength:i,checkPasswordOnly:s}){super({start(){Object.assign(this,{ready:new Promise(a=>this.resolveReady=a),password:rh(e,t),signed:n,strength:i-1,pending:new Uint8Array})},async transform(a,o){const c=this,{password:l,strength:u,resolveReady:d,ready:f}=c;l?(await rE(c,u,l,lr(a,0,hs[u]+2)),a=lr(a,hs[u]+2),s?o.error(new Error(xc)):d()):await f;const h=new Uint8Array(a.length-un-(a.length-un)%Ai);o.enqueue(eh(c,a,h,0,un,!0))},async flush(a){const{signed:o,ctr:c,hmac:l,pending:u,ready:d}=this;if(l&&c){await d;const f=lr(u,0,u.length-un),h=lr(u,u.length-un);let p=new Uint8Array;
2if(f.length){const m=As(Br,f);l.update(m);const A=c.update(m);p=gs(Br,A)}if(o){const m=lr(gs(Br,l.digest()),0,un);for(let A=0;A<un;A++)if(m[A]!=h[A])throw new Error(qf)}a.enqueue(p)}}})}}class tE extends TransformStream{constructor({password:e,rawPassword:t,encryptionStrength:n}){let i;super({start(){Object.assign(this,{ready:new Promise(s=>this.resolveReady=s),password:rh(e,t),strength:n-1,pending:new Uint8Array})},async transform(s,a){const o=this,{password:c,strength:l,resolveReady:u,ready:d}=o;let f=new Uint8Array;c?(f=await nE(o,l,c),u()):await d;const h=new Uint8Array(f.length+s.length-s.length%Ai);h.set(f,0),a.enqueue(eh(o,s,h,f.length,0))},async flush(s){const{ctr:a,hmac:o,pending:c,ready:l}=this;if(o&&a){await l;let u=new Uint8Array;if(c.length){const d=a.update(As(Br,c));o.update(d),u=gs(Br,d)}i.signature=gs(Br,o.digest()).slice(0,un),s.enqueue(vc(u,i.signature))}}}),i=this}}function eh(r,e,t,n,i,s){const{ctr:a,hmac:o,pending:c}=r,l=e.length-i;c.length&&(e=vc(c,e),t=aE(t,l-l%Ai));let u;for(u=0;u<=l-Ai;u+=Ai){const d=As(Br,lr(e,u,u+Ai));s&&o.update(d);const f=a.update(d);s||o.update(f),t.set(gs(Br,f),u+n)}return r.pending=lr(e,u),t}async function rE(r,e,t,n){const i=await th(r,e,t,lr(n,0,hs[e])),s=lr(n,hs[e]);if(i[0]!=s[0]||i[1]!=s[1])throw new Error(Kf)}async function nE(r,e,t){const n=jf(new Uint8Array(hs[e])),i=await th(r,e,t,n);return vc(n,i)}async function th(r,e,t,n){r.password=null;const i=await iE(Gb,t,qb,!1,jb),s=await sE(Object.assign({salt:n},Pc),i,8*(ms[e]*2+2)),a=new Uint8Array(s),o=As(Br,lr(a,0,ms[e])),c=As(Br,lr(a,ms[e],ms[e]*2)),l=lr(a,ms[e]*2);return Object.assign(r,{keys:{key:o,authentication:c,passwordVerification:l},ctr:new $b(new Jb(o),Array.from(Xb)),hmac:new Zb(c)}),l}async function iE(r,e,t,n,i){if($f)try{return await ps.importKey(r,e,t,n,i)}catch{return $f=!1,Mn.importKey(e)}else return Mn.importKey(e)}async function sE(r,e,t){if(Zf)try{return await ps.deriveBits(r,e,t)}catch{return Zf=!1,Mn.pbkdf2(e,r.salt,Pc.iterations,t)}else return Mn.pbkdf2(e,r.salt,Pc.iterations,t)}function rh(r,e){return e===Z?Pa(r):e}function vc(r,e){let t=r;return r.length+e.length&&(t=new Uint8Array(r.length+e.length),t.set(r,0),t.set(e,r.length)),t}function aE(r,e){if(e&&e>r.length){const t=r;r=new Uint8Array(e),r.set(t,0)}return r}function lr(r,e,t){return r.subarray(e,t)}function gs(r,e){return r.fromBits(e)}function As(r,e){return r.toBits(e)}const ws=12;class oE extends TransformStream{constructor({password:e,passwordVerification:t,checkPasswordOnly:n}){super({start(){Object.assign(this,{password:e,passwordVerification:t}),sh(this,e)},transform(i,s){const a=this;if(a.password){const o=nh(a,i.subarray(0,ws));if(a.password=null,o.at(-1)!=a.passwordVerification)throw new Error(Kf);i=i.subarray(ws)}n?s.error(new Error(xc)):s.enqueue(nh(a,i))}})}}class cE extends TransformStream{constructor({password:e,passwordVerification:t}){super({start(){Object.assign(this,{password:e,passwordVerification:t}),sh(this,e)},transform(n,i){const s=this;let a,o;if(s.password){s.password=null;const c=jf(new Uint8Array(ws));c[ws-1]=s.passwordVerification,a=new Uint8Array(n.length+c.length),a.set(ih(s,c),0),o=ws}else a=new Uint8Array(n.length),o=0;a.set(ih(s,n),o),i.enqueue(a)}})}}function nh(r,e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=ah(r)^e[n],_c(r,t[n]);return t}function ih(r,e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=ah(r)^e[n],_c(r,e[n]);return t}function sh(r,e){const t=[305419896,591751049,878082192];Object.assign(r,{keys:t,crcKey0:new xa(t[0]),crcKey2:new xa(t[2])});for(let n=0;n<e.length;n++)_c(r,e.charCodeAt(n))}function _c(r,e){let[t,n,i]=r.keys;r.crcKey0.append([e]),t=~r.crcKey0.get(),n=ch(Math.imul(ch(n+oh(t)),134775813)+1),r.crcKey2.append([n>>>24]),i=~r.crcKey2.get(),r.keys=[t,n,i]}function ah(r){const e=r.keys[2]|2;return oh(Math.imul(e,e^1)>>>8)}function oh(r){return r&255}function ch(r){return r&4294967295}const lh="Invalid uncompressed size",lE="deflate-raw",uE="deflate64-raw";class dE extends TransformStream{constructor(e,{chunkSize:t,CompressionStreamZlib:n,CompressionStream:i}){super({});const{compressed:s,encrypted:a,useCompressionStream:o,zipCrypto:c,signed:l,level:u}=e,d=this;let f,h,p=super.readable;
2(!a||c)&&l&&(f=new Vf,p=xr(p,f)),s&&(p=dh(p,o,{level:u,chunkSize:t},i,n,i)),a&&(c?p=xr(p,new cE(e)):(h=new tE(e),p=xr(p,h))),uh(d,p,()=>{let m;a&&!c&&(m=h.signature),(!a||c)&&l&&(m=new DataView(f.value.buffer).getUint32(0)),d.signature=m})}}class fE extends TransformStream{constructor(e,{chunkSize:t,DecompressionStreamZlib:n,DecompressionStream:i}){super({});const{zipCrypto:s,encrypted:a,signed:o,signature:c,compressed:l,useCompressionStream:u,deflate64:d}=e;let f,h,p=super.readable;a&&(s?p=xr(p,new oE(e)):(h=new eE(e),p=xr(p,h))),l&&(p=dh(p,u,{chunkSize:t,deflate64:d},i,n,i)),(!a||s)&&o&&(f=new Vf,p=xr(p,f)),uh(this,p,()=>{if((!a||s)&&o){const m=new DataView(f.value.buffer);if(c!=m.getUint32(0,!1))throw new Error(qf)}})}}function uh(r,e,t){e=xr(e,new TransformStream({flush:t})),Object.defineProperty(r,"readable",{get(){return e}})}function dh(r,e,t,n,i,s){const a=e&&n?n:i||s,o=t.deflate64?uE:lE;try{r=xr(r,new a(o,t))}catch(c){if(e)if(i)r=xr(r,new i(o,t));else if(s)r=xr(r,new s(o,t));else throw c;else throw c}return r}function xr(r,e){return r.pipeThrough(e)}const hE="message",mE="start",pE="pull",fh="data",gE="ack",hh="close",mh="deflate",ph="inflate";class AE extends TransformStream{constructor(e,t){super({});const n=this,{codecType:i}=e;let s;i.startsWith(mh)?s=dE:i.startsWith(ph)&&(s=fE),n.outputSize=0;let a=0;const o=new s(e,t),c=super.readable,l=new TransformStream({transform(d,f){d&&d.length&&(a+=d.length,f.enqueue(d))},flush(){Object.assign(n,{inputSize:a})}}),u=new TransformStream({transform(d,f){if(d&&d.length&&(f.enqueue(d),n.outputSize+=d.length,e.outputSize!==Z&&n.outputSize>e.outputSize))throw new Error(lh)},flush(){const{signature:d}=o;Object.assign(n,{signature:d,inputSize:a})}});Object.defineProperty(n,"readable",{get(){return c.pipeThrough(l).pipeThrough(o).pipeThrough(u)}})}}class wE extends TransformStream{constructor(e){let t;super({transform:n,flush(i){t&&t.length&&i.enqueue(t)}});function n(i,s){if(t){const a=new Uint8Array(t.length+i.length);a.set(t),a.set(i,t.length),i=a,t=null}i.length>e?(s.enqueue(i.slice(0,e)),n(i.slice(e),s)):t=i}}}const gh={type:"module"};let Fa,Fc,Ah,Rc=!0;try{Rc=typeof structuredClone==ln&&structuredClone(new DOMException("","AbortError")).code!==Z}catch{}let wh=()=>{};function yE({initModule:r}){wh=r}class Dc{constructor(e,{readable:t,writable:n},{options:i,config:s,streamOptions:a,useWebWorkers:o,transferStreams:c,workerURI:l},u){const{signal:d}=a;return Object.assign(e,{busy:!0,readable:t.pipeThrough(new wE(s.chunkSize)).pipeThrough(new bE(a),{signal:d}),writable:n,options:Object.assign({},i),workerURI:l,transferStreams:c,terminate(){return new Promise(f=>{const{worker:h,busy:p}=e;h?(p?e.resolveTerminated=f:(h.terminate(),f()),e.interface=null):f()})},onTaskFinished(){const{resolveTerminated:f}=e;f&&(e.resolveTerminated=null,e.terminated=!0,e.worker.terminate(),f()),e.busy=!1,u(e)}}),Fa===Z&&(Fa=typeof Worker!=cn),(o&&Fa?EE:yh)(e,s)}}class bE extends TransformStream{constructor({onstart:e,onprogress:t,size:n,onend:i}){let s=0;super({async start(){e&&await Mc(e,n)},async transform(a,o){s+=a.length,t&&await Mc(t,s,n),o.enqueue(a)},async flush(){i&&await Mc(i,s)}})}}async function Mc(r,...e){try{await r(...e)}catch{}}function yh(r,e){return{run:()=>kE(r,e)}}function EE(r,e){const{baseURI:t,chunkSize:n}=e;let{wasmURI:i}=e;if(!r.interface){typeof i==ln&&(i=i());let s;try{s=Ra(r.workerURI,t,r)}catch{return Fa=!1,yh(r,e)}Object.assign(r,{worker:s,interface:{run:()=>TE(r,{chunkSize:n,wasmURI:i,baseURI:t})}})}return r.interface}async function kE({options:r,readable:e,writable:t,onTaskFinished:n},i){let s;try{if(!r.useCompressionStream)try{await wh(i)}catch{r.useCompressionStream=!0}s=new AE(r,i),await e.pipeThrough(s).pipeTo(t,{preventClose:!0,preventAbort:!0});const{signature:a,inputSize:o,outputSize:c}=s;return{signature:a,inputSize:o,outputSize:c}}catch(a){throw s&&(a.outputSize=s.outputSize),a}finally{n()}}async function TE(r,e){let t,n;const i=new Promise((d,f)=>{t=d,n=f});Object.assign(r,{reader:null,writer:null,resolveResult:t,rejectResult:n,result:i});const{readable:s,options:a}=r,{writable:o,closed:c}=SE(r.writable),l=Da({type:mE,options:a,config:e,readable:s,writable:o},r);
2l||Object.assign(r,{reader:s.getReader(),writer:o.getWriter()});const u=await i;return l||await o.getWriter().close(),await c,u}function SE(r){const{writable:e,readable:t}=new TransformStream,n=t.pipeTo(r,{preventClose:!0});return{writable:e,closed:n}}function Ra(r,e,t,n,i=!0){let s,a,o;if(Fc===Z){const c=typeof r==ln;c?a=r(i):a=r;const l=a.startsWith("data:"),u=a.startsWith("blob:");if(l||u){n===Z&&(n=!1),n&&(o=gh);try{s=new Worker(a,o)}catch(d){if(u)try{URL.revokeObjectURL(a)}catch{}if(c&&u)return Ra(r,e,t,n,!1);if(n)throw d;return Ra(r,e,t,!0,!1)}}else{n===Z&&(n=!0),n&&(o=gh);try{a=new URL(a,e)}catch{}try{s=new Worker(a,o)}catch(d){if(n)throw d;return Ra(r,e,t,!1,i)}}Fc=a,Ah=o}else s=new Worker(Fc,Ah);return s.addEventListener(hE,c=>CE(c,t)),s}function Da(r,{worker:e,writer:t,onTaskFinished:n,transferStreams:i}){try{const{value:s,readable:a,writable:o}=r,c=[];if(s&&(r.value=s,c.push(r.value.buffer)),i&&Rc?(a&&c.push(a),o&&c.push(o)):r.readable=r.writable=null,c.length)try{return e.postMessage(r,c),!0}catch{Rc=!1,r.readable=r.writable=null,e.postMessage(r)}else e.postMessage(r)}catch(s){throw t&&t.releaseLock(),n(),s}}async function CE({data:r},e){const{type:t,value:n,messageId:i,result:s,error:a}=r,{reader:o,writer:c,resolveResult:l,rejectResult:u,onTaskFinished:d}=e;try{if(a){const{message:h,stack:p,code:m,name:A,outputSize:g}=a,w=new Error(h);Object.assign(w,{stack:p,code:m,name:A,outputSize:g}),f(w)}else{if(t==pE){const{value:h,done:p}=await o.read();Da({type:fh,value:h,done:p,messageId:i},e)}t==fh&&(await c.ready,await c.write(new Uint8Array(n)),Da({type:gE,messageId:i},e)),t==hh&&f(null,s)}}catch(h){Da({type:hh,messageId:i},e),f(h)}function f(h,p){h?u(h):l(p),c&&c.releaseLock(),d()}}let Un=[];const Uc=[];let bh=0;async function Eh(r,e){const{options:t,config:n}=e,{transferStreams:i,useWebWorkers:s,useCompressionStream:a,compressed:o,signed:c,encrypted:l}=t,{workerURI:u,maxWorkers:d}=n;e.transferStreams=i||i===Z;const f=!o&&!c&&!l&&!e.transferStreams;return e.useWebWorkers=!f&&(s||s===Z&&n.useWebWorkers),e.workerURI=e.useWebWorkers&&u?u:Z,t.useCompressionStream=a||a===Z&&n.useCompressionStream,(await h()).run();async function h(){const m=Un.find(A=>!A.busy);if(m)return kh(m),new Dc(m,r,e,p);if(Un.length<d){const A={indexWorker:bh};return bh++,Un.push(A),new Dc(A,r,e,p)}else return new Promise(A=>Uc.push({resolve:A,stream:r,workerOptions:e}))}function p(m){if(Uc.length){const[{resolve:A,stream:g,workerOptions:w}]=Uc.splice(0,1);A(new Dc(m,g,w,p))}else m.worker?(kh(m),IE(m,e)):Un=Un.filter(A=>A!=m)}}function IE(r,e){const{config:t}=e,{terminateWorkerTimeout:n}=t;Number.isFinite(n)&&n>=0&&(r.terminated?r.terminated=!1:r.terminateTimeout=setTimeout(async()=>{Un=Un.filter(i=>i!=r);try{await r.terminate()}catch{}},n))}function kh(r){const{terminateTimeout:e}=r;e&&(clearTimeout(e),r.terminateTimeout=null)}const BE="Writer iterator completed too soon",xE=64*1024,PE="writable";class Th{constructor(){this.size=0}init(){this.initialized=!0}}let Sh=class extends Th{get readable(){const e=this,{chunkSize:t=xE}=e,n=new ReadableStream({start(){this.chunkOffset=0},async pull(i){const{offset:s=0,size:a,diskNumberStart:o}=n,{chunkOffset:c}=this,l=a===Z?t:Math.min(t,a-c),u=await Ft(e,s+c,l,o);i.enqueue(u),c+t>a||a===Z&&!u.length&&l?i.close():this.chunkOffset+=t}});return n}};class vE extends Sh{constructor(e){super(),Object.assign(this,{blob:e,size:e.size})}async readUint8Array(e,t){const n=this,i=e+t;let a=await(e||i<n.size?n.blob.slice(e,i):n.blob).arrayBuffer();return a.byteLength>t&&(a=a.slice(e,i)),new Uint8Array(a)}}class _E extends Sh{constructor(e){super(),this.readers=e}async init(){const e=this,{readers:t}=e;e.lastDiskNumber=0,e.lastDiskOffset=0,await Promise.all(t.map(async(n,i)=>{await n.init(),i!=t.length-1&&(e.lastDiskOffset+=n.size),e.size+=n.size})),super.init()}async readUint8Array(e,t,n=0){const i=this,{readers:s}=this;let a,o=n;o==-1&&(o=s.length-1);let c=e;for(;s[o]&&c>=s[o].size;)c-=s[o].size,o++;const l=s[o];if(l){const u=l.size;if(c+t<=u)a=await Ft(l,c,t);else{const d=u-c;a=new Uint8Array(t);const f=await Ft(l,c,d);a.set(f,0);
2const h=await i.readUint8Array(e+d,t-d,n);a.set(h,d),f.length+h.length<t&&(a=a.subarray(0,f.length+h.length))}}else a=new Uint8Array;return i.lastDiskNumber=Math.max(o,i.lastDiskNumber),a}}class Ch extends Th{constructor(e,t=4294967295){super();const n=this;Object.assign(n,{diskNumber:0,diskOffset:0,size:0,maxSize:t,availableSize:t});let i,s,a;const o=new WritableStream({async write(u){const{availableSize:d}=n;if(a)u.length>=d?(await c(u.subarray(0,d)),await l(),n.diskOffset+=i.size,n.diskNumber++,a=null,await this.write(u.subarray(d))):await c(u);else{const{value:f,done:h}=await e.next();if(h&&!f)throw new Error(BE);i=f,i.size=0,i.maxSize&&(n.maxSize=i.maxSize),n.availableSize=n.maxSize,await dn(i),s=f.writable,a=s.getWriter(),await this.write(u)}},async close(){await a.ready,await l()}});Object.defineProperty(n,PE,{get(){return o}});async function c(u){const d=u.length;d&&(await a.ready,await a.write(u),i.size+=d,n.size+=d,n.availableSize-=d)}async function l(){await a.close()}}}class Oc{constructor(e){return Array.isArray(e)&&(e=new _E(e)),e instanceof ReadableStream&&(e={readable:e}),e}}class Ih{constructor(e){return e.writable===Z&&typeof e.next==ln&&(e=new Ch(e)),e instanceof WritableStream&&(e={writable:e}),e.size===Z&&(e.size=0),e instanceof Ch||Object.assign(e,{diskNumber:0,diskOffset:0,availableSize:fs,maxSize:fs}),e}}async function dn(r,e){if(r.init&&!r.initialized)await r.init(e);else return Promise.resolve()}function Ft(r,e,t,n){return r.readUint8Array(e,t,n)}const Bh="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split(""),FE=Bh.length==256;function RE(r){if(FE){let e="";for(let t=0;t<r.length;t++)e+=Bh[r[t]];return e}else return new TextDecoder().decode(r)}function Ma(r,e){return e&&e.trim().toLowerCase()=="cp437"?RE(r):new TextDecoder(e).decode(r)}const xh="filename",Ph="rawFilename",Nc="comment",vh="rawComment",Qc="uncompressedSize",_h="compressedSize",Fh="offset",Rh="diskNumberStart",Ua="lastModDate",Lc="rawLastModDate",zc="lastAccessDate",DE="rawLastAccessDate",Wc="creationDate",Dh="rawCreationDate",Mh="internalFileAttributes",Uh="externalFileAttributes",Oh="msdosAttributesRaw",Nh="msdosAttributes",Qh="msDosCompatible",Vc="zip64",Lh="encrypted",zh="version",Wh="versionMadeBy",Vh="zipCrypto",Oa="directory",Hh="executable",Gh="compressionMethod",Yh="signature",Kh="extraField",ME="extraFieldInfoZip",UE="extraFieldUnix",qh="uid",jh="gid",Xh="unixMode",Jh="setuid",$h="setgid",Zh="sticky",OE=[xh,Ph,Qc,_h,Ua,Lc,Nc,vh,zc,Wc,Dh,Fh,Rh,Mh,Uh,Oh,Nh,Qh,Vc,Lh,zh,Wh,Vh,Oa,Hh,Gh,Yh,Kh,UE,ME,qh,jh,Xh,Jh,$h,Zh,"bitFlag","filenameUTF8","commentUTF8","rawExtraField","extraFieldZip64","extraFieldUnicodePath","extraFieldUnicodeComment","extraFieldAES","extraFieldNTFS","extraFieldExtendedTimestamp"];class Na{constructor(e){OE.forEach(t=>this[t]=e[t])}}const NE="filenameEncoding",QE="commentEncoding",LE="decodeText",zE="extractPrependedData",WE="extractAppendedData",em="password",tm="rawPassword",rm="passThrough",nm="signal",VE="checkPasswordOnly",HE="checkOverlappingEntryOnly",GE="checkOverlappingEntry",YE="checkSignature",im="useWebWorkers",sm="useCompressionStream",am="transferStreams",om="preventClose",KE="encryptionStrength",qE="extendedTimestamp",jE="keepOrder",XE="level",JE="bufferedWrite",$E="createTempStream",ZE="dataDescriptorSignature",ek="useUnicodeFileNames",tk="dataDescriptor",rk="supportZip64SplitFile",nk="encodeText",cm="offset",lm="usdz",ik="unixExtraFieldType",Hc="File format is not recognized",sk="End of central directory not found",ak="End of Zip64 central directory locator not found",ok="Central directory header not found",ck="Local file header not found",lk="Zip64 extra field not found",uk="File contains encrypted entry",dk="Encryption method not supported",um="Compression method not supported",dm="Split zip file",fk="Overlapping entry found",fm="utf-8",hk="UTF8",hm="cp437",mk=[[Qc,et],[_h,et],[Fh,et],[Rh,Le]],pk={[Le]:{getValue:Je,bytes:4},[et]:{getValue:wi,bytes:8}};class gk{constructor(e,t={}){Object.assign(this,{reader:new Oc(e),options:t,config:Lf(),readRanges:[]})}async*getEntriesGenerator(e={}){const t=this;let{reader:n}=t;const{config:i}=t;if(await dn(n),(n.size===Z||!n.readUint8Array)&&(n=new vE(await new Response(n.readable).blob()),await dn(n)),n.size<Ur)throw new Error(Hc);n.chunkSize=zf(i);const s=await Tk(n,Tf,n.size,Ur,Le*16);if(!s){const v=await Ft(n,0,4),R=$e(v);throw Je(R)==pc?new Error(dm):new Error(sk)}const a=$e(s);
2let o=Je(a,12),c=Je(a,16);const l=s.offset,u=St(a,20),d=l+Ur+u;let f=St(a,4);const h=n.lastDiskNumber||0;let p=St(a,6),m=St(a,8),A=0,g=0;if(c==et||o==et||m==Le||p==Le){const v=await Ft(n,s.offset-cs,cs),R=$e(v);if(Je(R,0)==Sf){c=wi(R,8);let M=await Ft(n,c,ls,-1),z=$e(M);const W=s.offset-cs-ls;if(Je(z,0)!=Ac&&c!=W){const H=c;c=W,c>H&&(A=c-H),M=await Ft(n,c,ls,-1),z=$e(M)}if(Je(z,0)!=Ac)throw new Error(ak);f==Le&&(f=Je(z,16)),p==Le&&(p=Je(z,20)),m==Le&&(m=wi(z,32)),o==et&&(o=wi(z,40)),c-=o}}if(c>=n.size&&(A=n.size-c-o-Ur,c=n.size-o-Ur),h!=f)throw new Error(dm);if(c<0)throw new Error(Hc);let w=0,b=await Ft(n,c,o,p),k=$e(b);if(o){const v=s.offset-o;if(Je(k,w)!=gc&&c!=v){const R=c;c=v,c>R&&(A+=c-R),b=await Ft(n,c,o,p),k=$e(b)}}const S=s.offset-c-(n.lastDiskOffset||0);if(o!=S&&S>=0&&(o=S,b=await Ft(n,c,o,p),k=$e(b)),c<0||c>=n.size)throw new Error(Hc);const x=Rt(t,e,NE),B=Rt(t,e,QE);for(let v=0;v<m;v++){const R=new Ak(n,i,t.options);if(Je(k,w)!=gc)throw new Error(ok);mm(R,k,w+6);const M=!!R.bitFlag.languageEncodingFlag,z=w+46,W=z+R.filenameLength,H=W+R.extraFieldLength,U=St(k,w+4),j=U>>8==0,ce=U>>8==3,ee=b.subarray(z,W),fe=St(k,w+32),he=H+fe,G=b.subarray(H,he),ue=M,we=M,_e=Je(k,w+38),Ye=_e&Ir,xe={readOnly:!!(Ye&Tc),hidden:!!(Ye&Sc),system:!!(Ye&Cc),directory:!!(Ye&Ea),archive:!!(Ye&Ic)},ne=Je(k,w+42)+A,Pe=Rt(t,e,LE)||Ma,Ee=ue?fm:x||hm,me=we?fm:B||hm;let Fe=Pe(ee,Ee);Fe===Z&&(Fe=Ma(ee,Ee));let Qe=Pe(G,me);Qe===Z&&(Qe=Ma(G,me)),Object.assign(R,{versionMadeBy:U,msDosCompatible:j,compressedSize:0,uncompressedSize:0,commentLength:fe,offset:ne,diskNumberStart:St(k,w+34),internalFileAttributes:St(k,w+36),externalFileAttributes:_e,msdosAttributesRaw:Ye,msdosAttributes:xe,rawFilename:ee,filenameUTF8:ue,commentUTF8:we,rawExtraField:b.subarray(W,H),rawComment:G,filename:Fe,comment:Qe}),g=Math.max(ne,g),pm(R,R,k,w+6);const ze=R.externalFileAttributes>>16&Le;R.unixMode===Z&&(ze&(ka|ds|us))!=0&&(R.unixMode=ze);const T=!!(R.unixMode&Ta),V=!!(R.unixMode&Sa),F=!!(R.unixMode&Ca),O=R.unixMode!==Z?(R.unixMode&ds)!=0:ce&&(ze&ds)!=0,K=R.unixMode!==Z&&(R.unixMode&Rf)==us,N=(ze&Rf)==us;Object.assign(R,{setuid:T,setgid:V,sticky:F,unixExternalUpper:ze,internalFileAttribute:R.internalFileAttributes,externalFileAttribute:R.externalFileAttributes,executable:O,directory:K||N||j&&xe.directory||Fe.endsWith(Ia)&&!R.uncompressedSize,zipCrypto:R.encrypted&&!R.extraFieldAES});const X=new Na(R);X.getData=(oe,ie)=>R.getData(oe,X,t.readRanges,ie),X.arrayBuffer=async oe=>{const ie=new TransformStream,[ke]=await Promise.all([new Response(ie.readable).arrayBuffer(),R.getData(ie,X,t.readRanges,oe)]);return ke},w=he;const{onprogress:re}=e;if(re)try{await re(v+1,m,new Na(R))}catch{}yield X}const I=Rt(t,e,zE),C=Rt(t,e,WE);return I&&(t.prependedData=g>0?await Ft(n,0,g):new Uint8Array),t.comment=u?await Ft(n,l+Ur,u):new Uint8Array,C&&(t.appendedData=d<n.size?await Ft(n,d,n.size-d):new Uint8Array),!0}async getEntries(e={}){const t=[];for await(const n of this.getEntriesGenerator(e))t.push(n);return t}async close(){}}class Ak{constructor(e,t,n){Object.assign(this,{reader:e,config:t,options:n})}async getData(e,t,n,i={}){const s=this,{reader:a,offset:o,diskNumberStart:c,extraFieldAES:l,extraFieldZip64:u,compressionMethod:d,config:f,bitFlag:h,signature:p,rawLastModDate:m,uncompressedSize:A,compressedSize:g}=s,{dataDescriptor:w}=h,b=t.localDirectory={},k=await Ft(a,o,Dn,c),S=$e(k);let x=Rt(s,i,em),B=Rt(s,i,tm);const I=Rt(s,i,rm);if(x=x&&x.length&&x,B=B&&B.length&&B,l&&l.originalCompressionMethod!=bf)throw new Error(um);if(d!=yf&&d!=hc&&d!=mc&&!I)throw new Error(um);if(Je(S,0)!=Ef)throw new Error(ck);mm(b,S,4);const{extraFieldLength:C,filenameLength:v,lastAccessDate:R,creationDate:M}=b;b.rawExtraField=C?await Ft(a,o+Dn+v,C,c):new Uint8Array,pm(s,b,S,4,!0),Object.assign(t,{lastAccessDate:R,creationDate:M});const z=s.encrypted&&b.encrypted&&!I,W=z&&!l;if(I||(t.zipCrypto=W),z){if(!W&&l.strength===Z)throw new Error(dk);if(!x&&!B)throw new Error(uk)}const H=o+Dn+v+C,U=g,j=a.readable;Object.assign(j,{diskNumberStart:c,offset:H,size:U});const ce=Rt(s,i,nm),ee=Rt(s,i,VE);let fe=Rt(s,i,GE);const he=Rt(s,i,HE);he&&(fe=!0);const{onstart:G,onprogress:ue,onend:we}=i,_e=d==mc;let Ye=Rt(s,i,sm);_e&&(Ye=!1);const xe={options:{codecType:ph,password:x,rawPassword:B,zipCrypto:W,encryptionStrength:l&&l.strength,signed:Rt(s,i,YE)&&!I,passwordVerification:W&&(w?m>>>8&Ir:p>>>24&Ir),outputSize:I?g:A,signature:p,compressed:d!=0&&!I,encrypted:s.encrypted&&!I,useWebWorkers:Rt(s,i,im),useCompressionStream:Ye,transferStreams:Rt(s,i,am),deflate64:_e,checkPasswordOnly:ee},config:f,streamOptions:{signal:ce,size:U,onstart:G,onprogress:ue,onend:we}};fe&&await kk({reader:a,fileEntry:t,offset:o,diskNumberStart:c,signature:p,compressedSize:g,uncompressedSize:A,dataOffset:H,dataDescriptor:w||b.bitFlag.dataDescriptor,extraFieldZip64:u||b.extraFieldZip64,readRanges:n});let ne;try{if(!he){ee&&(e=new WritableStream),e=new Ih(e),await dn(e,I?g:A),{writable:ne}=e;const{outputSize:Pe}=await Eh({readable:j,writable:ne},xe);if(e.size+=Pe,Pe!=(I?g:A))throw new Error(lh)}}catch(Pe){if(Pe.outputSize!==Z&&(e.size+=Pe.outputSize),!ee||Pe.message!=xc)throw Pe}finally{!Rt(s,i,om)&&ne&&!ne.locked&&await ne.getWriter().close()}return ee||he?Z:e.getData?e.getData():ne}}function mm(r,e,t){const n=r.rawBitFlag=St(e,t+2),i=(n&bc)==bc,s=Je(e,t+6);Object.assign(r,{encrypted:i,version:St(e,t),bitFlag:{level:(n&Db)>>1,dataDescriptor:(n&Ec)==Ec,languageEncodingFlag:(n&kc)==kc},rawLastModDate:s,lastModDate:Sk(s),filenameLength:St(e,t+22),extraFieldLength:St(e,t+24)})}function pm(r,e,t,n,i){const{rawExtraField:s}=e,a=e.extraField=new Map,o=$e(new Uint8Array(s));let c=0;try{for(;c<s.length;){const w=St(o,c),b=St(o,c+2);a.set(w,{type:w,data:s.slice(c+4,c+4+b)}),c+=4+b}}catch{}const l=St(t,n+4);Object.assign(e,{signature:Je(t,n+Bc),compressedSize:Je(t,n+pi),uncompressedSize:Je(t,n+gi)});const u=a.get(wc);u&&(wk(u,e),e.extraFieldZip64=u);const d=a.get(Fb);d&&(gm(d,xh,Ph,e,r),e.extraFieldUnicodePath=d);const f=a.get(Rb);f&&(gm(f,Nc,vh,e,r),e.extraFieldUnicodeComment=f);const h=a.get(Bf);h?(yk(h,e,l),e.extraFieldAES=h):e.compressionMethod=l;const p=a.get(xf);
2p&&(bk(p,e),e.extraFieldNTFS=p);const m=a.get(Ff);if(m)Am(m,e,!1),e.extraFieldUnix=m;else{const w=a.get(_f);w&&(Am(w,e,!0),e.extraFieldInfoZip=w)}const A=a.get(yc);A&&(Ek(A,e,i),e.extraFieldExtendedTimestamp=A);const g=a.get(vf);g&&(e.extraFieldUSDZ=g)}function wk(r,e){e.zip64=!0;const t=$e(r.data),n=mk.filter(([i,s])=>e[i]==s);for(let i=0,s=0;i<n.length;i++){const[a,o]=n[i];if(e[a]==o){const c=pk[o];e[a]=r[a]=c.getValue(t,s),s+=c.bytes}else if(r[a])throw new Error(lk)}}function gm(r,e,t,n,i){const s=$e(r.data),a=new xa;a.append(i[t]);const o=$e(new Uint8Array(4));o.setUint32(0,a.get(),!0);const c=Je(s,1);Object.assign(r,{version:fn(s,0),[e]:Ma(r.data.subarray(5)),valid:!i.bitFlag.languageEncodingFlag&&c==Je(o,0)}),r.valid&&(n[e]=r[e],n[e+hk]=!0)}function yk(r,e,t){const n=$e(r.data),i=fn(n,4);Object.assign(r,{vendorVersion:fn(n,0),vendorId:fn(n,2),strength:i,originalCompressionMethod:t,compressionMethod:St(n,5)}),e.compressionMethod=r.compressionMethod}function bk(r,e){const t=$e(r.data);let n=4,i;try{for(;n<r.data.length&&!i;){const s=St(t,n),a=St(t,n+2);s==Pf&&(i=r.data.slice(n+4,n+4+a)),n+=4+a}}catch{}try{if(i&&i.length==24){const s=$e(i),a=s.getBigUint64(0,!0),o=s.getBigUint64(8,!0),c=s.getBigUint64(16,!0);Object.assign(r,{rawLastModDate:a,rawLastAccessDate:o,rawCreationDate:c});const l=Gc(a),u=Gc(o),d=Gc(c),f={lastModDate:l,lastAccessDate:u,creationDate:d};Object.assign(r,f),Object.assign(e,f)}}catch{}}function Am(r,e,t){try{const n=$e(new Uint8Array(r.data));let i=0;const s=fn(n,i++),a=fn(n,i++),o=r.data.subarray(i,i+a);i+=a;const c=wm(o),l=fn(n,i++),u=r.data.subarray(i,i+l);i+=l;const d=wm(u);let f=Z;if(!t&&i+2<=r.data.length){const h=r.data;f=new DataView(h.buffer,h.byteOffset+i,2).getUint16(0,!0)}Object.assign(r,{version:s,uid:c,gid:d,unixMode:f}),c!==Z&&(e.uid=c),d!==Z&&(e.gid=d),f!==Z&&(e.unixMode=f)}catch{}}function wm(r){const e=new Uint8Array(4);return e.set(r,0),new DataView(e.buffer,e.byteOffset,4).getUint32(0,!0)}function Ek(r,e,t){const n=$e(r.data),i=fn(n,0),s=[],a=[];t?((i&1)==1&&(s.push(Ua),a.push(Lc)),(i&2)==2&&(s.push(zc),a.push(DE)),(i&4)==4&&(s.push(Wc),a.push(Dh))):r.data.length>=5&&(s.push(Ua),a.push(Lc));let o=1;s.forEach((c,l)=>{if(r.data.length>=o+4){const u=Je(n,o);e[c]=r[c]=new Date(u*1e3);const d=a[l];r[d]=u}o+=4})}async function kk({reader:r,fileEntry:e,offset:t,diskNumberStart:n,signature:i,compressedSize:s,uncompressedSize:a,dataOffset:o,dataDescriptor:c,extraFieldZip64:l,readRanges:u}){let d=0;if(n)for(let p=0;p<n;p++){const m=r.readers[p];d+=m.size}let f=0;if(c&&(l?f=If:f=Cf),f){const p=await Ft(r,o+s,f+ba,n);if(Je($e(p),0)==kf){const A=Je($e(p),4);let g,w;l?(g=wi($e(p),8),w=wi($e(p),16)):(g=Je($e(p),8),w=Je($e(p),12)),(e.encrypted&&!e.zipCrypto||A==i)&&g==s&&w==a&&(f+=ba)}}const h={start:d+t,end:d+o+s+f,fileEntry:e};for(const p of u)if(p.fileEntry!=e&&h.start>=p.start&&h.start<p.end){const m=new Error(fk);throw m.overlappingEntry=p.fileEntry,m}u.push(h)}async function Tk(r,e,t,n,i){const s=new Uint8Array(4),a=$e(s);Ck(a,0,e);const o=n+i;return await c(n)||await c(Math.min(o,t));async function c(l){const u=t-l,d=await Ft(r,u,l);for(let f=d.length-n;f>=0;f--)if(d[f]==s[0]&&d[f+1]==s[1]&&d[f+2]==s[2]&&d[f+3]==s[3])return{offset:u+f,buffer:d.slice(f,f+n).buffer}}}function Rt(r,e,t){return e[t]===Z?r.options[t]:e[t]}function Sk(r){const e=(r&4294901760)>>16,t=r&Le;try{return new Date(1980+((e&65024)>>9),((e&480)>>5)-1,e&31,(t&63488)>>11,(t&2016)>>5,(t&31)*2,0)}catch{}}function Gc(r){return new Date(Number(r/BigInt(1e4)-BigInt(116444736e5)))}function fn(r,e){return r.getUint8(e)}function St(r,e){return r.getUint16(e,!0)}function Je(r,e){return r.getUint32(e,!0)}function wi(r,e){return Number(r.getBigUint64(e,!0))}function Ck(r,e,t){r.setUint32(e,t,!0)}function $e(r){return new DataView(r.buffer)}const Ik="File already exists",Bk="Zip file comment exceeds 64KB",xk="File entry comment exceeds 64KB",Pk="File entry name exceeds 64KB",ym="Version exceeds 65535",vk="The strength must equal 1, 2, or 3",_k="Extra field type exceeds 65535",Fk="Extra field data exceeds 64KB",bm="Zip64 is not supported (set the 'zip64' option to 'true')",Rk="Undefined uncompressed size",Dk="Zip file not empty",Mk="Invalid uid (must be integer 0..2^32-1)",Uk="Invalid gid (must be integer 0..2^32-1)",Ok="Invalid UNIX mode (must be integer 0..65535)",Nk="Invalid unixExtraFieldType (must be 'infozip' or 'unix')",Qk="Invalid msdosAttributesRaw (must be integer 0..255)",Lk="Invalid msdosAttributes (must be an object with boolean flags)",Em=new Uint8Array([7,0,2,0,65,69,3,0,0]),km="infozip",Tm="unix";let Yc=0;const Sm=[];class zk{constructor(e,t={}){e=new Ih(e);const n=e.availableSize!==Z&&e.availableSize>0&&e.availableSize!==fs&&e.maxSize!==Z&&e.maxSize>0&&e.maxSize!==fs;Object.assign(this,{writer:e,addSplitZipSignature:n,options:t,config:Lf(),files:new Map,filenames:new Set,offset:t[cm]===Z?e.size||e.writable.size||0:t[cm],pendingEntriesSize:0,pendingAddFileCalls:new Set,bufferedWrites:0})}async prependZip(e){if(this.filenames.size)throw new Error(Dk);e=new Oc(e);const t=new gk(e.readable),n=await t.getEntries();await t.close(),await e.readable.pipeTo(this.writer.writable,{preventClose:!0,preventAbort:!0}),this.writer.size=this.offset=e.size,this.filenames=new Set(n.map(i=>i.filename)),this.files=new Map(n.map(i=>{const{version:s,compressionMethod:a,lastModDate:o,lastAccessDate:c,creationDate:l,rawFilename:u,bitFlag:d,encrypted:f,uncompressedSize:h,compressedSize:p,diskOffset:m,diskNumber:A,zip64:g}=i;let{rawExtraFieldZip64:w,rawExtraFieldAES:b,rawExtraFieldExtendedTimestamp:k,rawExtraFieldNTFS:S,rawExtraFieldUnix:x,rawExtraField:B}=i;const{level:I,languageEncodingFlag:C,dataDescriptor:v}=d;w=w||new Uint8Array,b=b||new Uint8Array,k=k||new Uint8Array,S=S||new Uint8Array,x=i.rawExtraFieldUnix||new Uint8Array,B=B||new Uint8Array;const R=Ie(w,b,k,S,x,B),M=g&&h>et,z=g&&p>et,{headerArray:W,headerView:H}=Bm({version:s,bitFlag:xm(I,C,v,f,a),compressionMethod:a,uncompressedSize:h,compressedSize:p,lastModDate:o,rawFilename:u,zip64CompressedSize:z,zip64UncompressedSize:M,extraFieldLength:R});return Object.assign(i,{zip64UncompressedSize:M,zip64CompressedSize:z,zip64Offset:g&&this.offset-m>et,zip64DiskNumberStart:g&&A>Le,rawExtraFieldZip64:w,rawExtraFieldAES:b,rawExtraFieldExtendedTimestamp:k,rawExtraFieldNTFS:S,rawExtraFieldUnix:x,rawExtraField:B,extendedTimestamp:k.length>0||S.length>0,extraFieldExtendedTimestampFlag:1+(c?2:0)+(l?4:0),headerArray:W,headerView:H}),[i.filename,i]}))}async add(e="",t,n={}){const i=this,{pendingAddFileCalls:s,config:a}=i;Yc<a.maxWorkers?Yc++:await new Promise(c=>Sm.push(c));let o;try{if(e=e.trim(),i.filenames.has(e))throw new Error(Ik);return i.filenames.add(e),o=Vk(i,e,t,n),s.add(o),await o}catch(c){throw i.filenames.delete(e),c}finally{s.delete(o);const c=Sm.shift();c?c():Yc--}}remove(e){const{filenames:t,files:n}=this;if(typeof e=="string"&&(e=n.get(e)),e&&e.filename!==Z){const{filename:i}=e;if(t.has(i)&&n.has(i))return t.delete(i),n.delete(i),!0}return!1}async close(e=new Uint8Array,t={}){const n=this,{pendingAddFileCalls:i,writer:s}=this,{writable:a}=s;for(;i.size;)await Promise.allSettled(Array.from(i));return await $k(n,e,t),Te(n,t,om)||await a.getWriter().close(),s.getData?s.getData():a}}class Wk{constructor(e={}){const{readable:t,writable:n}=new TransformStream;this.readable=t,this.zipWriter=new zk(n,e)}transform(e){const{readable:t,writable:n}=new TransformStream({flush:()=>{this.zipWriter.close()}});return this.zipWriter.add(e,t),{readable:this.readable,writable:n}}writable(e){const{readable:t,writable:n}=new TransformStream;return this.zipWriter.add(e,t),n}close(e=Z,t={}){return this.zipWriter.close(e,t)}}async function Vk(r,e,t,n){e=e.trim();
2let i=Te(r,n,Qh),s=Te(r,n,Wh,i?20:768);const a=Te(r,n,Hh),o=Te(r,n,qh),c=Te(r,n,jh);let l=Te(r,n,Xh);const u=Te(r,n,ik);let d=Te(r,n,Jh),f=Te(r,n,$h),h=Te(r,n,Zh);if(o!==Z&&(o<0||o>et))throw new Error(Mk);if(c!==Z&&(c<0||c>et))throw new Error(Uk);if(l!==Z&&(l<0||l>Le))throw new Error(Ok);if(u!==Z&&u!==km&&u!==Tm)throw new Error(Nk);let p=Te(r,n,Oh),m=Te(r,n,Nh);const A=o!==Z||c!==Z||l!==Z||u,g=p!==Z||m!==Z;if(A?(i=!1,s=s&Le|768):g&&(i=!0,s=s&Ir),p!==Z&&(p<0||p>Ir))throw new Error(Qk);if(m&&typeof m!==Qb)throw new Error(Lk);if(s>Le)throw new Error(ym);let w=Te(r,n,Uh,0);!n[Oa]&&e.endsWith(Ia)&&(n[Oa]=!0);const b=Te(r,n,Oa);b?(e.endsWith(Ia)||(e+=Ia),w===0&&(w=Ea,i||(w|=(us|ds|ka)<<16))):!i&&w===0&&(a?w=(ds|ka)<<16:w=ka<<16);let k;i||(k=w>>16&Le,l=l===Z?k:l&Le,d?l|=Ta:d=!!(l&Ta),f?l|=Sa:f=!!(l&Sa),h?l|=Ca:h=!!(l&Ca),b&&(l|=us),w=(l&Le)<<16|w&Ir),{msdosAttributesRaw:p,msdosAttributes:m}=qk(p,m),g&&(w=w&et|p&Ir);const S=Te(r,n,nk,Pa);let x=S(e);if(x===Z&&(x=Pa(e)),Ie(x)>Le)throw new Error(Pk);const B=n[Nc]||"";let I=S(B);if(I===Z&&(I=Pa(B)),Ie(I)>Le)throw new Error(xk);const C=Te(r,n,zh,Nb);if(C>Le)throw new Error(ym);const v=Te(r,n,Ua,new Date),R=Te(r,n,zc),M=Te(r,n,Wc),z=Te(r,n,Mh,0),W=Te(r,n,rm);let H,U;W||(H=Te(r,n,em),U=Te(r,n,tm));const j=Te(r,n,KE,3),ce=Te(r,n,Vh),ee=Te(r,n,qE,!0),fe=Te(r,n,jE,!0),he=Te(r,n,im),G=Te(r,n,am,!0),ue=Te(r,n,JE),we=Te(r,n,$E),_e=Te(r,n,ZE,!1),Ye=Te(r,n,nm),xe=Te(r,n,ek,!0),ne=Te(r,n,Gh);let Pe=Te(r,n,XE),Ee=Te(r,n,sm),me=Te(r,n,tk);ue&&me===Z&&(me=!1),(me===Z||ce)&&(me=!0),Pe!==Z&&Pe!=6&&(Ee=!1),!Ee&&r.config.CompressionStream===Z&&r.config.CompressionStreamZlib===Z&&(Pe=0);let Fe=Te(r,n,Vc);if(!ce&&(H!==Z||U!==Z)&&!(j>=1&&j<=3))throw new Error(vk);let Qe=new Uint8Array;const ze=n[Kh];if(ze){let be=0,ht=0;ze.forEach(at=>
2be+=4+Ie(at)),Qe=new Uint8Array(be),ze.forEach((at,vt)=>{if(vt>Le)throw new Error(_k);if(Ie(at)>Le)throw new Error(Fk);qe(Qe,new Uint16Array([vt]),ht),qe(Qe,new Uint16Array([Ie(at)]),ht+2),qe(Qe,at,ht+4),ht+=4+Ie(at)})}let T=0,V=0,F=0;if(W&&(F=n[Qc],F===Z))throw new Error(Rk);const O=Fe===!0;t&&(t=new Oc(t),await dn(t),W?(n.uncompressedSize=F,T=Im(F)):t.size===Z?(me=!0,(Fe||Fe===Z)&&(Fe=!0,F=T=et+1)):(n.uncompressedSize=F=t.size,T=Im(F)));const{diskOffset:K,diskNumber:N}=r.writer,X=O||F>et,re=O||T>et;if(X||re){if(Fe===!1)throw new Error(bm);Fe=!0}Fe=Fe||!1;const oe=Te(r,n,Lh);n=Object.assign({},n,{rawFilename:x,rawComment:I,version:C,versionMadeBy:s,lastModDate:v,lastAccessDate:R,creationDate:M,rawExtraField:Qe,zip64:Fe,zip64UncompressedSize:X,zip64CompressedSize:re,password:H,rawPassword:U,level:Pe,useWebWorkers:he,transferStreams:G,encryptionStrength:j,extendedTimestamp:ee,zipCrypto:ce,bufferedWrite:ue,createTempStream:we,keepOrder:fe,useUnicodeFileNames:xe,dataDescriptor:me,dataDescriptorSignature:_e,signal:Ye,msDosCompatible:i,internalFileAttribute:z,internalFileAttributes:z,externalFileAttribute:w,externalFileAttributes:w,useCompressionStream:Ee,passThrough:W,encrypted:!!(H&&Ie(H)||U&&Ie(U))||W&&oe,signature:n[Yh],compressionMethod:ne,uncompressedSize:F,offset:r.offset-K,diskNumberStart:N,uid:o,gid:c,setuid:d,setgid:f,sticky:h,unixMode:l,msdosAttributesRaw:p,msdosAttributes:m,unixExternalUpper:k});const ie=Yk(n),ke=jk(n),Ne=Ie(ie.localHeaderArray,ke.dataDescriptorArray);V=Ne+T,r.options[lm]&&(V+=V+64),r.pendingEntriesSize+=V;let te;try{te=await Hk(r,e,t,{headerInfo:ie,dataDescriptorInfo:ke,metadataSize:Ne},n)}finally{r.pendingEntriesSize-=V}return Object.assign(te,{name:e,comment:B,extraField:ze}),new Na(te)}async function Hk(r,e,t,n,i){const{files:s,writer:a}=r,{keepOrder:o,dataDescriptor:c,signal:l}=i,{headerInfo:u}=n,d=r.options[lm],f=Array.from(s.values()).pop();let h={},p,m,A,g,w,b;s.set(e,h);try{let B;o&&(B=f&&f.lock,k()),(i.bufferedWrite||!o||r.writerLocked||r.bufferedWrites||!c)&&!d?(i.createTempStream?b=await i.createTempStream():b=new TransformStream(Z,Z,{highWaterMark:fs}),b.size=0,p=!0,r.bufferedWrites++,await dn(a)):(b=a,await S()),await dn(b);const{writable:I,diskOffset:C}=a;if(r.addSplitZipSignature){delete r.addSplitZipSignature;const z=new Uint8Array(4),W=Et(z);De(W,0,pc),await Or(a,z),r.offset+=4}d&&Kk(n,r.offset-C);const{localHeaderView:v,localHeaderArray:R}=u;p||(await B,await x(I));const{diskNumber:M}=a;return h.diskNumberStart=M,p||(w=!0,await Or(b,R)),h=await Gk(t,b,h,n,r.config,i),p||(w=!1),s.set(e,h),h.filename=e,p?(await Promise.all([b.writable.getWriter().close(),B]),await S(),g=!0,h.diskNumberStart=a.diskNumber,h.offset=r.offset-a.diskOffset,Jk(h,v,i),await x(I),await Or(a,R),await b.readable.pipeTo(I,{preventClose:!0,preventAbort:!0,signal:l}),a.size+=b.size,g=!1):h.offset=r.offset-C,r.offset+=h.size,h}catch(B){if(g||w){if(r.hasCorruptedEntries=!0,B)try{B.corruptedEntry=!0}catch{}p?r.offset+=b.size:r.offset=b.size}throw s.delete(e),B}finally{p&&r.bufferedWrites--,A&&A(),m&&m()}function k(){h.lock=new Promise(B=>A=B)}async function S(){r.writerLocked=!0;const{lockWriter:B}=r;r.lockWriter=new Promise(I=>m=()=>{r.writerLocked=!1,I()}),await B}async function x(B){Ie(u.localHeaderArray)>a.availableSize&&(a.availableSize=0,await Or(B,new Uint8Array))}}async function Gk(r,e,{diskNumberStart:t,lock:n},i,s,a){const{headerInfo:o,dataDescriptorInfo:c,metadataSize:l}=i,{headerArray:u,headerView:d,lastModDate:f,rawLastModDate:h,encrypted:p,compressed:m,version:A,compressionMethod:g,rawExtraFieldZip64:w,localExtraFieldZip64Length:b,rawExtraFieldExtendedTimestamp:k,extraFieldExtendedTimestampFlag:S,rawExtraFieldNTFS:x,rawExtraFieldUnix:B,rawExtraFieldAES:I}=o,{dataDescriptorArray:C}=c,{rawFilename:v,lastAccessDate:R,creationDate:M,password:z,rawPassword:W,level:H,zip64:U,zip64UncompressedSize:j,zip64CompressedSize:ce,zipCrypto:ee,dataDescriptor:fe,directory:he,executable:G,versionMadeBy:ue,rawComment:we,rawExtraField:_e,useWebWorkers:Ye,transferStreams:xe,onstart:ne,onprogress:Pe,onend:Ee,signal:me,encryptionStrength:Fe,extendedTimestamp:Qe,msDosCompatible:ze,internalFileAttributes:T,externalFileAttributes:V,uid:F,gid:O,unixMode:K,setuid:N,setgid:X,sticky:re,unixExternalUpper:oe,msdosAttributesRaw:ie,msdosAttributes:ke,useCompressionStream:Ne,passThrough:te}=a,be={lock:n,versionMadeBy:ue,zip64:U,directory:!!he,executable:!!G,filenameUTF8:!0,rawFilename:v,commentUTF8:!0,rawComment:we,rawExtraFieldZip64:w,localExtraFieldZip64Length:b,rawExtraFieldExtendedTimestamp:k,rawExtraFieldNTFS:x,rawExtraFieldUnix:B,rawExtraFieldAES:I,rawExtraField:_e,extendedTimestamp:Qe,msDosCompatible:ze,internalFileAttributes:T,externalFileAttributes:V,diskNumberStart:t,uid:F,gid:O,unixMode:K,setuid:N,setgid:X,sticky:re,unixExternalUpper:oe,msdosAttributesRaw:ie,msdosAttributes:ke};let{signature:ht,uncompressedSize:at}=a,vt=0;te||(at=0);const{writable:_n}=e;if(r){r.chunkSize=zf(s);const ua=r.readable,nc=r.size,Hd={options:{codecType:mh,level:H,rawPassword:W,password:z,encryptionStrength:Fe,zipCrypto:p&&ee,passwordVerification:p&&ee&&h>>8&Ir,signed:!te,compressed:m&&!te,encrypted:p&&!te,useWebWorkers:Ye,useCompressionStream:Ne,transferStreams:xe},config:s,streamOptions:{signal:me,size:nc,onstart:ne,onprogress:Pe,onend:Ee}};try{const nn=await Eh({readable:ua,writable:_n},Hd);vt=nn.outputSize,e.size+=vt,te||(at=nn.inputSize,ht=nn.signature)}catch(nn){throw nn.outputSize!==Z&&(e.size+=nn.outputSize),nn}}return Xk({signature:ht,compressedSize:vt,uncompressedSize:at,headerInfo:o,dataDescriptorInfo:c},a),fe&&await Or(e,C),Object.assign(be,{uncompressedSize:at,compressedSize:vt,lastModDate:f,rawLastModDate:h,creationDate:M,lastAccessDate:R,encrypted:p,zipCrypto:ee,size:l+vt,compressionMethod:g,version:A,headerArray:u,headerView:d,signature:ht,extraFieldExtendedTimestampFlag:S,zip64UncompressedSize:j,zip64CompressedSize:ce}),be}function Yk(r){const{rawFilename:e,lastModDate:t,lastAccessDate:n,creationDate:i,level:s,zip64:a,zipCrypto:o,useUnicodeFileNames:c,dataDescriptor:l,directory:u,rawExtraField:d,encryptionStrength:f,extendedTimestamp:h,passThrough:p,encrypted:m,zip64UncompressedSize:A,zip64CompressedSize:g,uncompressedSize:w}=r;let{version:b,compressionMethod:k}=r;const S=!u&&(s>0||s===Z&&k!==0);let x;const B=p||!S,I=a&&(r.bufferedWrite||!A&&!g||B);if(a){let G=4;A&&(G+=8),g&&(G+=8),x=new Uint8Array(G);const ue=Et(x);if(Re(ue,0,wc),Re(ue,2,Ie(x)-4),I){const we=Et(x);let _e=4;A&&(Ct(we,_e,BigInt(w)),_e+=8),g&&B&&(Ct(we,_e,BigInt(w)),_e+=8),_e==4&&(x=new Uint8Array)}}else x=new Uint8Array;let C;
2if(m&&!o){C=new Uint8Array(Ie(Em)+2);const G=Et(C);Re(G,0,Bf),qe(C,Em,2),yi(G,8,f)}else C=new Uint8Array;let v,R,M;if(h){R=new Uint8Array(9+(n?4:0)+(i?4:0));const G=Et(R);Re(G,0,yc),Re(G,2,Ie(R)-4),M=1+(n?2:0)+(i?4:0),yi(G,4,M);let ue=5;De(G,ue,Math.floor(t.getTime()/1e3)),ue+=4,n&&(De(G,ue,Math.floor(n.getTime()/1e3)),ue+=4),i&&De(G,ue,Math.floor(i.getTime()/1e3));try{v=new Uint8Array(36);const we=Et(v),_e=Kc(t);Re(we,0,xf),Re(we,2,32),Re(we,8,Pf),Re(we,10,24),Ct(we,12,_e),Ct(we,20,Kc(n)||_e),Ct(we,28,Kc(i)||_e)}catch{v=new Uint8Array}}else v=R=new Uint8Array;let z;try{const{uid:G,gid:ue,unixMode:we,setuid:_e,setgid:Ye,sticky:xe,unixExtraFieldType:ne}=r;if(ne&&(G!==Z||ue!==Z||we!==Z)){const Pe=Cm(G),Ee=Cm(ue);let me=new Uint8Array;if(ne==Tm&&we!==Z){let T=we&Le;_e&&(T|=Ta),Ye&&(T|=Sa),xe&&(T|=Ca),me=new Uint8Array(2),new DataView(me.buffer).setUint16(0,T,!0)}const Fe=3+Pe.length+Ee.length+me.length;z=new Uint8Array(4+Fe);const Qe=Et(z);Re(Qe,0,ne==km?_f:Ff),Re(Qe,2,Fe),yi(Qe,4,1),yi(Qe,5,Pe.length);let ze=6;qe(z,Pe,ze),ze+=Pe.length,yi(Qe,ze,Ee.length),ze++,qe(z,Ee,ze),ze+=Ee.length,qe(z,me,ze)}else z=new Uint8Array}
2catch{z=new Uint8Array}k===Z&&(k=S?hc:yf),a&&(b=b>Df?b:Df),m&&!o&&(b=b>Mf?b:Mf,C[9]=k,k=bf);const W=I?Ie(x):0,H=W+Ie(C,R,v,z,d),{headerArray:U,headerView:j,rawLastModDate:ce}=Bm({version:b,bitFlag:xm(s,c,l,m,k),compressionMethod:k,uncompressedSize:w,lastModDate:t<Of?Of:t>Uf?Uf:t,rawFilename:e,zip64CompressedSize:g,zip64UncompressedSize:A,extraFieldLength:H});let ee=Dn;const fe=new Uint8Array(ee+Ie(e)+H),he=Et(fe);return De(he,0,Ef),qe(fe,U,4),qe(fe,e,ee),ee+=Ie(e),I&&qe(fe,x,ee),ee+=W,qe(fe,C,ee),ee+=Ie(C),qe(fe,R,ee),ee+=Ie(R),qe(fe,v,ee),ee+=Ie(v),qe(fe,z,ee),ee+=Ie(z),qe(fe,d,ee),l&&(De(he,pi+4,0),De(he,gi+4,0)),{localHeaderArray:fe,localHeaderView:he,headerArray:U,headerView:j,lastModDate:t,rawLastModDate:ce,encrypted:m,compressed:S,version:b,compressionMethod:k,extraFieldExtendedTimestampFlag:M,rawExtraFieldZip64:new Uint8Array,localExtraFieldZip64Length:W,rawExtraFieldExtendedTimestamp:R,rawExtraFieldNTFS:v,rawExtraFieldUnix:z,rawExtraFieldAES:C,extraFieldLength:H}}function Kk(r,e){const{headerInfo:t}=r;let{localHeaderArray:n,extraFieldLength:i}=t,s=Et(n),a=64-(e+Ie(n))%64;a<4&&(a+=64);const o=new Uint8Array(a),c=Et(o);Re(c,0,vf),Re(c,2,a-2);const l=n;t.localHeaderArray=n=new Uint8Array(Ie(l)+a),qe(n,l),qe(n,o,Ie(l)),s=Et(n),Re(s,28,i+a),r.metadataSize+=a}function Cm(r){if(r===Z)return new Uint8Array;{const e=new Uint8Array(4);Et(e).setUint32(0,r,!0);let n=4;for(;n>1&&e[n-1]===0;)n--;return e.subarray(0,n)}}function qk(r,e){if(r!==Z)r=r&Ir;else if(e!==Z){const{readOnly:t,hidden:n,system:i,directory:s,archive:a}=e;let o=0;t&&(o|=Tc),n&&(o|=Sc),i&&(o|=Cc),s&&(o|=Ea),a&&(o|=Ic),r=o&Ir}return e===Z&&(e={readOnly:!!(r&Tc),hidden:!!(r&Sc),system:!!(r&Cc),directory:!!(r&Ea),archive:!!(r&Ic)}),{msdosAttributesRaw:r,msdosAttributes:e}}function jk({zip64:r,dataDescriptor:e,dataDescriptorSignature:t}){let n=new Uint8Array,i,s=0,a=r?If:Cf;return t&&(a+=ba),e&&(n=new Uint8Array(a),i=Et(n),t&&(s=ba,De(i,0,kf))),{dataDescriptorArray:n,dataDescriptorView:i,dataDescriptorOffset:s}}function Xk({signature:r,compressedSize:e,uncompressedSize:t,headerInfo:n,dataDescriptorInfo:i},{zip64:s,zipCrypto:a,dataDescriptor:o}){const{headerView:c,encrypted:l}=n,{dataDescriptorView:u,dataDescriptorOffset:d}=i;(!l||a)&&r!==Z&&(De(c,Bc,r),o&&De(u,d,r)),s?o&&(Ct(u,d+4,BigInt(e)),Ct(u,d+12,BigInt(t))):(De(c,pi,e),De(c,gi,t),o&&(De(u,d+4,e),De(u,d+8,t)))}function Jk({rawFilename:r,encrypted:e,zip64:t,localExtraFieldZip64Length:n,signature:i,compressedSize:s,uncompressedSize:a,zip64UncompressedSize:o,zip64CompressedSize:c},l,{dataDescriptor:u}){if(u||(e||De(l,Bc+4,i),c||De(l,pi+4,s),o||De(l,gi+4,a)),t&&n){let d=Dn+Ie(r)+4;o&&(Ct(l,d,BigInt(a)),d+=8),c&&(Ct(l,d,BigInt(s)),d+=8)}}async function $k(r,e,t){const{files:n,writer:i}=r,{diskOffset:s}=i;let{diskNumber:a}=i,o=0,c=0,l=r.offset-s,u=n.size;for(const[,k]of n){const{rawFilename:S,rawExtraFieldAES:x,rawComment:B,rawExtraFieldNTFS:I,rawExtraFieldUnix:C,rawExtraField:v,extendedTimestamp:R,extraFieldExtendedTimestampFlag:M,lastModDate:z,zip64UncompressedSize:W,zip64CompressedSize:H,uncompressedSize:U,compressedSize:j}=k,ce=k.offset>et,ee=k.diskNumberStart>Le;let fe;if(ce||ee||W||H){let G=4;W&&(G+=8),H&&(G+=8),ce&&(G+=8),ee&&(G+=4),fe=new Uint8Array(G);const ue=Et(fe);Re(ue,0,wc),Re(ue,2,G-4);let we=4;W&&(Ct(ue,we,BigInt(U)),we+=8),H&&(Ct(ue,we,BigInt(j)),we+=8),ce&&(Ct(ue,we,BigInt(k.offset)),we+=8),ee&&De(ue,we,k.diskNumberStart)}else fe=new Uint8Array;k.rawExtraFieldZip64=fe,k.zip64Offset=ce,k.zip64DiskNumberStart=ee;let he;if(R){he=new Uint8Array(9);const G=Et(he);Re(G,0,yc),Re(G,2,5),yi(G,4,M),De(G,5,Math.floor(z.getTime()/1e3))}else he=new Uint8Array;k.rawExtraFieldExtendedTimestamp=he,c+=46+Ie(S,B,fe,x,I,C,he,v)}const d=new Uint8Array(c),f=Et(d);await dn(i);let h=0;for(const[k,S]of Array.from(n.values()).entries()){const{offset:x,rawFilename:B,rawExtraFieldZip64:I,rawExtraFieldAES:C,rawExtraFieldExtendedTimestamp:v,rawExtraFieldNTFS:R,rawExtraFieldUnix:M,rawExtraField:z,rawComment:W,versionMadeBy:H,headerArray:U,headerView:j,zip64UncompressedSize:ce,zip64CompressedSize:ee,zip64DiskNumberStart:fe,zip64Offset:he,internalFileAttributes:G,externalFileAttributes:ue,diskNumberStart:we,uncompressedSize:_e,compressedSize:Ye}=S,xe=Ie(I,C,v,R,M,z);De(f,o,gc),Re(f,o+4,H),ce||De(j,gi,_e),ee||De(j,pi,Ye),qe(d,U,o+6);let ne=o+Dn;if(Re(f,ne,xe),ne+=2,Re(f,ne,Ie(W)),ne+=2,Re(f,ne,fe?Le:we),ne+=2,Re(f,ne,G),ne+=2,ue&&De(f,ne,ue),ne+=4,De(f,ne,he?et:x),ne+=4,qe(d,B,ne),ne+=Ie(B),qe(d,I,ne),ne+=Ie(I),qe(d,C,ne),ne+=Ie(C),qe(d,v,ne),ne+=Ie(v),qe(d,R,ne),ne+=Ie(R),qe(d,M,ne),ne+=Ie(M),qe(d,z,ne),ne+=Ie(z),qe(d,W,ne),ne+=Ie(W),o-h>i.availableSize&&(i.availableSize=0,await Or(i,d.slice(h,o)),h=o),o=ne,t.onprogress)try{await t.onprogress(k+1,n.size,new Na(S))}catch{}}await Or(i,h?d.slice(h):d);let p=i.diskNumber;const{availableSize:m}=i;m<Ur&&p++;let A=Te(r,t,Vc);if(l>et||c>et||u>Le||p>Le){if(A===!1)throw new Error(bm);A=!0}const g=new Uint8Array(A?_b:Ur),w=Et(g);o=0,A&&(De(w,0,Ac),Ct(w,4,BigInt(44)),Re(w,12,45),Re(w,14,45),De(w,16,p),De(w,20,a),Ct(w,24,BigInt(u)),Ct(w,32,BigInt(u)),Ct(w,40,BigInt(c)),Ct(w,48,BigInt(l)),De(w,56,Sf),Ct(w,64,BigInt(l)+BigInt(c)),De(w,72,p+1),Te(r,t,rk,!0)&&(p=Le,a=Le),u=Le,l=et,c=et,o+=ls+cs),De(w,o,Tf),Re(w,o+4,p),Re(w,o+6,a),Re(w,o+8,u),Re(w,o+10,u),De(w,o+12,c),De(w,o+16,l);const b=Ie(e);if(b)if(b<=Le)Re(w,o+20,b);else throw new Error(Bk);await Or(i,g),b&&await Or(i,e)}async function Or(r,e){const{writable:t}=r,n=t.getWriter();try{await n.ready,r.size+=Ie(e),await n.write(e)}finally{n.releaseLock()}}function Kc(r){if(r)return(BigInt(r.getTime())+BigInt(116444736e5))*BigInt(1e4)}function Te(r,e,t,n){const i=e[t]===Z?r.options[t]:e[t];return i===Z?n:i}function Im(r){return r+5*(Math.floor(r/16383)+1)}function yi(r,e,t){r.setUint8(e,t)}function Re(r,e,t){r.setUint16(e,t,!0)}function De(r,e,t){r.setUint32(e,t,!0)}function Ct(r,e,t){r.setBigUint64(e,t,!0)}function qe(r,e,t){r.set(e,t)}function Et(r){return new DataView(r.buffer)}function Ie(...r){let e=0;return r.forEach(t=>t&&(e+=t.length)),e}function Bm({version:r,bitFlag:e,compressionMethod:t,uncompressedSize:n,compressedSize:i,lastModDate:s,rawFilename:a,zip64CompressedSize:o,zip64UncompressedSize:c,extraFieldLength:l}){const u=new Uint8Array(Dn-4),d=Et(u);Re(d,0,r),Re(d,2,e),Re(d,4,t);const f=new Uint32Array(1),h=Et(f);Re(h,0,(s.getHours()<<6|s.getMinutes())<<5|s.getSeconds()/2),Re(h,2,(s.getFullYear()-1980<<4|s.getMonth()+1)<<5|s.getDate());const p=f[0];return De(d,6,p),(o||i!==Z)&&De(d,pi,o?et:i),(c||n!==Z)&&De(d,gi,c?et:n),Re(d,22,Ie(a)),Re(d,24,l),{headerArray:u,headerView:d,rawLastModDate:p}}function xm(r,e,t,n,i){let s=0;return e&&(s=s|kc),t&&(s=s|Ec),(i==hc||i==mc)&&(r>=0&&r<=3&&(s=s|Ob),r>3&&r<=5&&(s=s|Ub),r==9&&(s=s|Mb)),n&&(s=s|bc),s}try{Ba({baseURI:self.location.href})}catch{}const jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
2+/";function Zk(r){let e;r({wasmURI:()=>(e||(e="data:application/wasm;base64,"+(t=>{t=(a=>{const o=(a=(a+"").replace(/[^A-Za-z0-9+/=]/g,"")).length,c=[];for(let l=0;o>l;l+=4){const u=jt.indexOf(a[l])<<18|jt.indexOf(a[l+1])<<12|(63&jt.indexOf(a[l+2]))<<6|63&jt.indexOf(a[l+3]);c.push(u>>16&255),a[l+2]!=="="&&c.push(u>>8&255),a[l+3]!=="="&&c.push(255&u)}return new Uint8Array(c)})(t);let n=new Uint8Array(1024),i=0;for(let a=0;a<t.length;){const o=t[a++];if(128&o){const c=3+(127&o),l=t[a++]<<8|t[a++],u=i-l;s(i+c);for(let d=0;c>d;d++)n[i++]=n[u+d]}else{const c=o;s(i+c);for(let l=0;c>l&&a<t.length;l++)n[i++]=t[a++]}}return(a=>{let o="";const c=a.length;let l=0;for(;c>l+2;l+=3){const d=a[l]<<16|a[l+1]<<8|a[l+2];o+=jt[d>>18&63]+jt[d>>12&63]+jt[d>>6&63]+jt[63&d]}const u=c-l;if(u===1){const d=a[l]<<16;o+=jt[d>>18&63]+jt[d>>12&63]+"=="}else if(u===2){const d=a[l]<<16|a[l+1]<<8;o+=jt[d>>18&63]+jt[d>>12&63]+jt[d>>6&63]+"="}return o})(new Uint8Array(n.buffer.slice(0,i)));function s(a){if(n.length<a){let o=2*n.length;for(;a>o;)o*=2;const c=new Uint8Array(o);c.set(n.subarray(0,i)),n=c
vendor: 39,366 bytes, line 2
2}}})("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BAGZgAAEAVmAAAQB2YAABAE5gAAEAbmAAAQBeYAABAH5gAAEAQWAAAQBhYAABAFFgAAEAcWAAAQBJYAABAGlgAAEAWWAAAQB5YAABAEVgAAEAZWAAAQBVYAABAHVgAAEATWAAAQBtYAABAF1gAAEAfWAAAQBDYAABAGNgAAEAU2AAAQBzYAABIARMwIArYAABAFtgAAEAe2AAAQBHYAABAGdgAAEAV2AAAQB3YAABAE9gAAEAb2AAAQBfYAABAH9gAAEAROAAMIFEwEJAJOAAAgBk4AACAFTgAAIAVOAAAgB04AACAHTgAAIATOAAAgBM4AACAGzgAAIAbOAAAgBc4AACAFzgAAIAfOAAAgB84AACAELgAAIgBDagAQCgAAEgAAIAUuAAAgBS4AACAHLgAAIAcuAAAgBK4AACAErgAAIAauAAAgBq4AACAFrgAAIAWuAAAgB64AACAHrgAAIARuAAAgBG4AACAGbgAAIAZuAAAgBW4AACAFbgAAIAduAAAgB24AACAE7gAAIATuAAAgBu4AACAG7gAAIAXuAAAgBe4AACAH7gAAIAfuAAAiBA7YBB4AACAGHgAAIAYeAAAgBR4AACAFHgAAIAceAAAgBx4AACAEngAAIASeAAAgBp4AACAGngAAIAWeAAAgBZ4AACAHngAAIAeeAAAgBF4AACAEXgAAIAZeAAAgBl4AACAFXgAAIAVeAAAgB14AACAHXgAAIATeAAAgBN4AACAG3gAAIAbeAAAgBd4AACAF3gAAIAfeAAAgB94AACAEPgAAIAQ+AAAgBj4AACAGPgAAIAU+AAAgBT4AACAHPgAAIAc+AAAgBL4AACAEvgAAIAa+AAAgBr4AACAFvgAAIAW+AAAgB74AACAHvgAAIAR+AAAgBH4AACAGfgAAIAZ+AAAgBX4AACAFfgAAIAd+AAAgB34AACAE/gAAIAT+AAAgBv4AACAG/gAAIAX+AAAgBf4AACAH/gAAIAf+AAAiBBAoBQIAABAEggAAEAWCAAAQBEIAABAFQgAAEATCAAAQBcIIFVgMHAEiAAAQBKIAABAFogAAEARiAAAQBWIAABAE4gAAEAXiAAAQBBIAABAFEgAAEASSAAAQBZIAABAEUgAAEAVSAAAQBNIAABAF0gAAEAQOAAEIBg4AABAFDgAAEAcOAAAQBI4AABAGjgAAEAWOAAAQB44AABIC+K4AAdIECxgEFgABcAQWCBUoBFIAABAEMgAAEARyAAASAvlaABEQBBYIGBAEaggXqAQWAA9QBBYADuAEFgAOcgE92gAAEARGAAAQBCYAABAEZgAAEgQACARWAAAQBDYAABAEdgAAEgL59gAKkgQZAAQWAAiyBBaYBBYABtAEFgD3fAxsLTYMfuYcABIC+rooABIEHUYkABAEEjAAEAQWKAAQEQbAcC4C9CosAS40AO4UALwEGhAAEgQWIgQAEgQEKgQAEgQGSgQAEgIS2ggAEAQuEAAQBDIQABIAF24FHeQTgHQsjhQBfhQXLAhARgAVtBgcJBgoFC4A6uAQNAg4BgAclBJQeC2mFAJCFAIiFAICFAHiBAGiBAFyBBh8BEIAABAEUgAAEARiAAAQBHIAABAEggAAEASiAAAQBMIAABAE4gAAEAUCAAAQBUIAABIEGvQFwgAAEAYCAAAQBoIAABAHAgAAEAeCAAG8DHwtyjQBvgQBrgQBngQBjgQBfgQBbgQBXgQBTgQBPgQBLgQBHgQBDgQE8AYCvAEGAUc0CC22BAMcBBIAAAgEIgAAEgQEzgQJLARCAAA6DAAyBnqyAqmuEACSBB3OBAE8BCIAACIEAGIUADIEIt4MADAEggQCUgDKEgQBrAYCBCC8BBIMADIA/SAoBABAMAEGRIQv/gCUfgMDAgIKxBQgJCQoKgEk3gAABAQ2AAAEBDoAAAQEPgAABARCEAAEBEYQAAQEShAABAROEAAEBFIwAAQEVjAABARaMAAEBF4wAAQEYnAABARmcAAEBGpwAAQEbmwABARyBffsEBAQFBYHB1QEHgAABAQiEAAGAXSqCAAEBCowAAYAnsooAAYEBMJkAAYEBTJkAAYEBaLkAAYEBpLkAAYIDdYABzoUBvI0BqJ0BkLwBgAIbHLwAAQEdvAABgA9PgH05A9AqAQ==")),
2e)})}let ut,bi,Xt,ys;function eT(r){if(ut=r,{malloc:bi,free:Xt,memory:ys}=ut,typeof bi!="function"||typeof Xt!="function"||!ys)throw ut=bi=Xt=ys=null,new Error("Invalid WASM module")}function Pm(r,e,t={}){const n=typeof t.level=="number"?t.level:-1,i=typeof t.outBuffer=="number"?t.outBuffer:64*1024,s=typeof t.inBufferSize=="number"?t.inBufferSize:64*1024;return new TransformStream({start(){let a;if(this.out=bi(i),this.in=bi(s),this.inBufferSize=s,this._scratch=new Uint8Array(i),r?(this._process=ut.deflate_process,this._last_consumed=ut.deflate_last_consumed,this._end=ut.deflate_end,this.streamHandle=ut.deflate_new(),e==="gzip"?a=ut.deflate_init_gzip(this.streamHandle,n):e==="deflate-raw"?a=ut.deflate_init_raw(this.streamHandle,n):a=ut.deflate_init(this.streamHandle,n)):e==="deflate64-raw"?(this._process=ut.inflate9_process,this._last_consumed=ut.inflate9_last_consumed,this._end=ut.inflate9_end,this.streamHandle=ut.inflate9_new(),a=ut.inflate9_init_raw(this.streamHandle)):(this._process=ut.inflate_process,this._last_consumed=ut.inflate_last_consumed,this._end=ut.inflate_end,this.streamHandle=ut.inflate_new(),e==="deflate-raw"?a=ut.inflate_init_raw(this.streamHandle):e==="gzip"?a=ut.inflate_init_gzip(this.streamHandle):a=ut.inflate_init(this.streamHandle)),a!==0)throw new Error("init failed:"+a)},transform(a,o){try{const c=a,l=new Uint8Array(ys.buffer),u=this._process,d=this._last_consumed,f=this.out,h=this._scratch;let p=0;for(;p<c.length;){const m=Math.min(c.length-p,32768);(!this.in||this.inBufferSize<m)&&(this.in&&Xt&&Xt(this.in),this.in=bi(m),this.inBufferSize=m),l.set(c.subarray(p,p+m),this.in);const A=u(this.streamHandle,this.in,m,f,i,0),g=A&16777215;if(g&&(h.set(l.subarray(f,f+g),0),o.enqueue(h.slice(0,g))),!r){const b=A>>24&255,k=b&128?b-256:b;if(k<0)throw new Error("process error:"+k)}const w=d(this.streamHandle);if(w===0)break;p+=w}}catch(c){this._end&&this.streamHandle&&this._end(this.streamHandle),this.in&&Xt&&Xt(this.in),this.out&&Xt&&Xt(this.out),o.error(c)}},flush(a){try{const o=new Uint8Array(ys.buffer),c=this._process,l=this.out,u=this._scratch;for(;;){const d=c(this.streamHandle,0,0,l,i,4),f=d&16777215,h=d>>24&255;if(!r){const p=h&128?h-256:h;if(p<0)throw new Error("process error:"+p)}if(f&&(u.set(o.subarray(l,l+f),0),a.enqueue(u.slice(0,f))),h===1||f===0)break}}catch(o){a.error(o)}finally{if(this._end&&this.streamHandle){const o=this._end(this.streamHandle);o!==0&&a.error(new Error("end error:"+o))}this.in&&Xt&&Xt(this.in),this.out&&Xt&&Xt(this.out)}}})}class tT{constructor(e="deflate",t){return Pm(!0,e,t)}}class rT{constructor(e="deflate",t){return Pm(!1,e,t)}}let vm=!1;async function nT(r,{baseURI:e}){if(!vm){let t,n;try{try{n=new URL(r,e)}catch{}t=await(await fetch(n)).arrayBuffer()}catch(s){if(r.startsWith("data:application/wasm;base64,"))t=iT(r);else throw s}const i=await WebAssembly.instantiate(t);eT(i.instance.exports),vm=!0}}function iT(r){const e=r.split(",")[1],t=atob(e),n=t.length,i=new Uint8Array(n);for(let s=0;s<n;++s)i[s]=t.charCodeAt(s);return i.buffer}let qc;Zk(Ba),yE({initModule:r=>{if(!qc){let{wasmURI:e}=r;typeof e==ln&&(e=e()),qc=nT(e,r)}return qc}}),Ba({CompressionStreamZlib:tT,DecompressionStreamZlib:rT});const jc
vendor: 23,415 bytes, line 2
2={application:{"andrew-inset":"ez",annodex:"anx","atom+xml":"atom","atomcat+xml":"atomcat","atomserv+xml":"atomsrv",bbolin:"lin","cu-seeme":"cu","davmount+xml":"davmount",dsptype:"tsp",ecmascript:["es","ecma"],futuresplash:"spl",hta:"hta","java-archive":"jar","java-serialized-object":"ser","java-vm":"class",m3g:"m3g","mac-binhex40":"hqx",mathematica:["nb","ma","mb"],msaccess:"mdb",msword:["doc","dot","wiz"],mxf:"mxf",oda:"oda",ogg:"ogx",pdf:"pdf","pgp-keys":"key","pgp-signature":["asc","sig"],"pics-rules":"prf",postscript:["ps","ai","eps","epsi","epsf","eps2","eps3"],rar:"rar","rdf+xml":"rdf","rss+xml":"rss",rtf:"rtf","xhtml+xml":["xhtml","xht"],xml:["xml","xsl","xsd","xpdl"],"xspf+xml":"xspf",zip:"zip","vnd.android.package-archive":"apk","vnd.cinderella":"cdy","vnd.google-earth.kml+xml":"kml","vnd.google-earth.kmz":"kmz","vnd.mozilla.xul+xml":"xul","vnd.ms-excel":["xls","xlb","xlt","xlm","xla","xlc","xlw"],"vnd.ms-pki.seccat":"cat","vnd.ms-pki.stl":"stl","vnd.ms-powerpoint":["ppt","pps","pot","ppa","pwz"],"vnd.oasis.opendocument.chart":"odc","vnd.oasis.opendocument.database":"odb","vnd.oasis.opendocument.formula":"odf","vnd.oasis.opendocument.graphics":"odg","vnd.oasis.opendocument.graphics-template":"otg","vnd.oasis.opendocument.image":"odi","vnd.oasis.opendocument.presentation":"odp","vnd.oasis.opendocument.presentation-template":"otp","vnd.oasis.opendocument.spreadsheet":"ods","vnd.oasis.opendocument.spreadsheet-template":"ots","vnd.oasis.opendocument.text":"odt","vnd.oasis.opendocument.text-master":["odm","otm"],"vnd.oasis.opendocument.text-template":"ott","vnd.oasis.opendocument.text-web":"oth","vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","vnd.openxmlformats-officedocument.spreadsheetml.template":"xltx","vnd.openxmlformats-officedocument.presentationml.presentation":"pptx","vnd.openxmlformats-officedocument.presentationml.slideshow":"ppsx","vnd.openxmlformats-officedocument.presentationml.template":"potx","vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","vnd.openxmlformats-officedocument.wordprocessingml.template":"dotx","vnd.smaf":"mmf","vnd.stardivision.calc":"sdc","vnd.stardivision.chart":"sds","vnd.stardivision.draw":"sda","vnd.stardivision.impress":"sdd","vnd.stardivision.math":["sdf","smf"],"vnd.stardivision.writer":["sdw","vor"],"vnd.stardivision.writer-global":"sgl","vnd.sun.xml.calc":"sxc","vnd.sun.xml.calc.template":"stc","vnd.sun.xml.draw":"sxd","vnd.sun.xml.draw.template":"std","vnd.sun.xml.impress":"sxi","vnd.sun.xml.impress.template":"sti","vnd.sun.xml.math":"sxm","vnd.sun.xml.writer":"sxw","vnd.sun.xml.writer.global":"sxg","vnd.sun.xml.writer.template":"stw","vnd.symbian.install":["sis","sisx"],"vnd.visio":["vsd","vst","vss","vsw","vsdx","vssx","vstx","vssm","vstm"],"vnd.wap.wbxml":"wbxml","vnd.wap.wmlc":"wmlc","vnd.wap.wmlscriptc":"wmlsc","vnd.wordperfect":"wpd","vnd.wordperfect5.1":"wp5","x-123":"wk","x-7z-compressed":"7z","x-abiword":"abw","x-apple-diskimage":"dmg","x-bcpio":"bcpio","x-bittorrent":"torrent","x-cbr":["cbr","cba","cbt","cb7"],"x-cbz":"cbz","x-cdf":["cdf","cda"],"x-cdlink":"vcd","x-chess-pgn":"pgn","x-cpio":"cpio","x-csh":"csh","x-director":["dir","dxr","cst","cct","cxt","w3d","fgd","swa"],"x-dms":"dms","x-doom":"wad","x-dvi":"dvi","x-httpd-eruby":"rhtml","x-font":"pcf.Z","x-freemind":"mm","x-gnumeric":"gnumeric","x-go-sgf":"sgf","x-graphing-calculator":"gcf","x-gtar":["gtar","taz"],"x-hdf":"hdf","x-httpd-php":["phtml","pht","php"],"x-httpd-php-source":"phps","x-httpd-php3":"php3","x-httpd-php3-preprocessed":"php3p","x-httpd-php4":"php4","x-httpd-php5":"php5","x-ica":"ica","x-info":"info","x-internet-signup":["ins","isp"],"x-iphone":"iii","x-iso9660-image":"iso","x-java-jnlp-file":"jnlp","x-jmol":"jmz","x-killustrator":"kil","x-latex":"latex","x-lyx":"lyx","x-lzx":"lzx","x-maker":["frm","fb","fbdoc"],"x-ms-wmd":"wmd","x-msdos-program":["com","exe","bat","dll"],"x-netcdf":["nc"],"x-ns-proxy-autoconfig":["pac","dat"],"x-nwc":"nwc","x-object":"o","x-oz-application":"oza","x-pkcs7-certreqresp":"p7r","x-python-code":["pyc","pyo"],"x-qgis":["qgs","shp","shx"],"x-quicktimeplayer":"qtl","x-redhat-package-manager":["rpm","rpa"],"x-ruby":"rb","x-sh":"sh","x-shar":"shar","x-shockwave-flash":["swf","swfl"],"x-silverlight":"scr","x-stuffit":"sit","x-sv4cpio":"sv4cpio","x-sv4crc":"sv4crc","x-tar":"tar","x-tex-gf":"gf","x-tex-pk":"pk","x-texinfo":["texinfo","texi"],"x-trash":["~","%","bak","old","sik"],"x-ustar":"ustar","x-wais-source":"src","x-wingz":"wz","x-x509-ca-cert":["crt","der","cer"],"x-xcf":"xcf","x-xfig":"fig","x-xpinstall":"xpi",applixware:"aw","atomsvc+xml":"atomsvc","ccxml+xml":"ccxml","cdmi-capability":"cdmia","cdmi-container":"cdmic","cdmi-domain":"cdmid","cdmi-object":"cdmio","cdmi-queue":"cdmiq","docbook+xml":"dbk","dssc+der":"dssc","dssc+xml":"xdssc","emma+xml":"emma","epub+zip":"epub",exi:"exi","font-tdpfr":"pfr","gml+xml":"gml","gpx+xml":"gpx",gxf:"gxf",hyperstudio:"stk","inkml+xml":["ink","inkml"],ipfix:"ipfix","jsonml+json":"jsonml","lost+xml":"lostxml","mads+xml":"mads",marc:"mrc","marcxml+xml":"mrcx","mathml+xml":["mathml","mml"],mbox:"mbox","mediaservercontrol+xml":"mscml","metalink+xml":"metalink","metalink4+xml":"meta4","mets+xml":"mets","mods+xml":"mods",mp21:["m21","mp21"],mp4:"mp4s","oebps-package+xml":"opf","omdoc+xml":"omdoc",onenote:["onetoc","onetoc2","onetmp","onepkg"],oxps:"oxps","patch-ops-error+xml":"xer","pgp-encrypted":"pgp",pkcs10:"p10","pkcs7-mime":["p7m","p7c"],"pkcs7-signature":"p7s",pkcs8:"p8","pkix-attr-cert":"ac","pkix-crl":"crl","pkix-pkipath":"pkipath",pkixcmp:"pki","pls+xml":"pls","prs.cww":"cww","pskc+xml":"pskcxml","reginfo+xml":"rif","relax-ng-compact-syntax":"rnc","resource-lists+xml":"rl","resource-lists-diff+xml":"rld","rls-services+xml":"rs","rpki-ghostbusters":"gbr","rpki-manifest":"mft","rpki-roa":"roa","rsd+xml":"rsd","sbml+xml":"sbml","scvp-cv-request":"scq","scvp-cv-response":"scs","scvp-vp-request":"spq","scvp-vp-response":"spp",sdp:"sdp","set-payment-initiation":"setpay","set-registration-initiation":"setreg","shf+xml":"shf","sparql-query":"rq","sparql-results+xml":"srx",srgs:"gram","srgs+xml":"grxml","sru+xml":"sru","ssdl+xml":"ssdl","ssml+xml":"ssml","tei+xml":["tei","teicorpus"],"thraud+xml":"tfi","timestamped-data":"tsd","vnd.3gpp.pic-bw-large":"plb","vnd.3gpp.pic-bw-small":"psb","vnd.3gpp.pic-bw-var":"pvb","vnd.3gpp2.tcap":"tcap","vnd.3m.post-it-notes":"pwn","vnd.accpac.simply.aso":"aso","vnd.accpac.simply.imp":"imp","vnd.acucobol":"acu","vnd.acucorp":["atc","acutc"],"vnd.adobe.air-application-installer-package+zip":"air","vnd.adobe.formscentral.fcdt":"fcdt","vnd.adobe.fxp":["fxp","fxpl"],"vnd.adobe.xdp+xml":"xdp","vnd.adobe.xfdf":"xfdf","vnd.ahead.space":"ahead","vnd.airzip.filesecure.azf":"azf","vnd.airzip.filesecure.azs":"azs","vnd.amazon.ebook":"azw","vnd.americandynamics.acc":"acc","vnd.amiga.ami":"ami","vnd.anser-web-certificate-issue-initiation":"cii","vnd.anser-web-funds-transfer-initiation":"fti","vnd.antix.game-component":"atx","vnd.apple.installer+xml":"mpkg","vnd.apple.mpegurl":"m3u8","vnd.aristanetworks.swi":"swi","vnd.astraea-software.iota":"iota","vnd.audiograph":"aep","vnd.blueice.multipass":"mpm","vnd.bmi":"bmi","vnd.businessobjects":"rep","vnd.chemdraw+xml":"cdxml","vnd.chipnuts.karaoke-mmd":"mmd","vnd.claymore":"cla","vnd.cloanto.rp9":"rp9","vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"vnd.cluetrust.cartomobile-config":"c11amc","vnd.cluetrust.cartomobile-config-pkg":"c11amz","vnd.commonspace":"csp","vnd.contact.cmsg":"cdbcmsg","vnd.cosmocaller":"cmc","vnd.crick.clicker":"clkx","vnd.crick.clicker.keyboard":"clkk","vnd.crick.clicker.palette":"clkp","vnd.crick.clicker.template":"clkt","vnd.crick.clicker.wordbank":"clkw","vnd.criticaltools.wbs+xml":"wbs","vnd.ctc-posml":"pml","vnd.cups-ppd":"ppd","vnd.curl.car":"car","vnd.curl.pcurl":"pcurl","vnd.dart":"dart","vnd.data-vision.rdz":"rdz","vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"vnd.dece.ttml+xml":["uvt","uvvt"],"vnd.dece.unspecified":["uvx","uvvx"],"vnd.dece.zip":["uvz","uvvz"],"vnd.denovo.fcselayout-link":"fe_launch","vnd.dna":"dna","vnd.dolby.mlp":"mlp","vnd.dpgraph":"dpg","vnd.dreamfactory":"dfac","vnd.ds-keypoint":"kpxx","vnd.dvb.ait":"ait","vnd.dvb.service":"svc","vnd.dynageo":"geo","vnd.ecowin.chart":"mag","vnd.enliven":"nml","vnd.epson.esf":"esf","vnd.epson.msf":"msf","vnd.epson.quickanime":"qam","vnd.epson.salt":"slt","vnd.epson.ssf":"ssf","vnd.eszigno3+xml":["es3","et3"],"vnd.ezpix-album":"ez2","vnd.ezpix-package":"ez3","vnd.fdf":"fdf","vnd.fdsn.mseed":"mseed","vnd.fdsn.seed":["seed","dataless"],"vnd.flographit":"gph","vnd.fluxtime.clip":"ftc","vnd.framemaker":["fm","frame","maker","book"],"vnd.frogans.fnc":"fnc","vnd.frogans.ltf":"ltf","vnd.fsc.weblaunch":"fsc","vnd.fujitsu.oasys":"oas","vnd.fujitsu.oasys2":"oa2","vnd.fujitsu.oasys3":"oa3","vnd.fujitsu.oasysgp":"fg5","vnd.fujitsu.oasysprs":"bh2","vnd.fujixerox.ddd":"ddd","vnd.fujixerox.docuworks":"xdw","vnd.fujixerox.docuworks.binder":"xbd","vnd.fuzzysheet":"fzs","vnd.genomatix.tuxedo":"txd","vnd.geogebra.file":"ggb","vnd.geogebra.tool":"ggt","vnd.geometry-explorer":["gex","gre"],"vnd.geonext":"gxt","vnd.geoplan":"g2w","vnd.geospace":"g3w","vnd.gmx":"gmx","vnd.grafeq":["gqf","gqs"],"vnd.groove-account":"gac","vnd.groove-help":"ghf","vnd.groove-identity-message":"gim","vnd.groove-injector":"grv","vnd.groove-tool-message":"gtm","vnd.groove-tool-template":"tpl","vnd.groove-vcard":"vcg","vnd.hal+xml":"hal","vnd.handheld-entertainment+xml":"zmm","vnd.hbci":"hbci","vnd.hhe.lesson-player":"les","vnd.hp-hpgl":"hpgl","vnd.hp-hpid":"hpid","vnd.hp-hps":"hps","vnd.hp-jlyt":"jlt","vnd.hp-pcl":"pcl","vnd.hp-pclxl":"pclxl","vnd.hydrostatix.sof-data":"sfd-hdstx","vnd.ibm.minipay":"mpy","vnd.ibm.modcap":["afp","listafp","list3820"],"vnd.ibm.rights-management":"irm","vnd.ibm.secure-container":"sc","vnd.iccprofile":["icc","icm"],"vnd.igloader":"igl","vnd.immervision-ivp":"ivp","vnd.immervision-ivu":"ivu","vnd.insors.igm":"igm","vnd.intercon.formnet":["xpw","xpx"],"vnd.intergeo":"i2g","vnd.intu.qbo":"qbo","vnd.intu.qfx":"qfx","vnd.ipunplugged.rcprofile":"rcprofile","vnd.irepository.package+xml":"irp","vnd.is-xpr":"xpr","vnd.isac.fcs":"fcs","vnd.jam":"jam","vnd.jcp.javame.midlet-rms":"rms","vnd.jisp":"jisp","vnd.joost.joda-archive":"joda","vnd.kahootz":["ktz","ktr"],"vnd.kde.karbon":"karbon","vnd.kde.kchart":"chrt","vnd.kde.kformula":"kfo","vnd.kde.kivio":"flw","vnd.kde.kontour":"kon","vnd.kde.kpresenter":["kpr","kpt"],"vnd.kde.kspread":"ksp","vnd.kde.kword":["kwd","kwt"],"vnd.kenameaapp":"htke","vnd.kidspiration":"kia","vnd.kinar":["kne","knp"],"vnd.koan":["skp","skd","skt","skm"],"vnd.kodak-descriptor":"sse","vnd.las.las+xml":"lasxml","vnd.llamagraphics.life-balance.desktop":"lbd","vnd.llamagraphics.life-balance.exchange+xml":"lbe","vnd.lotus-1-2-3":"123","vnd.lotus-approach":"apr","vnd.lotus-freelance":"pre","vnd.lotus-notes":"nsf","vnd.lotus-organizer":"org","vnd.lotus-screencam":"scm","vnd.lotus-wordpro":"lwp","vnd.macports.portpkg":"portpkg","vnd.mcd":"mcd","vnd.medcalcdata":"mc1","vnd.mediastation.cdkey":"cdkey","vnd.mfer":"mwf","vnd.mfmp":"mfm","vnd.micrografx.flo":"flo","vnd.micrografx.igx":"igx","vnd.mif":"mif","vnd.mobius.daf":"daf","vnd.mobius.dis":"dis","vnd.mobius.mbk":"mbk","vnd.mobius.mqy":"mqy","vnd.mobius.msl":"msl","vnd.mobius.plc":"plc","vnd.mobius.txf":"txf","vnd.mophun.application":"mpn","vnd.mophun.certificate":"mpc","vnd.ms-artgalry":"cil","vnd.ms-cab-compressed":"cab","vnd.ms-excel.addin.macroenabled.12":"xlam","vnd.ms-excel.sheet.binary.macroenabled.12":"xlsb","vnd.ms-excel.sheet.macroenabled.12":"xlsm","vnd.ms-excel.template.macroenabled.12":"xltm","vnd.ms-fontobject":"eot","vnd.ms-htmlhelp":"chm","vnd.ms-ims":"ims","vnd.ms-lrm":"lrm","vnd.ms-officetheme":"thmx","vnd.ms-powerpoint.addin.macroenabled.12":"ppam","vnd.ms-powerpoint.presentation.macroenabled.12":"pptm","vnd.ms-powerpoint.slide.macroenabled.12":"sldm","vnd.ms-powerpoint.slideshow.macroenabled.12":"ppsm","vnd.ms-powerpoint.template.macroenabled.12":"potm","vnd.ms-project":["mpp","mpt"],"vnd.ms-word.document.macroenabled.12":"docm","vnd.ms-word.template.macroenabled.12":"dotm","vnd.ms-works":["wps","wks","wcm","wdb"],"vnd.ms-wpl":"wpl","vnd.ms-xpsdocument":"xps","vnd.mseq":"mseq","vnd.musician":"mus","vnd.muvee.style":"msty","vnd.mynfc":"taglet","vnd.neurolanguage.nlu":"nlu","vnd.nitf":["ntf","nitf"],"vnd.noblenet-directory":"nnd","vnd.noblenet-sealer":"nns","vnd.noblenet-web":"nnw","vnd.nokia.n-gage.data":"ngdat","vnd.nokia.n-gage.symbian.install":"n-gage","vnd.nokia.radio-preset":"rpst","vnd.nokia.radio-presets":"rpss","vnd.novadigm.edm":"edm","vnd.novadigm.edx":"edx","vnd.novadigm.ext":"ext","vnd.oasis.opendocument.chart-template":"otc","vnd.oasis.opendocument.formula-template":"odft","vnd.oasis.opendocument.image-template":"oti","vnd.olpc-sugar":"xo","vnd.oma.dd2+xml":"dd2","vnd.openofficeorg.extension":"oxt","vnd.openxmlformats-officedocument.presentationml.slide":"sldx","vnd.osgeo.mapguide.package":"mgp","vnd.osgi.dp":"dp","vnd.osgi.subsystem":"esa","vnd.palm":["pdb","pqa","oprc"],"vnd.pawaafile":"paw","vnd.pg.format":"str","vnd.pg.osasli":"ei6","vnd.picsel":"efif","vnd.pmi.widget":"wg","vnd.pocketlearn":"plf","vnd.powerbuilder6":"pbd","vnd.previewsystems.box":"box","vnd.proteus.magazine":"mgz","vnd.publishare-delta-tree":"qps","vnd.pvi.ptid1":"ptid","vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"vnd.realvnc.bed":"bed","vnd.recordare.musicxml":"mxl","vnd.recordare.musicxml+xml":"musicxml","vnd.rig.cryptonote":"cryptonote","vnd.rn-realmedia":"rm","vnd.rn-realmedia-vbr":"rmvb","vnd.route66.link66+xml":"link66","vnd.sailingtracker.track":"st","vnd.seemail":"see","vnd.sema":"sema","vnd.semd":"semd","vnd.semf":"semf","vnd.shana.informed.formdata":"ifm","vnd.shana.informed.formtemplate":"itp","vnd.shana.informed.interchange":"iif","vnd.shana.informed.package":"ipk","vnd.simtech-mindmapper":["twd","twds"],"vnd.smart.teacher":"teacher","vnd.solent.sdkm+xml":["sdkm","sdkd"],"vnd.spotfire.dxp":"dxp","vnd.spotfire.sfs":"sfs","vnd.stepmania.package":"smzip","vnd.stepmania.stepchart":"sm","vnd.sus-calendar":["sus","susp"],"vnd.svd":"svd","vnd.syncml+xml":"xsm","vnd.syncml.dm+wbxml":"bdm","vnd.syncml.dm+xml":"xdm","vnd.tao.intent-module-archive":"tao","vnd.tcpdump.pcap":["pcap","cap","dmp"],"vnd.tmobile-livetv":"tmo","vnd.trid.tpt":"tpt","vnd.triscape.mxs":"mxs","vnd.trueapp":"tra","vnd.ufdl":["ufd","ufdl"],"vnd.uiq.theme":"utz","vnd.umajin":"umj","vnd.unity":"unityweb","vnd.uoml+xml":"uoml","vnd.vcx":"vcx","vnd.visionary":"vis","vnd.vsf":"vsf","vnd.webturbo":"wtb","vnd.wolfram.player":"nbp","vnd.wqd":"wqd","vnd.wt.stf":"stf","vnd.xara":"xar","vnd.xfdl":"xfdl","vnd.yamaha.hv-dic":"hvd","vnd.yamaha.hv-script":"hvs","vnd.yamaha.hv-voice":"hvp","vnd.yamaha.openscoreformat":"osf","vnd.yamaha.openscoreformat.osfpvg+xml":"osfpvg","vnd.yamaha.smaf-audio":"saf","vnd.yamaha.smaf-phrase":"spf","vnd.yellowriver-custom-menu":"cmp","vnd.zul":["zir","zirz"],"vnd.zzazz.deck+xml":"zaz","voicexml+xml":"vxml",widget:"wgt",winhlp:"hlp","wsdl+xml":"wsdl","wspolicy+xml":"wspolicy","x-ace-compressed":"ace","x-authorware-bin":["aab","x32","u32","vox"],"x-authorware-map":"aam","x-authorware-seg":"aas","x-blorb":["blb","blorb"],"x-bzip":"bz","x-bzip2":["bz2","boz"],"x-cfs-compressed":"cfs","x-chat":"chat","x-conference":"nsc","x-dgc-compressed":"dgc","x-dtbncx+xml":"ncx","x-dtbook+xml":"dtb","x-dtbresource+xml":"res","x-eva":"eva","x-font-bdf":"bdf","x-font-ghostscript":"gsf","x-font-linux-psf":"psf","x-font-pcf":"pcf","x-font-snf":"snf","x-font-ttf":["ttf","ttc"],"x-font-type1":["pfa","pfb","pfm","afm"],"x-freearc":"arc","x-gca-compressed":"gca","x-glulx":"ulx","x-gramps-xml":"gramps","x-install-instructions":"install","x-lzh-compressed":["lzh","lha"],"x-mie":"mie","x-mobipocket-ebook":["prc","mobi"],"x-ms-application":"application","x-ms-shortcut":"lnk","x-ms-xbap":"xbap","x-msbinder":"obd","x-mscardfile":"crd","x-msclip":"clp","application/x-ms-installer":"msi","x-msmediaview":["mvb","m13","m14"],"x-msmetafile":["wmf","wmz","emf","emz"],"x-msmoney":"mny","x-mspublisher":"pub","x-msschedule":"scd","x-msterminal":"trm","x-mswrite":"wri","x-nzb":"nzb","x-pkcs12":["p12","pfx"],"x-pkcs7-certificates":["p7b","spc"],"x-research-info-systems":"ris","x-silverlight-app":"xap","x-sql":"sql","x-stuffitx":"sitx","x-subrip":"srt","x-t3vm-image":"t3","x-tex-tfm":"tfm","x-tgif":"obj","x-xliff+xml":"xlf","x-xz":"xz","x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"xaml+xml":"xaml","xcap-diff+xml":"xdf","xenc+xml":"xenc","xml-dtd":"dtd","xop+xml":"xop","xproc+xml":"xpl","xslt+xml":"xslt","xv+xml":["mxml","xhvml","xvml","xvm"],yang:"yang","yin+xml":"yin",envoy:"evy",fractals:"fif","internet-property-stream":"acx",olescript:"axs","vnd.ms-outlook":"msg","vnd.ms-pkicertstore":"sst","x-compress":"z","x-perfmon":["pma","pmc","pmr","pmw"],"ynd.ms-pkipko":"pko",gzip:["gz","tgz"],"smil+xml":["smi","smil"],"vnd.debian.binary-package":["deb","udeb"],"vnd.hzn-3d-crossword":"x3d","vnd.sqlite3":["db","sqlite","sqlite3","db-wal","sqlite-wal","db-shm","sqlite-shm"],"vnd.wap.sic":"sic","vnd.wap.slc":"slc","x-krita":["kra","krz"],"x-perl":["pm","pl"],yaml:["yaml","yml"]},audio:{amr:"amr","amr-wb":"awb",annodex:"axa",basic:["au","snd"],flac:"flac",midi:["mid","midi","kar","rmi"],mpeg:["mpga","mpega","mp3","m4a","mp2a","m2a","m3a"],mpegurl:"m3u",ogg:["oga","ogg","spx"],"prs.sid":"sid","x-aiff":"aifc","x-gsm":"gsm","x-ms-wma":"wma","x-ms-wax":"wax","x-pn-realaudio":"ram","x-realaudio":"ra","x-sd2":"sd2",adpcm:"adp",mp4:"mp4a",s3m:"s3m",silk:"sil","vnd.dece.audio":["uva","uvva"],"vnd.digital-winds":"eol","vnd.dra":"dra","vnd.dts":"dts","vnd.dts.hd":"dtshd","vnd.lucent.voice":"lvp","vnd.ms-playready.media.pya":"pya","vnd.nuera.ecelp4800":"ecelp4800","vnd.nuera.ecelp7470":"ecelp7470","vnd.nuera.ecelp9600":"ecelp9600","vnd.rip":"rip",webm:"weba","x-caf":"caf","x-matroska":"mka","x-pn-realaudio-plugin":"rmp",xm:"xm",aac:"aac",aiff:["aiff","aif","aff"],opus:"opus",wav:"wav"},chemical:{"x-alchemy":"alc","x-cache":["cac","cache"],"x-cache-csf":"csf","x-cactvs-binary":["cbin","cascii","ctab"],"x-cdx":"cdx","x-chem3d":"c3d","x-cif":"cif","x-cmdf":"cmdf","x-cml":"cml","x-compass":"cpa","x-crossfire":"bsd","x-csml":["csml","csm"],"x-ctx":"ctx","x-cxf":["cxf","cef"],"x-embl-dl-nucleotide":["emb","embl"],"x-gamess-input":["inp","gam","gamin"],"x-gaussian-checkpoint":["fch","fchk"],"x-gaussian-cube":"cub","x-gaussian-input":["gau","gjc","gjf"],"x-gaussian-log":"gal","x-gcg8-sequence":"gcg","x-genbank":"gen","x-hin":"hin","x-isostar":["istr","ist"],"x-jcamp-dx":["jdx","dx"],"x-kinemage":"kin","x-macmolecule":"mcm","x-macromodel-input":"mmod","x-mdl-molfile":"mol","x-mdl-rdfile":"rd","x-mdl-rxnfile":"rxn","x-mdl-sdfile":"sd","x-mdl-tgf":"tgf","x-mmcif":"mcif","x-mol2":"mol2","x-molconn-Z":"b","x-mopac-graph":"gpt","x-mopac-input":["mop","mopcrt","zmt"],"x-mopac-out":"moo","x-ncbi-asn1":"asn","x-ncbi-asn1-ascii":["prt","ent"],"x-ncbi-asn1-binary":"val","x-rosdal":"ros","x-swissprot":"sw","x-vamas-iso14976":"vms","x-vmd":"vmd","x-xtel":"xtel","x-xyz":"xyz"},font:{otf:"otf",woff:"woff",woff2:"woff2"},image:{gif:"gif",ief:"ief",jpeg:["jpeg","jpg","jpe","jfif","jfif-tbnl","jif"],pcx:"pcx",png:"png","svg+xml":["svg","svgz"],tiff:["tiff","tif"],"vnd.djvu":["djvu","djv"],"vnd.wap.wbmp":"wbmp","x-canon-cr2":"cr2","x-canon-crw":"crw","x-cmu-raster":"ras","x-coreldraw":"cdr","x-coreldrawpattern":"pat","x-coreldrawtemplate":"cdt","x-corelphotopaint":"cpt","x-epson-erf":"erf","x-icon":"ico","x-jg":"art","x-jng":"jng","x-nikon-nef":"nef","x-olympus-orf":"orf","x-portable-anymap":"pnm","x-portable-bitmap":"pbm","x-portable-graymap":"pgm","x-portable-pixmap":"ppm","x-rgb":"rgb","x-xbitmap":"xbm","x-xpixmap":"xpm","x-xwindowdump":"xwd",bmp:"bmp",cgm:"cgm",g3fax:"g3",ktx:"ktx","prs.btif":"btif",sgi:"sgi","vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"vnd.dwg":"dwg","vnd.dxf":"dxf","vnd.fastbidsheet":"fbs","vnd.fpx":"fpx","vnd.fst":"fst","vnd.fujixerox.edmics-mmr":"mmr","vnd.fujixerox.edmics-rlc":"rlc","vnd.ms-modi":"mdi","vnd.ms-photo":"wdp","vnd.net-fpx":"npx","vnd.xiff":"xif",webp:"webp","x-3ds":"3ds","x-cmx":"cmx","x-freehand":["fh","fhc","fh4","fh5","fh7"],"x-pict":["pic","pct"],"x-tga":"tga","cis-cod":"cod",avif:"avifs",heic:["heif","heic"],pjpeg:["pjpg"],"vnd.adobe.photoshop":"psd","x-adobe-dng":"dng","x-fuji-raf":"raf","x-icns":"icns","x-kodak-dcr":"dcr","x-kodak-k25":"k25","x-kodak-kdc":"kdc","x-minolta-mrw":"mrw","x-panasonic-raw":["raw","rw2","rwl"],"x-pentax-pef":["pef","ptx"],"x-sigma-x3f":"x3f","x-sony-arw":"arw","x-sony-sr2":"sr2","x-sony-srf":"srf"},message:{rfc822:["eml","mime","mht","mhtml","nws"]},model:{iges:["igs","iges"],mesh:["msh","mesh","silo"],vrml:["wrl","vrml"],"x3d+vrml":["x3dv","x3dvz"],"x3d+xml":"x3dz","x3d+binary":["x3db","x3dbz"],"vnd.collada+xml":"dae","vnd.dwf":"dwf","vnd.gdl":"gdl","vnd.gtw":"gtw","vnd.mts":"mts","vnd.usdz+zip":"usdz","vnd.vtu":"vtu"},text:{"cache-manifest":["manifest","appcache"],calendar:["ics","icz","ifb"],css:"css",csv:"csv",h323:"323",html:["html","htm","shtml","stm"],iuls:"uls",plain:["txt","text","brf","conf","def","list","log","in","bas","diff","ksh"],richtext:"rtx",scriptlet:["sct","wsc"],texmacs:"tm","tab-separated-values":"tsv","vnd.sun.j2me.app-descriptor":"jad","vnd.wap.wml":"wml","vnd.wap.wmlscript":"wmls","x-bibtex":"bib","x-boo":"boo","x-c++hdr":["h++","hpp","hxx","hh"],"x-c++src":["c++","cpp","cxx","cc"],"x-component":"htc","x-dsrc":"d","x-diff":"patch","x-haskell":"hs","x-java":"java","x-literate-haskell":"lhs","x-moc":"moc","x-pascal":["p","pas","pp","inc"],"x-pcs-gcd":"gcd","x-python":"py","x-scala":"scala","x-setext":"etx","x-tcl":["tcl","tk"],"x-tex":["tex","ltx","sty","cls"],"x-vcalendar":"vcs","x-vcard":"vcf",n3:"n3","prs.lines.tag":"dsc",sgml:["sgml","sgm"],troff:["t","tr","roff","man","me","ms"],turtle:"ttl","uri-list":["uri","uris","urls"],vcard:"vcard","vnd.curl":"curl","vnd.curl.dcurl":"dcurl","vnd.curl.scurl":"scurl","vnd.curl.mcurl":"mcurl","vnd.dvb.subtitle":"sub","vnd.fly":"fly","vnd.fmi.flexstor":"flx","vnd.graphviz":"gv","vnd.in3d.3dml":"3dml","vnd.in3d.spot":"spot","x-asm":["s","asm"],"x-c":["c","h","dic"],"x-fortran":["f","for","f77","f90"],"x-opml":"opml","x-nfo":"nfo","x-sfv":"sfv","x-uuencode":"uu",webviewhtml:"htt",javascript:"js",json:"json",markdown:["md","markdown","mdown","markdn"],"vnd.wap.si":"si","vnd.wap.sl":"sl"},video:{avif:"avif","3gpp":"3gp",annodex:"axv",dl:"dl",dv:["dif","dv"],fli:"fli",gl:"gl",mpeg:["mpeg","mpg","mpe","m1v","m2v","mp2","mpa","mpv2"],mp4:["mp4","mp4v","mpg4"],quicktime:["qt","mov"],ogg:"ogv","vnd.mpegurl":["mxu","m4u"],"x-flv":"flv","x-la-asf":["lsf","lsx"],"x-mng":"mng","x-ms-asf":["asf","asx","asr"],"x-ms-wm":"wm","x-ms-wmv":"wmv","x-ms-wmx":"wmx","x-ms-wvx":"wvx","x-msvideo":"avi","x-sgi-movie":"movie","x-matroska":["mpv","mkv","mk3d","mks"],"3gpp2":"3g2",h261:"h261",h263:"h263",h264:"h264",jpeg:"jpgv",jpm:["jpm","jpgm"],mj2:["mj2","mjp2"],"vnd.dece.hd":["uvh","uvvh"],"vnd.dece.mobile":["uvm","uvvm"],"vnd.dece.pd":["uvp","uvvp"],"vnd.dece.sd":["uvs","uvvs"],"vnd.dece.video":["uvv","uvvv"],"vnd.dvb.file":"dvb","vnd.fvt":"fvt","vnd.ms-playready.media.pyv":"pyv","vnd.uvvu.mp4":["uvu","uvvu"],"vnd.vivo":"viv",webm:"webm","x-f4v":"f4v","x-m4v":"m4v","x-ms-vob":"vob","x-smv":"smv",mp2t:"ts"},"x-conference":{"x-cooltalk":"ice"},"x-world":{"x-vrml":["vrm","flr","wrz","xaf","xof"]}};(()=>{const 
2r={};for(const e of Object.keys(jc))for(const t of Object.keys(jc[e])){const n=jc[e][t];if(typeof n=="string")r[n]=e+"/"+t;else for(let i=0;i<n.length;i++)r[n[i]]=e+"/"+t}return r})(),Wb(Ba);const Ei=".",sT=r=>{var e;return r&&r.includes(Ei)&&((e=r.split(Ei).pop())==null?void 0:e.trim())||null},aT=r=>r.includes(Ei)?r.split(Ei).slice(0,-1).join(Ei):r,oT=(r,e)=>{const t=sT(r),n=e(aT(r));return t?`${n}${Ei}${t}`:n},bs="/",cT=r=>r?r.replace(/\\/g,bs).split(bs).filter(Boolean):[],lT=(r,e)=>{const t=cT(r),n=t.length<=1,i=t.shift()||"";return n?oT(i,e):`${e(i)}${bs}${t.join(bs)}`},uT=async(r,e)=>{const t=new Wk(r),{onProgress:n}=e||{};let i=0,s=0;const a=new TransformStream({transform(o,c){s+=o.byteLength,n==null||n({sourceBytesRead:i,destinationBytesWritten:s}),c.enqueue(o)}});return{zipStream:t.readable.pipeThrough(a),writeZip:async o=>{const c=new Map;for(const l of o){const u=typeof l=="function"?await l():l;if(!u)continue;const{path:d,stream:f,options:h}=u;let p=d,m=2;for(;c.has(p);)p=lT(d,g=>`${g}(${m})`),m++;const A=new TransformStream({transform(g,w){w.enqueue(g),i+=g.byteLength,n==null||n({sourceBytesRead:i,destinationBytesWritten:s})}});c.set(p,await t.zipWriter.add(p,f.pipeThrough(A),h))}return await t.close(),c}}};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function dT(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Xc(r,...e){if(!dT(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function _m(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function fT(r,e){Xc(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Jc(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function $c(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Zc(r,e){return r<<e|r>>>32-e>>>0}function hT(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Fm(r){return typeof r=="string"&&(r=hT(r)),Xc(r),r}class mT{}function pT(r){const e=n=>r().update(Fm(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function gT(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);const i=BigInt(32),s=BigInt(4294967295),a=Number(t>>i&s),o=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,a,n),r.setUint32(e+l,o,n)}function AT(r,e,t){return r&e^~r&t}function wT(r,e,t){return r&e^r&t^e&t}class yT extends mT{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=$c(this.buffer)}update(e){_m(this),e=Fm(e),Xc(e);const{view:t,buffer:n,blockLen:i}=this,s=e.length;for(let a=0;a<s;){const o=Math.min(i-this.pos,s-a);if(o===i){const c=$c(e);for(;i<=s-a;a+=i)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){_m(this),fT(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:i,isLE:s}=this;let{pos:a}=this;t[a++]=128,Jc(this.buffer.subarray(a)),this.padOffset>i-a&&(this.process(n,0),a=0);for(let d=a;d<i;d++)t[d]=0;gT(n,i-8,BigInt(this.length*8),s),this.process(n,0);const o=$c(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)o.setUint32(4*d,u[d],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:i,finished:s,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=s,e.length=i,e.pos=o,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Es=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),hn=new Uint32Array(80);class bT extends yT{constructor(){super(64,20,8,!1),this.A=Es[0]|0,this.B=Es[1]|0,this.C=Es[2]|0,this.D=Es[3]|0,this.E=Es[4]|0}get(){const{A:e,B:t,C:n,D:i,E:s}=this;return[e,t,n,i,s]}set(e,t,n,i,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)hn[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)hn[c]=Zc(hn[c-3]^hn[c-8]^hn[c-14]^hn[c-16],1);let{A:n,B:i,C:s,D:a,E:o}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=AT(i,s,a),u=1518500249):c<40?(l=i^s^a,u=1859775393):c<60?(l=wT(i,s,a),u=2400959708):(l=i^s^a,u=3395469782);const d=Zc(n,5)+l+o+u+hn[c]|0;o=a,a=s,s=Zc(i,30),i=n,n=d}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,this.set(n,i,s,a,o)}roundClean(){Jc(hn)}destroy(){this.set(0,0,0,0,0),Jc(this.buffer)}}const ET=pT(()=>new bT);class Rm extends TransformStream{constructor(){let e=null;super({start:()=>{e=ET.create()},transform:(t,n)=>{e&&e.update(t),n.enqueue(t)},flush:()=>{e&&this.sha1PromiseWithResolvers.resolve(e.digest())}}),this.sha1PromiseWithResolvers=on()}getSha1(){return this.sha1PromiseWithResolvers.promise}}const Dm=180*1e3+1e4;
2class kT{constructor(e){this.target=e,this.handlers=new Set}start(){var t,n;const e=i=>{this.handlers.forEach(s=>{s(i)})};return(n=(t=this.target).start)==null||n.call(t),this.target.addEventListener("message",e),()=>{this.handlers.clear(),this.target.removeEventListener("message",e)}}getApiOptions(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptions":{s.id===e&&(this.handlers.delete(n),t(s.apiOptions));break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptions",id:e})})}getApiOptionsInit(e,t){const n=t||{},i=crypto.randomUUID();return new Promise(s=>{const a=o=>{const{data:c}=o;switch(c.type){case"msgChannelServerApiOptionsInit":{c.id===i&&(this.handlers.delete(a),s(c.apiOptionsInit));break}}};this.handlers.add(a),this.target.postMessage({type:"msgChannelClientApiOptionsInit",id:i,apiInput:C0(e),apiInit:{...t,body:typeof(n==null?void 0:n.body)=="string"?n.body:void 0,headers:ga(n==null?void 0:n.headers),signal:void 0}})})}getCsrfFetcher(){return{getCsrfToken:()=>this.apiOptionsGetCsrfToken(),invalidateCsrfToken:()=>this.apiOptionsInvalidateCsrfToken(),getFetchedCsrfToken:()=>this.apiOptionsGetFetchedCsrfToken()}}getTurnstileToken(){const e=crypto.randomUUID();return new Promise((t,n)=>{const i=c=>{const{data:l}=c;switch(l.type){case"msgChannelServerApiOptionsGetTurnstileToken":{l.id===e&&(s(),l.turnstileToken?t(l.turnstileToken):n(new Error(l.error||"Turnstile challenge failed")));break}}},s=()=>{this.handlers.delete(i),o.removeEventListener("abort",a)},a=()=>{s(),n(new Error(`Turnstile token request was not answered within ${Dm}ms`))},o=AbortSignal.timeout(Dm);o.addEventListener("abort",a),this.handlers.add(i),this.target.postMessage({type:"msgChannelClientApiOptionsGetTurnstileToken",id:e})})}getAuthFetcher(){return{getAuthToken:()=>this.apiOptionsGetAuthToken(),invalidateAuthToken:()=>this.apiOptionsInvalidateAuthToken()}}apiOptionsGetCsrfToken(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptionsGetCsrfToken":{s.id===e&&(this.handlers.delete(n),t(s.csrfToken));break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptionsGetCsrfToken",id:e})})}apiOptionsInvalidateCsrfToken(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptionsInvalidateCsrfToken":{s.id===e&&(this.handlers.delete(n),t());break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptionsInvalidateCsrfToken",id:e})})}apiOptionsGetFetchedCsrfToken(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptionsFetchedCsrfToken":{s.id===e&&(this.handlers.delete(n),t(s.csrfToken));break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptionsFetchedCsrfToken",id:e})})}apiOptionsGetAuthToken(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptionsGetAuthToken":{s.id===e&&(this.handlers.delete(n),t(s.authToken));break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptionsGetAuthToken",id:e})})}apiOptionsInvalidateAuthToken(){const e=crypto.randomUUID();return new Promise(t=>{const n=i=>{const{data:s}=i;switch(s.type){case"msgChannelServerApiOptionsInvalidateAuthToken":{s.id===e&&(this.handlers.delete(n),t());break}}};this.handlers.add(n),this.target.postMessage({type:"msgChannelClientApiOptionsInvalidateAuthToken",id:e})})}}const Mm=(r,e)=>typeof OffscreenCanvas=="function"&&r instanceof OffscreenCanvas?r.convertToBlob(e):new Promise((t,n)=>{try{r.toBlob(i=>{i?t(i):n()},e==null?void 0:e.type,e==null?void 0:e.quality)}catch{n()}}),TT=r=>{const{width:e=0,height:t=0,context2DSettings:n}=r||{},i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d",n);if(!s)throw new Error("Canvas context couldn't be created");return{canvas:i,context:s,getBlob:a=>Mm(i,a)}},ST=()=>typeof OffscreenCanvas=="function",Um=r=>{const{width:e=0,height:t=0,context2DSettings:n}=r||{};if(!ST())throw new Error("Offscreen Canvas API not supported");const i=new OffscreenCanvas(e,t),s=i.getContext("2d",n);if(!s)throw new Error("Offscreen Canvas context couldn't be created");return{canvas:i,context:s,getBlob:a=>Mm(i,a)}},Om=r=>{try{return Um(r)}catch{}return TT(r)},CT=r=>{if(typeof r=="string")return[r];const e=URL.createObjectURL(r);return[e,()=>URL.revokeObjectURL(e)]},IT=async r=>{const[e,t]=CT(r),n=document.createElement("img"),i=new Promise((a,o)=>{n.onload=()=>{a(n)},n.onerror=()=>{o(new Error(`Couldn't load image: ${e}`))}});n.src=e;const s=Tt({mediaElement:n,dispose:()=>{t==null||t()}});return n.complete?s:i.catch(a=>pe(wt(a))).then(()=>s)},BT=async r=>{if(r instanceof Blob){const e=await IT(r);if(!e.ok)return e;const{mediaElement:t,dispose:n}=e.value;return Tt({dispose:()=>{n()}
2,width:t.naturalWidth,height:t.naturalHeight,source:t})}if(r instanceof HTMLVideoElement)return Tt({dispose:pa,width:r.videoWidth,height:r.videoHeight,source:r});if(r instanceof HTMLImageElement)return Tt({dispose:pa,width:r.naturalWidth,height:r.naturalHeight,source:r});if(r instanceof SVGImageElement){const{width:e,height:t}=r.getBBox();return Tt({dispose:pa,width:e,height:t,source:r})}return Tt({dispose:pa,width:r.width,height:r.height,source:r})},xT=async r=>{try{const e=await createImageBitmap(r);return Tt({dispose:()=>e.close(),height:e.height,width:e.width,source:e})}catch(e){return pe(wt(e))}},PT=async r=>{const e=await xT(r);return e.ok?e:BT(r)},Nm=(r,e,t=!1,n=.5,i=.5,s=1)=>{const{width:a,height:o}=e,{width:c,height:l}=r,u=c/l,d=a/o;let f=a*s,h=o*s;return(t?u>d:u<d)?h=f/u:f=h*u,{width:f,height:h,offsetX:(a-f)*n,offsetY:(o-h)*i}},Qm={width:256,height:256},vT=.86,_T=r=>{const e=Om({width:20,height:20});return e.context.fillStyle="#fff",e.context.fillRect(0,0,20,20),e.context.fillStyle="#D0D5DD",e.context.fillRect(10,0,10,10),e.context.fillRect(0,10,10,10),r.createPattern(e.canvas,"repeat")},FT=async(r,{width:e,height:t})=>{const{width:n,height:i,offsetX:s,offsetY:a}=Nm({width:e,height:t},Qm),o=await PT(r);if(!o.ok)return null;const{dispose:c,source:l}=o.value,{context:u,getBlob:d}=Om({...Qm,context2DSettings:{alpha:!1,desynchronized:!0}}),f=_T(u);f&&(u.fillStyle=f),u.fillRect(0,0,n,i),u.drawImage(l,s,a,n,i);const h=await d({type:"image/jpeg",quality:vT}).catch(()=>null);return c(),h};var RT="/build/workers/worker-BAOIWoxA.js",DT="/build/assets/ffmpeg-core-CI9Irx9p.js",MT="/build/assets/ffmpeg-core-CgUfceKH.wasm";const Lm=new Map,UT=async r=>{const{signal:e,timeout:t=45e3,classWorkerURL:n=RT,coreURL:i=DT,wasmURL:s=MT}=r||{},a=on(),o=()=>{clearTimeout(c),a.resolve(pe(new Error("Ffmpeg load timed out or was aborted"))),e==null||e.removeEventListener("abort",o)},c=setTimeout(o,t);return e==null||e.addEventListener("abort",o),e!=null&&e.aborted&&o(),(async()=>{const{FFmpeg:l}=await Promise.resolve().then(function(){return gS}),d=JSON.stringify({coreURL:i,wasmURL:s,classWorkerURL:n}),f=Lm.get(d);if(f)return f;const h=new l,p=new Promise(m=>{h.load({coreURL:i,wasmURL:s,classWorkerURL:n}).then(A=>{m(A?Tt(h):pe(new Error("Ffmpeg load wasn't successful")))}).catch(A=>m(pe(wt(A,new Error(`Ffmpeg load error: ${A}`)))))});return Lm.set(d,p),p})().then(l=>{a.resolve(l)}),a.promise},zm=1e3,OT=["B","KB","MB","GB","TB","PB"],el=(r,e={})=>{if(!r)return"0B";const t=Math.floor(Math.log(r)/Math.log(zm));return new Intl.NumberFormat("en-US",{style:"decimal",maximumFractionDigits:1,...e}).format(r/Math.pow(zm,t))+OT[t]},Wm=(r,e,t)=>{const n=new DataView(r.buffer),i=[],s=r.length/e;for(let a=0;a<e;a++){const o=Math.floor(a*s),c=Math.ceil((a+1)*s);let l=0;for(let u=o;u<c;u+=2){const d=Math.floor(u/2)*2,f=n.getInt16(d,!0);Math.abs(f)>Math.abs(l)&&(l=f)}i.push(Math.round(l*t)/t)}return i},Vm=500*1024*1024,NT=async(r,e,t,n,i)=>{const s=[],{promise:a,resolve:o}=on(),c=u=>{s.forEach(d=>{d()}),o(u)};n&&n.addEventListener("abort",()=>{c(pe(new Error("Pcm data operation was aborted")))});const l=setTimeout(()=>{c(pe(new Error("Pcm data operation timed out")))},i);return s.push(()=>clearTimeout(l)),(async()=>{try{const{Input:u,Output:d,Conversion:f,BlobSource:h,BufferTarget:p,WavOutputFormat:m,AudioSampleSink:A,BufferSource:g,ALL_FORMATS:w,WAVE:b}=await Promise.resolve().then(function(){return s1}),k=new u({formats:w,source:new h(r)});s.push(()=>k.dispose());const S=new d({format:new m,target:new p}),x=await f.init({input:k,output:S,audio:{sampleRate:1e3,codec:"pcm-s16"}});if(s.push(()=>x.cancel()),await x.execute(),!S.target.buffer)throw new Error("No Output Buffer");const B=new u({formats:[b],source:new g(S.target.buffer)});s.push(()=>B.dispose());const I=await B.getPrimaryAudioTrack();if(!I)throw new Error("No Audio Track");const C=new A(I);let v=new Uint8Array;for await(const R of C.samples()){s.push(()=>R.close());const{numberOfChannels:M}=R,z=[];let W=1/0;for(let U=0;U<M;U++){const j=R.allocationSize({format:"s16-planar",planeIndex:U}),ce=new Int16Array(j/2);R.copyTo(ce,{format:"s16-planar",planeIndex:U}
2),z.push(ce),W=Math.min(W,ce.length)}const H=new Int16Array(W);for(let U=0;U<W;U++){const j=z.reduce((ce,ee)=>ce+ee[U],0)/M;H[U]=j}v=S0(v,new Uint8Array(H.buffer)),R.close()}c(Tt(Wm(v,e,t)))}catch(u){c(pe(wt(u)))}})(),a},QT=async(r,e,t,n,i,s)=>{const a=performance.now(),o=await UT({signal:n,timeout:i,...s}),c=performance.now()-a;if(!o.ok)return o;if(n!=null&&n.aborted)return pe(new Error("Pcm data operation was aborted"));const{value:l}=o,u=crypto.randomUUID(),d=`audio-${u}`,f=`pcm-${u}`,h=async()=>{await Promise.all([l.deleteFile(d).catch(()=>null),l.deleteFile(f).catch(()=>null)])};try{if(!await l.writeFile(d,new Uint8Array(await r.arrayBuffer()),{signal:n}))throw new Error(`FFmpeg couldn't write ${d}`);const m=await l.exec([...`-i ${d} -ac 1 -filter_complex:a aresample=1000 -map 0:a -c:a pcm_s16le -f data ${f}`.split(" ").filter(w=>!!w)],i-c,{signal:n});if(m!==0)throw new Error(`FFmpeg executed with code: ${m}`);const A=await l.readFile(f,void 0,{signal:n});if(!(A instanceof Uint8Array))throw new Error("FFmpeg read file didn't return binary data");const g=Wm(A,e,t);return Tt(g)}catch(p){return pe(wt(p,new Error(`Pcm data error: ${p}`)))}finally{await h()}},LT=async(r,e)=>{if(r.size>Vm)return pe(new Error(`Pcm data size limit is ${el(Vm)}`));const{maxLength:t=8e3,precision:n=1e4,signal:i,timeout:s=45e3,ffmpegOptions:a}=e||{},o=await NT(r,t,n,i,s);return o.ok?o:(console.log(o.error),QT(r,t,n,i,s,a))},zT=async(r,e)=>{const t=await LT(r,e);if(!t.ok)return null;try{const n={length:t.value.length,data:t.value},i=new TextEncoder().encode(JSON.stringify(n));return new Blob([i],{type:"application/json"})}catch{return null}},WT=3,Hm=async(r,e,t)=>{var m;const{init:n,retry:i,signal:s,onPartCreated:a,onPartStart:o,onPartProgress:c,onPartEnd:l}=t||{},{data:u,partNumber:d}=r,f={partNumber:d,size:u.size};a==null||a(f);let h=0,p=null;for(;;){let A,g;try{({url:A,method:g}=await e())}catch(k){return pe(wt(k,new Error(`S3 Part upload could not resolve URL for Part #${d}`)))}const w=await F0(A,{init:async k=>{const S=await O0(n,k)||{};return{...S,withCredentials:!1,signal:nf(S.signal,s),method:g,body:u,progressStall:2e4,headers:ga(S.headers,{"content-type":u.type||"application/octet-stream"})}},inspect:k=>!(k.status>=200&&k.status<300)&&pe(new or(new Error(`S3 Part upload (${g}) failed for Part #${d}. (${k.status})`),k)),uploadCallbacks:{onLoadStart(k){o==null||o(f,{loaded:k.loaded,total:k.total})},onProgress(k){c==null||c(f,{loaded:k.loaded,total:k.total})},onLoad(k){l==null||l(f,{loaded:k.loaded,total:k.total})}}});if(w.ok){const k=w.value.getResponseHeader("ETag");return k?Tt({partNumber:d,size:u.size,eTag:k}):pe(new Error("S3 Part upload could not find eTag header in upload response"))}p=w.error;let b;try{b=await N0(i,h,w.error)}catch{break}if(typeof b!="number"||((m=w.error.xhr)==null?void 0:m.status)===403&&h>=WT)break;b>0&&await new Promise(k=>setTimeout(k,b)),h++}return pe(new Error(`S3 Part upload could not upload data (${el(u.size)}): ${(p==null?void 0:p.message)??"Unknown error"}`))},VT=async(r,e,t)=>{const{apiOptions:n,createUploadRequest:i}=e,{signal:s,retry:a,onProgress:o}=t||{},c=dc(wf,{...n,retry:a}),l=await wa(c.createSingleFileUpload({createUploadRequest:i}));if(!l.ok)return pe(new Error(`Could not create S3 Singlepart upload: ${l.error.code}`));const{method:u,url:d,resultS3Url:f}=l.value,h={partNumber:1,data:new Blob};try{await r.pipeTo(new WritableStream({write:A=>{h.data=new Blob([h.data,A])}}),{signal:s})}catch(A){return pe(new Error(`S3 Singlepart upload stream error: ${wt(A).message}`))}let p={loaded:0};const m=await Hm(h,async()=>({url:d,method:u}),{...t,onPartProgress:(A,g)=>{var w;(w=t==null?void 0:t.onPartProgress)==null||w.call(t,A,g),p={...g,loaded:Math.max(p.loaded,g.loaded)},o==null||o(p)}});return m.ok?Tt({s3Url:f,size:m.value.size,parts:[m.value]}):pe(new Error(`S3 Singlepart upload error: ${m.error.message}`))},HT=async(r,e,t,n)=>Hm(t,async()=>{const s=await wa(r.signPart({...e,partNumber:t.partNumber}));if(!s.ok)throw new Error(`Could not sign part #${t.partNumber} (${el(t.data.size)}): ${s.error.code}`);return s.value},n),GT=async(r,e,t,n)=>{const{apiOptions:i,createUploadRequest:s}=e,{maxPartSize:a,maxParallelParts:o}=t,{signal:c,retry:l,onProgress:u}=n||{},d=dc(wf,{...i,async init(B,I){const C=await df(i.init,B,I);
2return os(f,C.signal),{...C,signal:f.signal}},retry:l}),f=new AbortController,h=await wa(d.createMultipartFileUpload({createUploadRequest:s}));if(!h.ok)return pe(new Error(`Could not create S3 Multipart upload: ${h.error.code}`));const p=new Map,m=[],A=new Map;let g={partNumber:1,data:new Blob([])};const w=B=>{if(Array.from(A.keys()).find(({partNumber:W})=>W===B.partNumber)||m.find(({partNumber:W})=>W===B.partNumber))return;const{data:v,partNumber:R}=B;if(v.size===0&&R!==1)return;const M={partNumber:R,size:v.size},z=HT(d,h.value,B,{...n,signal:f.signal,onPartProgress:(W,H)=>{var j;(j=n==null?void 0:n.onPartProgress)==null||j.call(n,W,H);const U=p.get(W)||H;p.set(W,{...U,loaded:Math.max(U.loaded,H.loaded)}),u==null||u(Array.from(p.values()).reduce((ce,{loaded:ee})=>({...ce,loaded:ce.loaded+ee}),{loaded:0}))}});A.set(M,z)},b=B=>{const I=Array.from(A.entries()).find(([{partNumber:C}])=>C===B.partNumber);I&&A.delete(I[0]),m.push(B)},k=B=>{x(B),A.clear(),p.clear(),f.signal.aborted||f.abort(B)},{promise:S,resolve:x}=on();return f.signal.addEventListener("abort",()=>{const{reason:B}=f.signal;k(pe(wt(B,new Error(`S3 Multipart upload aborted: ${B}`))))}),os(f,c),(async()=>{try{await r.pipeTo(new WritableStream({async write(I){if(g.data=new Blob([g.data,I]),g.data.size>=a){const C=g.data.slice(0,a),v={partNumber:g.partNumber,data:C};w(v),g={partNumber:g.partNumber+1,data:g.data.slice(v.data.size)}}if(A.size>=o){const C=Array.from(A.values()),v=await Promise.race(C);if(!v.ok)throw v.error;b(v.value)}},async close(){const I=g.data.slice(0,a),C={partNumber:g.partNumber,data:I};w(C);const v=Array.from(A.values()),R=await Promise.all(v);for(const M of R){if(!M.ok)throw M.error;b(M.value)}}}),{signal:f.signal}),m.sort((I,C)=>I.partNumber-C.partNumber);const B=await wa(d.completeMultipartUpload({...h.value,completeMultipartUploadRequest:{parts:m}}));if(!B.ok)throw new Error(`Could not complete multipart upload: ${B.error.code}`);k(Tt({s3Url:B.value.resultS3Url,size:m.reduce((I,{size:C})=>I+C,0),parts:m.map(({partNumber:I,size:C})=>({partNumber:I,size:C}))}))}catch(B){k(pe(new Error(`S3 Multipart upload error: ${wt(B).message}`)))}})(),S},Gm=(r,e,t,n)=>{const{strategies:i=["stream","multipart","singlepart"]}=n||{},{promise:s,resolve:a}=on();return(async()=>{try{for(const o of i)if(o!=="stream"){if(o==="multipart"){a(await GT(r,e,t,n));return}if(o==="singlepart"){a(await VT(r,e,n));return}}}catch(o){a(pe(wt(o,new Error(`S3 Upload error: ${o}
2`))))}a(pe(new Error(`S3 Upload no strategy returned a result. (${i.join(", ")})`)))})(),s};var Qa={staticContentItemEncryptionIvs:{mainFileNameBase64:"EtrUFVLIRAW8aUCd",mainFileBase64:"C8aZG384/qPpBzg=",mainFileSha1Base64:"6Q+YlJkg8RFR/FHN",previewFileBase64:"i3iv8Nv2xEje9VE="}};const tl=256,Ym=["encrypt","decrypt"],YT={ASYMMETRIC_PRIVATE_KEY:{keyFormat:"jwk",keyProperties:{name:"ECDH",namedCurve:"P-256"},keyUsages:["deriveBits","deriveKey"]},"SYMMETRIC_AES-GCM_KEY":{keyFormat:"raw",keyProperties:{name:"AES-GCM",length:tl},keyUsages:Ym},"SYMMETRIC_AES-CTR_KEY":{keyFormat:"raw",keyProperties:{name:"AES-CTR",length:tl},keyUsages:Ym},WRAPPING_KEY:{keyFormat:"raw",keyProperties:{name:"AES-KW",length:tl},keyUsages:["wrapKey","unwrapKey"]},WRAPPED_ASYMMETRIC_PRIVATE_KEY:{keyFormat:"raw",keyProperties:{name:"AES-CTR"},keyUsages:["wrapKey"]}},Km=new Map,qm=new Map;class pr{static getKeyProperties(e){return YT[e]}async createKeyWrappingKey(){const e=pr.getKeyProperties("WRAPPING_KEY");return crypto.subtle.generateKey(e.keyProperties,!0,e.keyUsages)}async createEncryptionAesCryptoKey(e){const t=pr.getKeyProperties(e);return{aesKeyType:e,cryptoKey:await crypto.subtle.generateKey(t.keyProperties,!0,t.keyUsages)}}async deriveEncryptionKeyFromAesKey(e,t){const n=pr.getKeyProperties(e.aesKeyType),i=await crypto.subtle.exportKey("raw",e.cryptoKey),s=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]),a=new TextEncoder;return{aesKeyType:e.aesKeyType,cryptoKey:await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",info:a.encode(t),salt:a.encode("no-salt-because-it-needs-to-be-deterministic")},s,n.keyProperties,!0,n.keyUsages)}}async serializeEncryptionAesCryptoKey({aesKeyType:e,cryptoKey:t}){return{aesKeyType:e,jwk:await crypto.subtle.exportKey("jwk",t)}}async deserializeEncryptionAesCryptoKey({aesKeyType:e,jwk:t}){const n=pr.getKeyProperties(e);return{aesKeyType:e,cryptoKey:await crypto.subtle.importKey("jwk",t,n.keyProperties,!0,n.keyUsages)}}randomSalt(){return crypto.getRandomValues(new Uint8Array(16))}async wrapWithPassphrase(e,t,n){const i=await this.generateWrappingKeyFromPassphrase(e,t),s=this.getWrappingFormat(n);return crypto.subtle.wrapKey(s,n,i,"AES-KW")}async extractPrivateKeyAndWrapWithPassphrase(e,t,n){const i=await this.generateWrappingKeyFromPassphrase(e,t);return this.extractPrivateKeyAndWrapWithWrappingKey(i,n)}async unwrapKeyWithPassphrase(e,t,n,i){const s=`${i}_${e}_${an(t)}_${an(n)}`,a=qm.get(s);if(a)return a;const o=await this.generateWrappingKeyFromPassphrase(e,t),{keyFormat:c,keyProperties:l,keyUsages:u}=pr.getKeyProperties(i),d=await crypto.subtle.unwrapKey(c,n,o,"AES-KW",l,!0,u);return qm.set(s,d),d}async unwrapKeyWithWrappingKey(e,t,n){const{keyFormat:i,keyProperties:s,keyUsages:a}=pr.getKeyProperties(n);return crypto.subtle.unwrapKey(i,t,e,"AES-KW",s,!0,a)}wrapWithWrappingKey(e,t){return crypto.subtle.wrapKey(this.getWrappingFormat(t),t,e,"AES-KW")}async extractPrivateKeyAndWrapWithWrappingKey(e,t){const n=await this.extractPrivateKey(t),i=await crypto.subtle.importKey("raw",sn(n),{name:"AES-CTR"},!0,["wrapKey"]);return crypto.subtle.wrapKey("raw",i,e,"AES-KW")}async encryptAesGcm(e,t,n){const i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e.cryptoKey,t);return{iv:n,encryptedData:i}}async encryptAesCtr(e,t,n,i){const s=this.getAesCtrNonce(n,i),a=await crypto.subtle.encrypt({name:"AES-CTR",counter:s,length:40},e.cryptoKey,t),o=i+Math.ceil(t.byteLength/16);return{iv:n,encryptedData:a,newCounter:o}}getAesCtrNonce(e,t){if(e.byteLength!==11)throw new Error("IV must be 11 bytes");if(t<0||t>0xffffffffff||!Number.isInteger(t))throw new Error("Counter must be a non-negative integer not exceeding 40 bits");const n=new ArrayBuffer(16);new Uint8Array(n).set(new Uint8Array(e),0);const s=new DataView(n,11,5);return s.setUint32(0,Math.floor(t/256),!1),s.setUint8(4,t%256),n}decryptAesGcm(e,t,n){return n.byteLength===0?new ArrayBuffer(0):crypto.subtle.decrypt({name:"AES-GCM",iv:t},e.cryptoKey,n)}async decryptAesCtr(e,t,n,i){if(i.byteLength==0)return{decryptedData:new ArrayBuffer(0),newCounter:n};const a={name:"AES-CTR",counter:this.getAesCtrNonce(t,n),length:40},o=await crypto.subtle.decrypt(a,e.cryptoKey,i),c=n+Math.ceil(i.byteLength/16);return{decryptedData:o,newCounter:c}}async exportPrivateKey(e){return JSON.stringify(await crypto.subtle.exportKey("jwk",e))}async importPrivateKey(e){const{keyProperties:t}=pr.getKeyProperties("ASYMMETRIC_PRIVATE_KEY");return await crypto.subtle.importKey("jwk",e,t,!0,["deriveKey","deriveBits"])}async generateWrappingKeyFromPassphrase(e,t){const n=`${e}_${an(t)}`,i=Km.get(n);if(i)return i;const s=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"]),a=pr.getKeyProperties("WRAPPING_KEY"),o=await crypto.subtle.deriveKey({name:"PBKDF2",iterations:1e5,hash:"SHA-256",salt:t},s,a.keyProperties,!0,a.keyUsages);return Km.set(n,o),o}getWrappingFormat(e){switch(e.type){case"private":return"jwk";case"public":case"secret":return"raw";default:throw new Error("Unsupported")}}async extractPrivateKey(e){if(e.type==="secret")return an(await crypto.subtle.exportKey("raw",e));const n=(await crypto.subtle.exportKey("jwk",e)).d;if(!n)throw Error("Could not extract private-key part");return T0(n)}}class jm{constructor(e){this.encryptionKeys=e,this.utf8TextEncoder=new TextEncoder,this.symmetricKeyService=new pr}async encryptFileContents(e){return await this.encryptAesCtr(e,sn(Qa.staticContentItemEncryptionIvs.mainFileBase64))}async encryptPreview(e){return await this.encryptAesCtr(e,sn(Qa.staticContentItemEncryptionIvs.previewFileBase64))}async encryptFileName(e){const t=await this.encryptAesGcm(this.utf8TextEncoder.encode(e),sn(Qa.staticContentItemEncryptionIvs.mainFileNameBase64));return{nameEncrypted:an(t)}}async encryptSha1(e){const t=await this.encryptAesGcm(e,sn(Qa.staticContentItemEncryptionIvs.mainFileSha1Base64));return{sha1Encrypted:an(t)}}async encryptAesGcm(e,t){const n=this.encryptionKeys.aesGcmCryptoKey;if(t.byteLength!==12)throw Error("AES-GCM requires a 12-byte IV");return(await this.symmetricKeyService.encryptAesGcm(n,e,t)).encryptedData}async encryptAesCtr(e,t){const n=this.encryptionKeys.aesCtrCryptoKey,i=this.symmetricKeyService;if(t.byteLength!==11)throw Error("AES-CTR requires a 11-byte IV");let s=0,a=new Uint8Array(0);const o=new TransformStream({async transform(c,l){const u=new Uint8Array(a.byteLength+c.byteLength);u.set(a,0),u.set(c,a.byteLength);const d=Math.floor(u.byteLength/16)*16,f=u.slice(0,d),{encryptedData:h,newCounter:p}
2=await i.encryptAesCtr(n,f,t,s);l.enqueue(new Uint8Array(h)),a=u.slice(d),s=p},async flush(c){if(a.byteLength>0){const{encryptedData:l,newCounter:u}=await i.encryptAesCtr(n,a,t,s);c.enqueue(new Uint8Array(l)),s=u}}});return e.pipeThrough(o)}}const Xm=async r=>{const e=new pr,[t,n]=await Promise.all([e.deserializeEncryptionAesCryptoKey(r.aesGcmJwk),e.deserializeEncryptionAesCryptoKey(r.aesCtrJwk)]);return{ephemeralPublicKey:r.ephemeralPublicKey,aesGcmCryptoKey:t,aesCtrCryptoKey:n}},Jm={sha1Names:["x6BHXOMaRK5nCIjWOP9ftrwFJyA="],sha1Hashes:["PmB5hC7xpfiwsuTAiBQxdYgloAw=","Mv6gYUOyM/x6SKQ2xYc2jqOxy04="]};var KT="/build/assets/320n-Boc8XrX1.onnx",qT="/build/assets/nms-yolov8-BHIYmFPb.onnx",jT="/build/assets/ort-wasm-simd-threaded-CEqy8P9J.mjs",XT="/build/assets/ort-wasm-simd-threaded-CpHjICJN.wasm";const JT="UNKNOWN",$T=["FEMALE_GENITALIA_COVERED","FACE_FEMALE","BUTTOCKS_EXPOSED","FEMALE_BREAST_EXPOSED","FEMALE_GENITALIA_EXPOSED","MALE_BREAST_EXPOSED","ANUS_EXPOSED","FEET_EXPOSED","BELLY_COVERED","FEET_COVERED","ARMPITS_COVERED","ARMPITS_EXPOSED","FACE_MALE","BELLY_EXPOSED","MALE_GENITALIA_EXPOSED","ANUS_COVERED","FEMALE_BREAST_COVERED","BUTTOCKS_COVERED"],ki={width:320,height:320};let rl=null;const nl=[1,3,ki.height,ki.width],ZT=100,eS=.45,tS=.25,rS=async()=>{const r=await Promise.resolve().then(function(){return F1}),{env:e}=r;return e.wasm.wasmPaths={mjs:jT,wasm:XT},r},nS=async()=>{const{Tensor:r,InferenceSession:e}=await rS(),[t,n]=await Promise.all([fetch(KT).then(s=>s.arrayBuffer()).then(s=>e.create(s)),fetch(qT).then(s=>s.arrayBuffer()).then(s=>e.create(s))]),i=new r("float32",new Float32Array(nl.reduce((s,a)=>s*a)),nl);return await t.run({images:i}),{analyzeImage:async s=>{const a=await sS(s),o=await r.fromImage(a,{dataType:"float32",tensorFormat:"RGB",tensorLayout:"NCHW"}),{output0:c}=await t.run({images:new r("float32",o.data,nl)}),{selected:l}=await n.run({detection:c,config:new r("float32",new Float32Array([ZT,eS,tS]))}),u=[];for(let d=0;d<l.dims[1];d++){const f=l.data.slice(d*l.dims[2],(d+1)*l.dims[2]),h=f.slice(0,4),p=f.slice(4),m=p.reduce((S,x)=>Math.max(S,x),-1),A=p.indexOf(m),[g,w,b,k]=[h[0]-.5*h[2],h[1]-.5*h[3],h[2],h[3]];u.push({labelId:A,label:$T[A]||JT,probability:m,bbx:[g,w,b,k]})}return{items:u}}}},iS=()=>(rl||(rl=nS()),rl),sS=async({data:r,width:e,height:t})=>{if(r instanceof ArrayBuffer)return new ImageData(new Uint8ClampedArray(r),e,t);const n={width:e,height:t},{context:i}=Um(ki),s=Nm(n,ki,!0);i.drawImage(r,s.offsetX,s.offsetY,s.width,s.height);const a=i.getImageData(0,0,ki.width,ki.height);return r.close(),a},aS=async r=>{const e=await iS().catch(wt);if(e instanceof Error)return pe(e.message);const t=await e.analyzeImage(r).catch(wt);return t instanceof Error?pe(t.message):Tt(t)};class oS{constructor(e){this.target=e}start(){var t,n;const e=async i=>{const{data:s}=i;switch(s.type){case"msgChannelClientNsfwAnalyzeImage":{this.target.postMessage({type:"msgChannelServerNsfwAnalyzeImage",id:s.id,result:await aS(s.image)});break}}};return(n=(t=this.target).start)==null||n.call(t),this.target.addEventListener("message",e),()=>{this.target.removeEventListener("message",e)}}}const cS=new oS(self),On=new kT(self),$m=ot({minDelay:1e3,maxDelay:2e4}),Zm=On.getCsrfFetcher(),ep=On.getAuthFetcher();typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&(addEventListener("error",({error:r})=>{throw r instanceof Error?r:typeof r=="string"?new Error(r):new Error(`[Upload worker] error: ${r}`)}),addEventListener("unhandledrejection",({reason:r})=>{throw r instanceof Error?r:typeof r=="string"?new Error(r):new Error(`[Upload worker] unhandledrejection: ${r}`)}),addEventListener("message",async r=>{const{data:e}=r;switch(e.type){case"imagePreview":{postMessage({type:"imagePreview",imagePreview:await FT(e.fileData,e.metadata).catch(()=>null)});break}case"audioWaveformJsonPreview":{postMessage({type:"audioWaveformJsonPreview",waveformJsonPreview:await zT(e.fileData,{ffmpegOptions:e.ffmpegOptions}).catch(()=>null)});break}case"previewUpload":{postMessage({type:"previewUpload",previewItem:await lS(e.preview,e.openUploadResultSerialized,e.encryptionKeysSerialized,e.uploadMultipartOptions)});break}case"fileUpload":{postMessage({type:"fileUpload",uploadedFile:await uS(e.openUploadResultSerialized,e.encryptionKeysSerialized,e.uploadMultipartOptions)});break}}}),On.start(),cS.start());async function lS(r,e,t,n){const{id:i,previewType:s,fileDescriptor:{data:a,type:o}}=r;if(!a)throw new Error("Couldn't get preview data");const l=await new jm(await Xm(t)).encryptPreview(a.stream()),u={...await On.getApiOptions(),init:(...f)=>On.getApiOptionsInit(...f),csrfFetcher:Zm,authFetcher:ep},d=await Gm(l,{apiOptions:u,createUploadRequest:{sharingBucket:e.sharingBucket,contentItem:e.contentItem,fileEncryptionKey:e.f
2ileEncryptionKey,metadataId:i}},n,{strategies:["stream","singlepart"],retry:(f,{underlyingError:h,response:p})=>{if(!(lc(p)||!p&&!af(h)))return $m(f)}});if(!d.ok)throw new Error(`Preview Upload Error: ${d.error}`);return{id:r.id,mediaType:o,type:s}}async function uS(r,e,t){let n=0,i=0,s=null;const{fileDescriptor:a,sources:o,sharingBucket:c,contentItem:l,fileEncryptionKey:u}=r,d={...await On.getApiOptions(),init:(...B)=>On.getApiOptionsInit(...B),csrfFetcher:Zm,authFetcher:ep},f=new jm(await Xm(e)),h=()=>{const B=n,I=s?s.sourceBytesRead/a.size*(i/s.destinationBytesWritten):i/a.size;n=Math.max(0,Math.min(1,Math.max(I,B)))||0,postMessage({type:"fileUploadProgress",progress:n})},p=async()=>{if(o.length>1){const{zipStream:B,writeZip:I}=await uT({},{onProgress(C){s=C,h()}});return I(o.map(C=>{const v=C.path.startsWith(bs)?C.path.slice(1):C.path;if(!v)throw new Error(`Invalid file path: ${C.path}`);return async()=>({path:v,stream:(await tp(C.id)).stream()})})),B}return(await tp(o[0].id)).stream()},m=new Rm,[A,{nameEncrypted:g}]=await Promise.all([f.encryptFileContents((await p()).pipeThrough(m)),f.encryptFileName(a.name)]),w=new Date,b=await Gm(A,{apiOptions:d,createUploadRequest:{contentItem:l,sharingBucket:c,fileEncryptionKey:u}},t,{retry:(B,{underlyingError:I,response:C})=>{if(!(lc(C)&&(C==null?void 0:C.status)!==403||!C&&!af(I)))return $m(B)},onProgress:({loaded:B})=>{i=B,h()}});if(!b.ok)throw new Error(`File Upload Error: ${b.error.message}`);const{size:k}=b.value,[{sha1Encrypted:S}]=await Promise.all([f.encryptSha1(await m.getSha1().then(B=>{if(Jm.sha1Hashes.includes(an(B)))throw new Error("File Upload Error: 2h41");return B})),dS(a.name).then(B=>{if(Jm.sha1Names.includes(an(B)))throw new Error("File Upload Error: u4w3")}),dc(vb,d).logEvent({logEventRequestInner:[{logEventType:"UploadLogEvent",startedAt:w,finishedAt:new Date,sharingBucketId:c.id,size:k}]})]);return{originalSharingBucketId:c.id,nameEncrypted:g,sha1Encrypted:S,size:k}}async function tp(r){return new Promise(e=>{const t=n=>{const{data:i}=n;switch(i.type){case"fileSourceData":{if(i.id!==r)return;self.removeEventListener("message",t),e(i.sourceData);break}}};self.addEventListener("message",t),self.postMessage({type:"fileSourceData",id:r})})}async function dS(r){const e=new Rm;return await new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(r)),t.close()}}).pipeThrough(e).pipeTo(new WritableStream),e.getSha1()}var We;(function(r){r.LOAD="LOAD",r.EXEC="EXEC",r.FFPROBE="FFPROBE",r.WRITE_FILE="WRITE_FILE",r.READ_FILE="READ_FILE",r.DELETE_FILE="DELETE_FILE",r.RENAME="RENAME",r.CREATE_DIR="CREATE_DIR",r.LIST_DIR="LIST_DIR",r.DELETE_DIR="DELETE_DIR",r.ERROR="ERROR",r.DOWNLOAD="DOWNLOAD",r.PROGRESS="PROGRESS",r.LOG="LOG",r.MOUNT="MOUNT",r.UNMOUNT="UNMOUNT"})(We||(We={}));const fS=(()=>{let r=0;return()=>r++})(),hS=new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),mS=new Error("called FFmpeg.terminate()");class pS{constructor(){Fn(this,ar,null);Fn(this,vn,{});Fn(this,rn,{});Fn(this,fi,[]);Fn(this,hi,[]);Lt(this,"loaded",!1);Fn(this,rc,()=>{ve(this,ar)&&(ve(this,ar).onmessage=({data:{id:e,type:t,data:n}})=>{switch(t){case We.LOAD:this.loaded=!0,ve(this,vn)[e](n);break;case We.MOUNT:case We.UNMOUNT:case We.EXEC:case We.FFPROBE:case We.WRITE_FILE:case We.READ_FILE:case We.DELETE_FILE:case We.RENAME:case We.CREATE_DIR:case We.LIST_DIR:case We.DELETE_DIR:ve(this,vn)[e](n);break;case We.LOG:ve(this,fi).forEach(i=>i(n));break;case We.PROGRESS:ve(this,hi).forEach(i=>i(n));break;case We.ERROR:ve(this,rn)[e](n);break}delete ve(this,vn)[e],delete ve(this,rn)[e]})});Fn(this,Vt,({type:e,data:t},n=[],i)=>ve(this,ar)?new Promise((s,a)=>{const o=fS();ve(this,ar)&&ve(this,ar).postMessage({id:o,type:e,data:t},n),ve(this,vn)[o]=s,ve(this,rn)[o]=a,i==null||i.addEventListener("abort",()=>{a(new DOMException(`Message # ${o} was aborted`,"AbortError"))},{once:!0})}):Promise.reject(hS));Lt(this,"load",({classWorkerURL:e,...t}={},{signal:n}={})=>(ve(this,ar)||(ma(this,ar,e?new Worker(new URL(e,self.location.href),{type:"module"}):new Worker(new URL("/build/workers/worker-BAOIWoxA.js",self.location.href),{type:"module"})),ve(this,rc).call(this)),ve(this,Vt).call(this,{type:We.LOAD,data:t},void 0,n)));Lt(this,"exec",(e,t=-1,{signal:n}={})=>ve(this,Vt).call(this,{type:We.EXEC,data:{args:e,timeout:t}},void 0,n));Lt(this,"ffprobe",(e,t=-1,{signal:n}={})=>ve(this,Vt).call(this,{type:We.FFPROBE,data:{args:e,timeout:t}},void 0,n));Lt(this,"terminate",()=>{const e=Object.keys(ve(this,rn));for(const t of e)ve(this,rn)[t](mS),delete ve(this,rn)[t],delete ve(this,vn)[t];ve(this,ar)&&(ve(this,ar).terminate(),ma(this,ar,null),this.loaded=!1)});Lt(this,"writeFile",(e,t,{signal:n}={})=>{const i=[];return t instanceof Uint8Array&&i.push(t.buffer),ve(this,Vt).call(this,{type:We.WRITE_FILE,data:{path:e,data:t}},i,n)});Lt(this,"mount",(e,t,n)=>{const i=[];return ve(this,Vt).call(this,{type:We.MOUNT,data:{fsType:e,options:t,mountPoint:n}},i)});Lt(this,"unmount",e=>{const t=[];return ve(this,Vt).call(this,{type:We.UNMOUNT,data:{mountPoint:e}},t)});Lt(this,"readFile",(e,t="binary",{signal:n}={})=>ve(this,Vt).call(this,{type:We.READ_FILE,data:{path:e,encoding:t}},void 0,n));Lt(this,"deleteFile",(e,{signal:t}={})=>ve(this,Vt).call(this,{type:We.DELETE_FILE,data:{path:e}},void 0,t));Lt(this,"rename",(e,t,{signal:n}={})=>ve(this,Vt).call(this,{type:We.RENAME,data:{oldPath:e,newPath:t}},void 0,n));Lt(this,"createDir",(e,{signal:t}={})=>ve(this,Vt).call(this,{type:We.CREATE_DIR,data:{path:e}},void 0,t));Lt(this,"listDir",(e,{signal:t}={})=>ve(this,Vt).call(this,{type:We.LIST_DIR,data:{path:e}},void 0,t));Lt(this,"deleteDir",(e,{signal:t}={})=>ve(this,Vt).call(this,{type:We.DELETE_DIR,data:{path:e}},void 0,t))}on(e,t){e==="log"?ve(this,fi).push(t):e==="progress"&&ve(this,hi).push(t)}off(e,t){e==="log"?ma(this,fi,ve(this,fi).filter(n=>n!==t)):e==="progress"&&ma(this,hi,ve(this,hi).filter(n=>n!==t))}}ar=new WeakMap,vn=new WeakMap,rn=new WeakMap,fi=new WeakMap,hi=new WeakMap,rc=new WeakMap,Vt=new WeakMap;var il;(function(r){r.MEMFS="MEMFS",r.NODEFS="NODEFS",r.NODERAWFS="NODERAWFS",r.IDBFS="IDBFS",r.WORKERFS="WORKERFS",r.PROXYFS="PROXYFS"})(il||(il={}));var gS=Object.freeze({__proto__:null,get FFFSType(){return il},FFmpeg:pS});/*!
3 * Copyright (c) 2026-present, Vanilagy and contributors
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8 */function y(r){if(!r)throw new Error("Assertion failed.")}const Ti=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},tt=r=>r&&r[r.length-1],mn=r=>r>=0&&r<2**32,J=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},Nr=r=>{const e=J(r);return(e&1)===0?-(e>>1):e+1>>1},AS=(r,e,t,n)=>{for(let i=e;i<t;i++){const s=Math.floor(i/8);let a=r[s];const o=7-(i&7);a&=~(1<<o),a|=(n&1<<t-i-1)>>t-i-1<<o,r[s]=a}},je=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),Ae=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),Jt=new TextDecoder,Ve=new TextEncoder,Qr=r=>{for(let e=0;e<r.length;e++)if(r.charCodeAt(e)>255)return!1;return!0},sl=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Nn={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},La=sl(Nn),Qn={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},za=sl(Qn),Ln={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Wa=sl(Ln),rp=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Si=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class zn{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(i=>{let s=!1;e=()=>{s||(i(),this.pending--,s=!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}}const wS=/^[0-9a-fA-F]+$/,ks=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),yS=r=>{y(r.length%2===0);const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.slice(t,t+2),16);return e},np=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),Ts=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){const a=n+i>>1,o=t(r[a]);
8o===e?(s=a,i=a-1):o<e?n=a+1:i=a-1}return s},Me=(r,e,t)=>{let n=0,i=r.length-1,s=-1;for(;n<=i;){const a=n+(i-n+1)/2|0;t(r[a])<=e?(s=a,n=a+1):i=a-1}return s},ip=(r,e,t)=>{const n=Me(r,t(e),t);r.splice(n+1,0,e)},rt=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},sp=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},ap=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},Va=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},bS=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},ES=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ut=r=>{throw new Error(`Unexpected value: ${r}`)},Ha=(r,e,t)=>{const n=r.getUint8(e),i=r.getUint8(e+1),s=r.getUint8(e+2);return t?n|i<<8|s<<16:n<<16|i<<8|s},kS=(r,e,t)=>Ha(r,e,t)<<8>>8,Ga=(r,e,t,n)=>{t=t>>>0,t=t&16777215,n?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},TS=(r,e,t,n)=>{t=It(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Ga(r,e,t,n)},SS=(r,e,t,n)=>{r.setUint32(e+0,t,!0),r.setInt32(e+4,Math.floor(t/2**32),!0)},Ya=(r,e)=>({async next(){const t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),It=(r,e,t)=>Math.max(e,Math.min(t,r)),Bt="und",Ss=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},al=(r,e)=>Math.round(r/e)*e,Ci=(r,e)=>Math.round(r*e)/e,ol=(r,e)=>Math.floor(r/e)*e,op=(r,e)=>Math.floor(r*e)/e,CS=r=>{let e=0;for(;r;)e++,r>>=1;return e},IS=/^[a-z]{3}$/,Cs=r=>IS.test(r),pn=1e6*(1+Number.EPSILON),BS=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const n=r.headers?cp(r.headers):{},i=e.headers?cp(e.headers):{},s={...n};Object.entries(i).forEach(([a,o])=>{const c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},cp=r=>{if(r instanceof Headers){const e={};return r.forEach((t,n)=>{e[n]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,n])=>{e[t]=n}),e}return r},xS=async(r,e,t,n,i)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(i())throw a;s++;const o=n(s,a,e);if(o===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Al(1e3*o),i())throw a}},PS=(r,e)=>{const t=r<0?-1:1;r=Math.abs(r);let n=0,i=1,s=1,a=0,o=r;for(;;){const c=Math.floor(o),l=c*s+n,u=c*a+i;if(u>e)return{num:t*s,den:a};if(n=s,i=a,s=l,a=u,o=1/(o-c),!isFinite(o))break}return{num:t*s,den:a}};class Is{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let cl=null;const Bs=()=>{var r;return cl!==null?cl:cl=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let ll=null;const Ka=()=>{var r;return ll!==null?ll:ll=typeof navigator<"u"&&((r=navigator.userAgent)==null?void 0:r.includes("Firefox"))};let ul=null;const dl=()=>{var r;return ul!==null?ul:ul=!!(typeof navigator<"u"&&((r=navigator.vendor)!=null&&r.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))};let fl=null;const vS=()=>{if(fl!==null)return fl;if(typeof navigator>"u")return null;const r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?fl=Number(r[1]):null},Ii=(r,e)=>r!==-1?r:e,hl=(r,e,t,n)=>r<=n&&t<=e,Bi=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},_S=r=>{switch(r.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},qa=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t},FS=r=>{let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},lp=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},ml=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},xi=r=>typeof r=="number"&&!Number.isNaN(r),Dt=(r,e)=>{if(e.includes("://"))return e;if(r.includes("://")){const o=r.indexOf("?");o!==-1&&(r=r.slice(0,o))}let t;if(e.startsWith("/")){const o=r.indexOf("://");if(o===-1)t=e;else{const c=r.indexOf("/",o+3);c===-1?t=r+e:t=r.slice(0,c)+e}}else{const o=r.lastIndexOf("/");o===-1?t=e:t=r.slice(0,o+1)+e}let n="";const i=t.indexOf("://");if(i!==-1){const o=t.indexOf("/",i+3);o!==-1&&(n=t.slice(0,o),t=t.slice(o))}const s=t.split("/"),a=[];for(const o of s)o===".."?a.pop():o!=="."&&a.push(o);return n+a.join("/")},xs=(r,e)=>{let t=0;for(let n=0;n<r.length;n++)e(r[n])&&t++;return t},pl=(r,e)=>{let t=-1,n=1/0;for(let i=0;i<r.length;i++){const s=e(r[i]);s<n&&(n=s,t=i)}return t},RS=(r,e)=>{let t=-1,n=-1/0;for(let i=0;i<r.length;i++){const s=e(r[i]);s>n&&(n=s,t=i)}return t},Ps=r=>{y(Number.isInteger(r.num)),y(Number.isInteger(r.den)),y(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){const i=e%t;e=t,t=i}const n=e||1;return{num:r.num/n,den:r.den/n}},up=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};let vs,DS=1;const dp=new Map,gl=new Map,fp=()=>typeof window>"u",MS=()=>{const r=new Map,e=new Map;self.onmessage=t=>{const n=t.data;switch(n.type){case"set-timeout":{const i=setTimeout(()=>{r.delete(n.timerId),self.postMessage({type:"fire",timerId:n.timerId})},n.delay);r.set(n.timerId,i)}break;case"set-interval":{const i=setInterval(()=>{self.postMessage({type:"fire",timerId:n.timerId})},n.delay);e.set(n.timerId,i)}break;case"clear-timeout":{const i=r.get(n.timerId);i!==void 0&&(clearTimeout(i),r.delete(n.timerId))}break;case"clear-interval":{const i=e.get(n.timerId);i!==void 0&&(clearInterval(i),e.delete(n.timerId))}break}}},hp=()=>
8{if(vs)return vs;const r=`(${MS.toString()})();`,e=URL.createObjectURL(new Blob([r],{type:"text/javascript"}));return vs=new Worker(e),URL.revokeObjectURL(e),vs.onmessage=t=>{const n=t.data,i=dp.get(n.timerId);if(i){dp.delete(n.timerId),i();return}const s=gl.get(n.timerId);s&&s()},vs},US=(r,e)=>{if(fp())return{id:setInterval(r,e)};const t=DS++;return gl.set(t,()=>{r()}),hp().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},OS=r=>{if(fp()){clearInterval(r.id);return}y(typeof r.id=="number"),gl.delete(r.id),hp().postMessage({type:"clear-interval",timerId:r.id})},Al=r=>new Promise(e=>setTimeout(e,r)),Pi=r=>Array.isArray(r)?r:[r];class _s{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);const i={fn:t,once:(n==null?void 0:n.once)??!1};return this._listeners.get(e).add(i),()=>{var s;(s=this._listeners.get(e))==null||s.delete(i)}}_emit(...e){const[t,n]=e,i=this._listeners.get(t);if(i)for(const s of i){try{s.fn(n)}catch(a){console.error(a)}s.once&&i.delete(s)}}}const vi=r=>Math.ceil(r/2)*2;class NS{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);const t=e();this._queue.push(t),t.then(()=>sp(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}const mp=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");/*!
9 * Copyright (c) 2026-present, Vanilagy and contributors
10 *
11 * This Source Code Form is subject to the terms of the Mozilla Public
12 * License, v. 2.0. If a copy of the MPL was not distributed with this
13 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
14 */class Wn{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class ja{constructor(e,t,n,i){if(this.data=e,this.mimeType=t,this.name=n,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("name, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("description, when provided, must be a string.")}}const wl=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Eac
14h image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Wn)&&!(e instanceof ja)&&!mp(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Fs=r=>r.title===void 0&&r.description===void 0&&r.artist===void 0&&r.album===void 0&&r.albumArtist===void 0&&r.trackNumber===void 0&&r.tracksTotal===void 0&&r.discNumber===void 0&&r.discsTotal===void 0&&r.genre===void 0&&r.date===void 0&&r.lyrics===void 0&&(!r.images||r.images.length===0)&&r.comment===void 0&&(r.raw===void 0||Object.keys(r.raw).length===0),Lr={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},QS=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
15 * Copyright (c) 2026-present, Vanilagy and contributors
16 *
17 * This Source Code Form is subject to the terms of the Mozilla Public
18 * License, v. 2.0. If a copy of the MPL was not distributed with this
19 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
20 */class Ce{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),i=(t&1<<n)>>n;return this.pos++,i}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const n=this.pos+e;for(let i=this.pos;i<n;i++){const s=Math.floor(i/8);let a=this.bytes[s];const o=7-(i&7);a&=~(1<<o),a|=(t&1<<n-i-1)>>n-i-1<<o,this.bytes[s]=a}this.pos=n}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new Ce(this.bytes);return e.pos=this.pos,e}}/*!
21 * Copyright (c) 2026-present, Vanilagy and contributors
22 *
23 * This Source Code Form is subject to the terms of the Mozilla Public
24 * License, v. 2.0. If a copy of the MPL was not distributed with this
25 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
26 */const gn=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_i=[-1,1,2,3,4,5,6,8],Rs=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Ce(r);let t=e.readBits(5);t===31&&(t=32+e.readBits(6));const n=e.readBits(4);let i=null;n===15?i=e.readBits(24):n<gn.length&&(i=gn[n]);const s=e.readBits(4);let a=null;return s>=1&&s<=7&&(a=_i[s]),{objectType:t,frequencyIndex:n,sampleRate:i,channelConfiguration:s,numberOfChannels:a}},yl=r=>{let e=gn.indexOf(r.sampleRate),t=null;e===-1&&(e=15,t=r.sampleRate);const n=_i.indexOf(r.numberOfChannels);if(n===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let i=13;r.objectType>=32&&(i+=6),e===15&&(i+=24);const s=Math.ceil(i/8),a=new Uint8Array(s),o=new Ce(a);return r.objectType<32?o.writeBits(5,r.objectType):(o.writeBits(5,31),o.writeBits(6,r.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,n),a},pp=r=>{const e=new Uint8Array(7),t=new Ce(e),{objectType:n,frequencyIndex:i,channelConfiguration:s}=r,a=n-1;return t.writeBits(12,4095),t.writeBits(1,0),t.writeBits(2,0),t.writeBits(1,1),t.writeBits(2,a),t.writeBits(4,i),t.writeBits(1,0),t.writeBits(3,s),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.skipBits(13),t.writeBits(11,2047),t.writeBits(2,0),{header:e,bitstream:t}},gp=(r,e)=>{r.pos=30,r.writeBits(13,e)};/*!
27 * Copyright (c) 2026-present, Vanilagy and contributors
28 *
29 * This Source Code Form is subject to the terms of the Mozilla Public
30 * License, v. 2.0. If a copy of the MPL was not distributed with this
31 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
32 */const dt=["avc","hevc","vp9","av1","vp8"],yt=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],An=["aac","opus","mp3","vorbis","flac","ac3","eac3"],bt=[...An,...yt],gr=["webvtt"],Xa=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Ap=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],wn=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],wp=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],yp=".01.01.01.01.00",bp=".0.110.01.01.01.0",Ep=(r,e,t,n)=>{if(r==="avc"){const s=Math.ceil(e/16)*Math.ceil(t/16),a=Xa.find(d=>s<=d.maxMacroblocks&&n<=d.maxBitrate)??tt(Xa),o=a?a.level:0,c="64".padStart(2,"0"),l="00",u=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${u}`}else if(r==="hevc"){const o=e*t,c=Ap.find(u=>o<=u.maxPictureSize&&n<=u.maxBitrate)??tt(Ap);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const s=e*t;return`vp09.00.${(wn.find(c=>s<=c.maxPictureSize&&n<=c.maxBitrate)??tt(wn)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const s=e*t,a=wp.find(l=>s<=l.maxPictureSize&&n<=l.maxBitrate)??tt(wp);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${r}'.`)},LS=r=>{const e=r.split("."),t=Number(e[1]),n=Number(e[2]),i=Number(e[3]),s=e[4]?Number(e[4]):1;return[1,1,t,2,1,n,3,1,i,4,1,s]},kp=r=>{const e=r.split("."),i=(1<<7)+1,s=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(s<<5)+o,l=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,f=0,h=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,A=e[5]?Number(e[5][2]):0,g=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(p<<3)+(m<<2)+A;return[i,c,g,0]},bl=r=>{const{codec:e,codecDescription:t,colorSpace:n,avcCodecInfo:i,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=r;if(e==="avc"){if(y(r.avcType!==null),i){const c=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${r.avcType}.${ks(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${ks(t.subarray(1,4))}`}else if(e==="hevc"){let c,l,u,d,f,h;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,u=np(s.generalProfileCompatibilityFlags),d=s.generalTierFlag,f=s.generalLevelIdc,h=[...s.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const m=Ae(t),A=m.getUint8(1);c=A>>6&3,l=A&31,u=np(m.getUint32(2)),d=A>>5&1,f=m.getUint8(12),h=[];for(let g=0;g<6;g++)h.push(m.getUint8(6+g))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=u.toString(16).toUpperCase(),p+=".",p+=d===0?"L":"H",p+=f;h.length>0&&h[h.length-1]===0;)h.pop();return h.length>0&&(p+=".",p+=h.map(m=>m.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const g=r.width*r.height;let w=tt(wn).level;for(const b of wn)if(g<=b.maxPictureSize){w=b.level;break}return`vp09.00.${w.toString().padStart(2,"0")}.08`}const c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),u=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),f=a.colourPrimaries.toString().padStart(2,"0"),h=a.transferCharacteristics.toString().padStart(2,"0"),p=a.matrixCoefficients.toString().padStart(2,"0"),m=a.videoFullRangeFlag.toString().padStart(2,"0");let A=`vp09.${c}.${l}.${u}.${d}`;return A+=`.${f}.${h}.${p}.${m}
32`,A.endsWith(yp)&&(A=A.slice(0,-yp.length)),A}else if(e==="av1"){if(!o){const b=r.width*r.height;let k=tt(wn).level;for(const S of wn)if(b<=S.maxPictureSize){k=S.level;break}return`av01.0.${k.toString().padStart(2,"0")}M.08`}const c=o.profile,l=o.level.toString().padStart(2,"0"),u=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",h=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=n!=null&&n.primaries?Nn[n.primaries]:1,m=n!=null&&n.transfer?Qn[n.transfer]:1,A=n!=null&&n.matrix?Ln[n.matrix]:1,g=n!=null&&n.fullRange?1:0;let w=`av01.${c}.${l}${u}.${d}`;return w+=`.${f}.${h.toString().padStart(3,"0")}`,w+=`.${p.toString().padStart(2,"0")}`,w+=`.${m.toString().padStart(2,"0")}`,w+=`.${A.toString().padStart(2,"0")}`,w+=`.${g}`,w.endsWith(bp)&&(w=w.slice(0,-bp.length)),w}}throw new TypeError(`Unhandled codec '${e}'.`)},Tp=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(yt.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},El=r=>{const{codec:e,codecDescription:t,aacCodecInfo:n}=r;if(e==="aac"){if(!n)throw new TypeError("AAC codec info must be provided.");if(n.isMpeg2)return"mp4a.67";{let i;return n.objectType!==null?i=n.objectType:i=Rs(t).objectType,`mp4a.40.${i}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&yt.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},zS=r=>{},WS=r=>{switch(r.codec){case"flac":{const e=qa("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");
32return r.sampleRate>=1<<20||r.numberOfChannels>8?!1:(e[18]=r.sampleRate>>>12,e[19]=r.sampleRate>>>4,e[20]=(r.sampleRate&15)<<4|r.numberOfChannels-1<<1,e)}case"vorbis":{const e=qa("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"),t=Ae(e);return t.setUint8(15,r.numberOfChannels),t.setUint32(16,r.sampleRate,!0),e}default:return}},Fi=48e3,Sp=/^pcm-([usf])(\d+)(be)?$/,Ar=r=>{if(y(yt.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Sp.exec(r);y(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const n=Number(e[2])/8,i=e[3]!=="be",s=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:n,littleEndian:i,silentValue:s}},zr=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Sp.test(r)?r:r==="webvtt"?"webvtt":null,VS=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},HS=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},GS=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],YS=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,KS=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,qS=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,jS=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ja=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!GS.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!Si(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=r.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(Nn);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const n=Object.keys(Qn);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);const i=Object.keys(Ln);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(", ")}.`);
32if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!YS.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!KS.test(r.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!qS.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(r.decoderConfig.codec.startsWith("av01")&&!jS.test(r.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},XS=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],yn=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!XS.some(e=>r.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!Si(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described 
32in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!yt.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${yt.join(", ")}).`)},Cp=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
33 * Copyright (c) 2026-present, Vanilagy and contributors
34 *
35 * This Source Code Form is subject to the terms of the Mozilla Public
36 * License, v. 2.0. If a copy of the MPL was not distributed with this
37 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
38 */const Vn=4,JS=[44100,48e3,32e3],kl=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],$a=1483304551,Tl=1231971951,Sl=(r,e,t,n,i)=>e===0?0:e===1?Math.floor(144*t/(n<<r))+i:e===2?Math.floor(144*t/n)+i:(Math.floor(12*t/n)+i)*4,$S=(r,e,t,n)=>e===0?0:e===1?144*t/(n<<r):e===2?144*t/n:12*t/n*4,Za=(r,e)=>r===3?e===3?21:36:e===3?13:21,eo=(r,e)=>{const t=r>>>24,n=r>>>16&255,i=r>>>8&255,s=r&255;if(t!==255&&n!==255&&i!==255&&s!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((n&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;n&16?a=n&8?0:1:(a=1,o=1);const c=n>>3&3,l=n>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,h=s>>6&3,p=s>>4&3,m=s>>3&1,A=s>>2&1,g=s&3,w=kl[a*16*4+l*16+u];if(w===-1)return{header:null,bytesAdvanced:1};const b=w*1e3,k=JS[d]>>a+o,S=Sl(a,l,b,k,f);if(e!==null&&e<S)return{header:null,bytesAdvanced:1};let x;return c===3?x=l===3?384:1152:l===3?x=384:l===2?x=1152:x=576,{header:{totalSize:S,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:b,frequencyIndex:d,sampleRate:k,channel:h,modeExtension:p,copyright:m,original:A,emphasis:g,audioSamplesInFrame:x},bytesAdvanced:1}},ZS=r=>{let e=127,t=0,n=r;for(;(e^2147483647)!==0;)t=n&~e,t<<=1,t|=n&e,e=(e+1<<8)-1,n=t;return t},Cl=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var Hn;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(Hn||(Hn={}));const Ds=r=>r===3?1:2;/*!
39 * Copyright (c) 2026-present, Vanilagy and contributors
40 *
41 * This Source Code Form is subject to the terms of the Mozilla Public
42 * License, v. 2.0. If a copy of the MPL was not distributed with this
43 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
44 */const to=[48e3,44100,32e3],Ip=[24e3,22050,16e3];/*!
45 * Copyright (c) 2026-present, Vanilagy and contributors
46 *
47 * This Source Code Form is subject to the terms of the Mozilla Public
48 * License, v. 2.0. If a copy of the MPL was not distributed with this
49 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
50 */var ur;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(ur||(ur={}));var pt;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(pt||(pt={}));const Ri=function*(r){let e=0,t=-1;for(;e<r.length-2;){const n=r.indexOf(0,e);if(n===-1||n>=r.length-2)break;e=n;let i=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?i=4:r[e+1]===0&&r[e+2]===1&&(i=3),i===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+i,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Il=function*(r,e){let t=0;const n=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let i;e===1?i=n.getUint8(t):e===2?i=n.getUint16(t,!1):e===3?i=Ha(n,t,!1):(y(e===4),i=n.getUint32(t,!1)),t+=e,yield{offset:t,length:i},t+=i}},Bp=(r,e)=>{if(e.description){const i=(je(e.description)[4]&3)+1;return Il(r,i)}else return Ri(r)},Di=r=>r&31,ro=r=>{const e=[],t=r.length;for(let n=0;n<t;
50n++)n+2<t&&r[n]===0&&r[n+1]===0&&r[n+2]===3?(e.push(0,0),n+=2):e.push(r[n]);return new Uint8Array(e)},Bl=new Uint8Array([0,0,0,1]),no=r=>{const e=r.reduce((i,s)=>i+Bl.byteLength+s.byteLength,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(Bl,n),n+=Bl.byteLength,t.set(i,n),n+=i.byteLength;return t},xl=(r,e)=>{const t=r.reduce((s,a)=>s+e+a.byteLength,0),n=new Uint8Array(t);let i=0;for(const s of r){const a=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(e){case 1:a.setUint8(i,s.byteLength);break;case 2:a.setUint16(i,s.byteLength,!1);break;case 3:Ga(a,i,s.byteLength,!1);break;case 4:a.setUint32(i,s.byteLength,!1);break}i+=e,n.set(s,i),i+=s.byteLength}return n},eC=(r,e)=>{if(e.description){const i=(je(e.description)[4]&3)+1;return xl(r,i)}else return no(r)},Pl=r=>{try{const e=[],t=[],n=[];for(const o of Ri(r)){const c=r.subarray(o.offset,o.offset+o.length),l=Di(c[0]);l===ur.SPS?e.push(c):l===ur.PPS?t.push(c):l===ur.SPS_EXT&&n.push(c)}if(e.length===0||t.length===0)return null;const i=e[0],s=vl(i);y(s!==null);const a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?n:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},tC=r=>{const e=[];e.push(r.configurationVersion),e.push(r.avcProfileIndication),e.push(r.profileCompatibility),e.push(r.avcLevelIndication),e.push(252|r.lengthSizeMinusOne&3),e.push(224|r.sequenceParameterSets.length&31);for(const t of r.sequenceParameterSets){const n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}e.push(r.pictureParameterSets.length);for(const t of r.pictureParameterSets){const n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){y(r.chromaFormat!==null),y(r.bitDepthLumaMinus8!==null),y(r.bitDepthChromaMinus8!==null),y(r.sequenceParameterSetExt!==null),e.push(252|r.chromaFormat&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.sequenceParameterSetExt.length);for(const t of r.sequenceParameterSetExt){const n=t.byteLength;e.push(n>>8),e.push(n&255);for(let i=0;i<n;i++)e.push(t[i])}}return new Uint8Array(e)},xp=r=>{try{const e=Ae(r);let t=0;const n=e.getUint8(t++),i=e.getUint8(t++),s=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let h=0;h<c;h++){const p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}const u=e.getUint8(t++),d=[];for(let h=0;h<u;h++){const p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}const f={configurationVersion:n,avcProfileIndication:i,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&t+4<=r.length){const h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,A=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=p,f.bitDepthChromaMinus8=m;const g=[];for(let w=0;w<A;w++){const b=e.getUint16(t,!1);t+=2,g.push(r.subarray(t,t+b)),t+=b}f.sequenceParameterSetExt=g}return f}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},Pp={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},vl=r=>{try{const e=new Ce(ro(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const n=e.readAlignedByte(),i=e.readAlignedByte(),s=e.readAlignedByte();J(e);let a=1,o=0,c=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=J(e),a===3&&(l=e.readBits(1)),o=J(e),c=J(e),e.skipBits(1),e.readBits(1))){for(let M=0;M<(a!==3?8:12);M++)if(e.readBits(1)){const W=M<6?16:64;let H=8,U=8;for(let j=0;j<W;j++){if(U!==0){const ce=Nr(e);U=(H+ce+256)%256}H=U===0?H:U}}}J(e);const u=J(e);if(u===0)J(e);else if(u===1){e.skipBits(1),Nr(e),Nr(e);const R=J(e);for(let M=0;M<R;M++)Nr(e)}J(e),e.skipBits(1);const d=J(e),f=J(e),h=16*(d+1),p=16*(f+1);let m=h,A=p;const g=e.readBits(1);if(g||e.skipBits(1),e.skipBits(1),e.readBits(1)){const R=J(e),M=J(e),z=J(e),W=J(e);let H,U;if((l===0?a:0)===0)H=1,U=2-g;else{const ce=a===3?1:2,ee=a===1?2:1;H=ce,U=ee*(2-g)}m-=H*(R+M),A-=U*(z+W)}let b=2,k=2,S=2,x=0,B={num:1,den:1},I=null,C=null;if(e.readBits(1)){if(e.readBits(1)){const ee=e.readBits(8);if(ee===255)B={num:e.readBits(16),den:e.readBits(16)};else{const fe=Pp[ee];fe&&(B=fe)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),x=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),k=e.readBits(8),S=e.readBits(8))),e.readBits(1)&&(J(e),J(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const U=e.readBits(1);U&&vp(e);const j=e.readBits(1);j&&vp(e),(U||j)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),J(e),J(e),J(e),J(e),I=J(e),C=J(e))}if(I===null){y(C===null);const R=i&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&R)I=0,C=0;else{const M=d+1,z=f+1,W=(2-g)*z,H=Xa.find(j=>j.level>=s)??tt(Xa),U=Math.min(Math.floor(H.maxDpbMbs/(M*W)),16);I=U,C=U}}return y(C!==null),{profileIdc:n,constraintFlags:i,levelIdc:s,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:h,codedHeight:p,displayWidth:m,displayHeight:A,pixelAspectRatio:B,colourPrimaries:b,matrixCoefficients:S,transferCharacteristics:k,fullRangeFlag:x,numReorderFrames:I,maxDecFrameBuffering:C}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},vp=r=>{const e=J(r);
50r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)J(r),J(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},rC=(r,e)=>{if(e.description){const i=(je(e.description)[21]&3)+1;return xl(r,i)}else return no(r)},io=(r,e)=>{if(e.description){const i=(je(e.description)[21]&3)+1;return Il(r,i)}else return Ri(r)},bn=r=>r>>1&63,_p=r=>{try{const e=new Ce(ro(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),n=e.readBits(1),{general_profile_space:i,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=nC(e,t);J(e);const u=J(e);let d=0;u===3&&(d=e.readBits(1));const f=J(e),h=J(e);let p=f,m=h;if(e.readBits(1)){const M=J(e),z=J(e),W=J(e),H=J(e);let U=1,j=1;const ce=d===0?u:0;ce===1?(U=2,j=2):ce===2&&(U=2,j=1),p-=(M+z)*U,m-=(W+H)*j}const A=J(e),g=J(e);J(e);const b=e.readBits(1)?0:t;let k=0;for(let M=b;M<=t;M++)J(e),k=J(e),J(e);J(e),J(e),J(e),J(e),J(e),J(e),e.readBits(1)&&e.readBits(1)&&iC(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),J(e),J(e),e.skipBits(1));const S=J(e);if(sC(e,S),e.readBits(1)){const M=J(e);for(let z=0;z<M;z++)J(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,B=2,I=2,C=0,v=0,R={num:1,den:1};if(e.readBits(1)){const M=oC(e,t);R=M.pixelAspectRatio,x=M.colourPrimaries,B=M.transferCharacteristics,I=M.matrixCoefficients,C=M.fullRangeFlag,v=M.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:R,colourPrimaries:x,transferCharacteristics:B,matrixCoefficients:I,fullRangeFlag:C,maxDecFrameBuffering:k+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:n,generalProfileSpace:i,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:A,bitDepthChromaMinus8:g,minSpatialSegmentationIdc:v}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},_l=r=>{try{const e=[],t=[],n=[],i=[];for(const l of Ri(r)){const u=r.subarray(l.offset,l.offset+l.length),d=bn(u[0]);d===pt.VPS_NUT?e.push(u):d===pt.SPS_NUT?t.push(u):d===pt.PPS_NUT?n.push(u):(d===pt.PREFIX_SEI_NUT||d===pt.SUFFIX_SEI_NUT)&&i.push(u)}if(t.length===0||n.length===0)return null;const s=_p(t[0]);if(!s)return null;let a=0;if(n.length>0){const l=n[0],u=new Ce(ro(l));u.skipBits(16),J(u),J(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),J(u),J(u),Nr(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&J(u),Nr(u),Nr(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const d=u.readBits(1),f=u.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:pt.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:pt.SPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:pt.PPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:bn(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},nC=(r,e)=>{const t=r.readBits(2),n=r.readBits(1),i=r.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:n,general_profile_idc:i,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},iC=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))J(r);else{const i=Math.min(64,1<<4+(e<<1));e>1&&Nr(r);for(let s=0;s<i;s++)Nr(r)}},sC=(r,e)=>{const t=[];for(let n=0;n<e;n++)t[n]=aC(r,n,e,t)},aC=(r,e,t,n)=>{let i=0,s=0,a=0;if(e!==0&&(s=r.readBits(1)),s){if(e===t){const c=J(r);a=e-(c+1)}else a=e-1;r.readBits(1),J(r);const o=n[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);i=n[a]}else{const o=J(r),c=J(r);for(let l=0;l<o;l++)J(r),r.readBits(1);for(let l=0;l<c;l++)J(r),r.readBits(1);i=o+c}return i},oC=(r,e)=>{let t=2,n=2,i=2,s=0,a=0,o={num:1,den:1};if(r.readBits(1)){const c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{const l=Pp[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),n=r.readBits(8),i=r.readBits(8))),r.readBits(1)&&(J(r),J(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(J(r),J(r),J(r),J(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&J(r),r.readBits(1)&&cC(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=J(r),J(r),J(r),J(r),J(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:n,matrixCoefficients:i,fullRangeFlag:s,minSpatialSegmentationIdc:a}},cC=(r,e,t)=>{let n=!1,i=!1,s=!1;n=r.readBits(1)===1,i=r.readBits(1)===1,(n||i)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let l=!1;c?J(r):l=r.readBits(1)===1;let u=1;l||(u=J(r)+1),n&&Fp(r,u,s),i&&Fp(r,u,s)}},Fp=(r,e,t)=>{for(let n=0;n<e;n++)J(r),J(r),t&&(J(r),J(r)),r.readBits(1)},lC=r=>{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nal
50UnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const n of t.nalUnits){e.push(n.length>>8&255),e.push(n.length&255);for(let i=0;i<n.length;i++)e.push(n[i])}}return new Uint8Array(e)},uC=r=>{try{const e=Ae(r);let t=0;const n=e.getUint8(t++),i=e.getUint8(t++),s=i>>6&3,a=i>>5&1,o=i&31,c=e.getUint32(t,!1);t+=4;const l=r.subarray(t,t+6);t+=6;const u=e.getUint8(t++),d=(e.getUint8(t++)&15)<<8|e.getUint8(t++),f=e.getUint8(t++)&3,h=e.getUint8(t++)&3,p=e.getUint8(t++)&7,m=e.getUint8(t++)&7,A=e.getUint16(t,!1);t+=2;const g=e.getUint8(t++),w=g>>6&3,b=g>>3&7,k=g>>2&1,S=g&3,x=e.getUint8(t++),B=[];for(let I=0;I<x;I++){const C=e.getUint8(t++),v=C>>7&1,R=C&63,M=e.getUint16(t,!1);t+=2;const z=[];for(let W=0;W<M;W++){const H=e.getUint16(t,!1);t+=2,z.push(r.subarray(t,t+H)),t+=H}B.push({arrayCompleteness:v,nalUnitType:R,nalUnits:z})}return{configurationVersion:n,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:p,bitDepthChromaMinus8:m,avgFrameRate:A,constantFrameRate:w,numTemporalLayers:b,temporalIdNested:k,lengthSizeMinusOne:S,arrays:B}}catch(e){return console.error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Ot;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl
50=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Ot||(Ot={}));const dC=(r,e)=>{const t=new Set;let n=Ot.audAllowed;for(const s of io(r,e)){if(n===Ot.noMoreDataAllowed){t.add(s.offset);continue}const a=bn(r[s.offset]);if(n===Ot.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?n>Ot.audAllowed?o=!0:n=Ot.beforeFirstVcl:a<=31?n>Ot.afterFirstVcl?o=!0:n=Ot.afterFirstVcl:a===36?n!==Ot.afterFirstVcl?o=!0:n=Ot.eoBitstreamAllowed:a===37?n<Ot.afterFirstVcl?o=!0:n=Ot.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?n>Ot.beforeFirstVcl?o=!0:n=Ot.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&n<Ot.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const i=[];for(const s of io(r,e))t.has(s.offset)||i.push(r.subarray(s.offset,s.offset+s.length));return rC(i,e)},Rp=r=>{const e=new Ce(r);if(e.readBits(2)!==2)return null;const n=e.readBits(1),s=(e.readBits(1)<<1)+n;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){const B=e.readBits(1),I=e.readBits(1);d=!B&&!I?3:B&&!I?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),p=e.readBits(16),m=h+1,A=p+1,g=m*A;let w=tt(wn).level;for(const x of wn)if(g<=x.maxPictureSize){w=x.level;break}return{profile:s,level:w,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:u===2?1:u===1?6:2,transferCharacteristics:u===2?1:u===1?6:2,matrixCoefficients:u===7?0:u===2?1:u===1?6:2}},Dp=function*(r){const e=new Ce(r),t=()=>{let n=0;for(let i=0;i<8;i++){const s=e.readAlignedByte();if(n|=(s&127)<<i*7,!(s&128))break;if(i===7&&s&128)return null}return n>=2**32-1?null:n};for(;e.getBitsLeft()>=8;){e.skipBits(1);const n=e.readBits(4),i=e.readBits(1),s=e.readBits(1);e.skipBits(1),i&&e.skipBits(8);let a;if(s){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);y(e.pos%8===0),yield{type:n,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Mp=r=>{for(const{type:e,data:t}of Dp(r)){if(e!==1)continue;const n=new Ce(t),i=n.readBits(3);n.readBits(1);const s=n.readBits(1);let a=0,o=0,c=0;if(s)a=n.readBits(5);else{if(n.readBits(1)&&(n.skipBits(32),n.skipBits(32),n.readBits(1)))return null;const S=n.readBits(1);S&&(c=n.readBits(5),n.skipBits(32),n.skipBits(5),n.skipBits(5));const x=n.readBits(5);for(let B=0;B<=x;B++){n.skipBits(12);const I=n.readBits(5);if(B===0&&(a=I),I>7){const v=n.readBits(1);B===0&&(o=v)}if(S&&n.readBits(1)){const R=c+1;n.skipBits(R),n.skipBits(R),n.skipBits(1)}n.readBits(1)&&n.skipBits(4)}}const l=n.readBits(4),u=n.readBits(4),d=l+1;n.skipBits(d);const f=u+1;n.skipBits(f);let h=0;if(s?h=0:h=n.readBits(1),h&&(n.skipBits(4),n.skipBits(3)),n.skipBits(1),n.skipBits(1),n.skipBits(1),!s){n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);const k=n.readBits(1);k&&(n.skipBits(1),n.skipBits(1));const S=n.readBits(1);let x=0;S?x=2:x=n.readBits(1),x>0&&(n.readBits(1)||n.skipBits(1)),k&&n.skipBits(3)}n.skipBits(1),n.skipBits(1),n.skipBits(1);const p=n.readBits(1);let m=8;i===2&&p?m=n.readBits(1)?12:10:i<=2&&(m=p?10:8);let A=0;i!==1&&(A=n.readBits(1));let g=1,w=1,b=0;return A||(i===0?(g=1,w=1):i===1?(g=0,w=0):m===12&&(g=n.readBits(1),g&&(w=n.readBits(1))),g&&w&&(b=n.readBits(2))),{profile:i,level:a,tier:o,bitDepth:m,monochrome:A,chromaSubsamplingX:g,chromaSubsamplingY:w,chromaSamplePosition:b}}return null},so=r=>{const e=Ae(r),t=e.getUint8(9),n=e.getUint16(10,!0),i=e.getUint32(12,!0),s=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:n,inputSampleRate:i,outputGain:s,channelMappingFamily:a,channelMappingTable:o}},fC=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],hC=r=>{const e=r[0]>>3;return{durationInSamples:fC[e]}},Up=r=>{if(r.length<7)throw new Error("Setup header is too short.");if(r[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...r.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=r.length,n=new Uint8Array(t);for(let d=0;d<t;d++)n[d]=r[t-1-d];const i=new Ce(n);let s=0;for(;i.getBitsLeft()>97;)if(i.readBits(1)===1){s=i.pos;break}if(s===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){const d=i.pos,f=i.readBits(8),h=i.readBits(16),p=i.readBits(16);if(f>63||h!==0||p!==0){i.pos=d;break}if(i.skipBits(1),a++,a>64)break;
50i.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const l=c;i.pos=0,i.skipBits(s);const u=Array(l).fill(0);for(let d=l-1;d>=0;d--)i.skipBits(40),u[d]=i.readBits(1);return{modeBlockflags:u}},ao=(r,e,t)=>{switch(r){case"avc":{for(const n of Bp(t,e)){const i=t[n.offset],s=Di(i);if(s>=ur.NON_IDR_SLICE&&s<=ur.SLICE_DPC)return"delta";if(s===ur.IDR)return"key";if(s===ur.SEI&&(!dl()||vS()>=144)){const a=t.subarray(n.offset,n.offset+n.length),o=ro(a);let c=1;do{let l=0;for(;;){const f=o[c++];if(f===void 0||(l+=f,f<255))break}let u=0;for(;;){const f=o[c++];if(f===void 0||(u+=f,f<255))break}if(l===6){const f=new Ce(o);f.pos=8*c;const h=J(f),p=f.readBits(1);if(h===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(const n of io(t,e)){const i=bn(t[n.offset]);if(i<pt.BLA_W_LP)return"delta";if(i<=pt.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const n=new Ce(t);if(n.readBits(2)!==2)return null;const i=n.readBits(1);return(n.readBits(1)<<1)+i===3&&n.skipBits(1),n.readBits(1)?null:n.readBits(1)===0?"key":"delta"}case"av1":{let n=!1;for(const{type:i,data:s}of Dp(t))if(i===1){const a=new Ce(s);a.skipBits(4),n=!!a.readBits(1)}else if(i===3||i===6||i===7){if(n)return"key";const a=new Ce(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:Ut(r),y(!1)}};var Wr;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Wr||(Wr={}));const Fl=(r,e)=>{var o,c;const t=Ae(r);let n=0;const i=t.getUint32(n,!0);n+=4;const s=Jt.decode(r.subarray(n,n+i));n+=i,i>0&&(e.raw??(e.raw={}),(o=e.raw).vendor??(o.vendor=s));const a=t.getUint32(n,!0);n+=4;for(let l=0;l<a;l++){const u=t.getUint32(n,!0);n+=4;const d=Jt.decode(r.subarray(n,n+u));n+=u;const f=d.indexOf("=");if(f===-1)continue;const h=d.slice(0,f).toUpperCase(),p=d.slice(f+1);switch(e.raw??(e.raw={}),(c=e.raw)[h]??(c[h]=p),h){case"TITLE":e.title??(e.title=p);break;case"DESCRIPTION":e.description??(e.description=p);break;case"ARTIST":e.artist??(e.artist=p);break;case"ALBUM":e.album??(e.album=p);break;case"ALBUMARTIST":e.albumArtist??(e.albumArtist=p);break;case"COMMENT":e.comment??(e.comment=p);break;case"LYRICS":e.lyrics??(e.lyrics=p);break;case"TRACKNUMBER":{const m=p.split("/"),A=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(A)&&A>0&&(e.trackNumber??(e.trackNumber=A)),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??(e.tracksTotal=g))}break;case"TRACKTOTAL":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.tracksTotal??(e.tracksTotal=m))}break;case"DISCNUMBER":{const m=p.split("/"),A=Number.parseInt(m[0],10),g=m[1]&&Number.parseInt(m[1],10);Number.isInteger(A)&&A>0&&(e.discNumber??(e.discNumber=A)),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??(e.discsTotal=g))}break;case"DISCTOTAL":{const m=Number.parseInt(p,10);Number.isInteger(m)&&m>0&&(e.discsTotal??(e.discsTotal=m))}break;case"DATE":{const m=new Date(p);Number.isNaN(m.getTime())||(e.date??(e.date=m))}break;case"GENRE":e.genre??(e.genre=p);break;case"METADATA_BLOCK_PICTURE":{const m=qa(p),A=Ae(m),g=A.getUint32(0,!1),w=A.getUint32(4,!1),b=String.fromCharCode(...m.subarray(8,8+w)),k=A.getUint32(8+w,!1),S=Jt.decode(m.subarray(12+w,12+w+k)),x=A.getUint32(w+k+28),B=m.subarray(w+k+32,w+k+32+x);e.images??(e.images=[]),e.images.push({data:B,mimeType:b,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:S||void 0})}break}}},Rl=(r,e,t)=>{var p,m;const n=[r],s=Ve.encode("Mediabunny");let a=new Uint8Array(4+s.length),o=new DataView(a.buffer);o.setUint32(0,s.length,!0),a.set(s,4),n.push(a);const c=new Set,l=(A,g)=>{const w=`${A}=${g}`,b=Ve.encode(w);a=new Uint8Array(4+b.length),o=new DataView(a.buffer),o.setUint32(0,b.length,!0),a.set(b,4),n.push(a),c.add(A)};for(const{key:A,value:g}of Bi(e))switch(A){case"title":l("TITLE",g);break;case"description":l("DESCRIPTION",g);break;case"artist":l("ARTIST",g);break;case"album":l("ALBUM",g);break;case"albumArtist":l("ALBUMARTIST",g);break;case"genre":l("GENRE",g);break;case"date":{const w=((p=e.raw)==null?void 0:p.DATE)??((m=e.raw)==null?void 0:m.date);w&&typeof w=="string"?l("DATE",w):l("DATE",g.toISOString().slice(0,10))}break;case"comment":l("COMMENT",g);break;case"lyrics":l("LYRICS",g);break;case"trackNumber":l("TRACKNUMBER",g.toString());break;case"tracksTotal":l("TRACKTOTAL",g.toString());break;case"discNumber":l("DISCNUMBER",g.toString());break;case"discsTotal":l("DISCTOTAL",g.toString());break;case"images":{if(!t)break;for(const w of g){const b=w.kind==="coverFront"?3:w.kind==="coverBack"?4:0,k=new Uint8Array(w.mimeType.length);for(let C=0;C<w.mimeType.length;C++)k[C]=w.mimeType.charCodeAt(C);const S=Ve.encode(w.description??""),x=new Uint8Array(8+k.length+4+S.length+16+4+w.data.length),B=Ae(x);B.setUint32(0,b,!1),B.setUint32(4,k.length,!1),x.set(k,8),B.setUint32(8+k.length,S.length,!1),x.set(S,12+k.length),B.setUint32(28+k.length+S.length,w.data.length,!1),x.set(w.data,32+k.length+S.length);const I=FS(x);l("METADATA_BLOCK_PICTURE",I)}}break;case"raw":break;default:Ut(A)}if(e.raw)for(const A in e.raw){const g=e.raw[A]??e.raw[A.toLowerCase()];A==="vendor"||g==null||c.has(A)||typeof g=="string"&&l(A,g)}const u=new Uint8Array(4);Ae(u).setUint32(0,c.size,!0),n.splice(2,0,u);const d=n.reduce((A,g)=>A+g.length,0),f=new Uint8Array(d);let h=0;
50for(const A of n)f.set(A,h),h+=A.length;return f},Dl=[2,1,2,3,3,4,4,5],Op=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new Ce(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const n=e.readBits(6),i=e.readBits(5);if(i>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(n/2);return{fscod:t,bsid:i,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},mC=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],pC=1536,oo=new Uint8Array([5,4,65,67,45,51]),co=new Uint8Array([5,4,69,65,67,51]),Np=[1,2,3,6],Qp=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new Ce(r);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const n=e.readBits(11),i=e.readBits(2);let s=0,a;i===3?(s=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),l=e.readBits(5);if(l<11||l>16)return null;const u=Np[a];let d;return i<3?d=to[i]/1e3:d=Ip[s]/1e3,{dataRate:Math.round((n+1)*d/(u*16)),substreams:[{fscod:i,fscod2:s,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},gC=r=>{if(r.length<2)return null;const e=new Ce(r),t=e.readBits(13),n=e.readBits(3),i=[];for(let s=0;s<=n&&!(Math.ceil(e.pos/8)+3>r.length);s++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),l=e.readBits(3),u=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let f=0;d>0?f=e.readBits(9):e.skipBits(1),i.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:f})}return i.length===0?null:{dataRate:t,substreams:i}},Lp=r=>{const e=r.substreams[0];return y(e),e.fscod<3?to[e.fscod]:e.fscod2!==null&&e.fscod2<3?Ip[e.fscod2]:null},zp=r=>{const e=r.substreams[0];y(e);let t=Dl[e.acmod]+e.lfeon;if(e.numDepSub>0){const n=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)e.chanLoc&1<<8-i&&(t+=n[i])}return t};/*!
51 * Copyright (c) 2026-present, Vanilagy and contributors
52 *
53 * This Source Code Form is subject to the terms of the Mozilla Public
54 * License, v. 2.0. If a copy of the MPL was not distributed with this
55 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
56 */class Vr{constructor(e){this.input=e}dispose(){}}/*!
57 * Copyright (c) 2026-present, Vanilagy and contributors
58 *
59 * This Source Code Form is subject to the terms of the Mozilla Public
60 * License, v. 2.0. If a copy of the MPL was not distributed with this
61 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
62 */const $t=new Uint8Array(0);class He{constructor(e,t,n,i,s=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=i,this.sequenceNumber=s,e===$t&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(n))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if((o==null?void 0:o.alpha)!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((o==null?void 0:o.alphaByteLength)!==void 0&&(!Number.isInteger(o.alph
62aByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===$t}get microsecondTimestamp(){return Math.trunc(pn*this.timestamp)}get microsecondDuration(){return Math.trunc(pn*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");
62return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const n=new Uint8Array(e.byteLength);return e.copyTo(n),new He(n,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if((e==null?void 0:e.data)!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((e==null?void 0:e.type)!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if((e==null?void 0:e.sequenceNumber)!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((e==null?void 0:e.sideData)!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new He((e==null?void 0:e.data)??this.data,(e==null?void 0:e.type)??this.type,(e==null?void 0:e.timestamp)??this.timestamp,(e==null?void 0:e.duration)??this.duration,(e==null?void 0:e.sequenceNumber)??this.sequenceNumber,this.byteLength,(e==null?void 0:e.sideData)??this.sideData)}}/*!
63 * Copyright (c) 2026-present, Vanilagy and contributors
64 *
65 * This Source Code Form is subject to the terms of the Mozilla Public
66 * License, v. 2.0. If a copy of the MPL was not distributed with this
67 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
68 */const Wp=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const n=[...new Set(r.codecStrings)];t+=`; codecs="${n.join(", ")}"`}return t},Vp=r=>{const e=Ae(r);let t=0;const n=e.getUint8(t);t+=1,t+=3;const i=ks(r.subarray(t,t+16));t+=16;let s=null;if(n>0){const o=e.getUint32(t);if(t+=4,o>0){s=[];for(let c=0;c<o;c++)s.push(ks(r.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:i,keyIds:s,data:r.slice(t,t+a)}},Hp=(r,e)=>r.systemId===e.systemId&&lp(r.data,e.data);/*!
69 * Copyright (c) 2026-present, Vanilagy and contributors
70 *
71 * This Source Code Form is subject to the terms of the Mozilla Public
72 * License, v. 2.0. If a copy of the MPL was not distributed with this
73 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
74 */const Hr=8,Gn=16,En=r=>{let e=q(r);const t=ct(r,4);let n=8;e===1&&(e=fr(r),n=16);const s=e-n;return s<0?null:{name:t,totalSize:e,headerSize:n,contentSize:s}},Yn=r=>ei(r)/65536,Ml=r=>ei(r)/1073741824,Ul=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const n=se(r);if(e|=n&127,(n&128)===0)break}return e},Pr=r=>{let e=At(r);return r.skip(2),e=Math.min(e,r.remainingLength),Jt.decode(ae(r,e))},AC=r=>{const e=En(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=q(r);r.skip(4);const n=ae(r,e.contentSize-8);switch(t){case 1:return Jt.decode(n);case 2:return new TextDecoder("utf-16be").decode(n);case 13:return new Wn(n,"image/jpeg");case 14:return new Wn(n,"image/png");case 27:return new Wn(n,"image/bmp");default:return n}};/*!
75 * Copyright (c) 2026-present, Vanilagy and contributors
76 *
77 * This Source Code Form is subject to the terms of the Mozilla Public
78 * License, v. 2.0. If a copy of the MPL was not distributed with this
79 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
80 */const vr=16,Gr=new Uint32Array(256),Mi=new Uint32Array(256),Ui=new Uint32Array(256),Oi=new Uint32Array(256),Ni=new Uint32Array(256),Mt=new Uint32Array(256),Gp=new Uint32Array(10);let Yp=!1;const wC=()=>{const r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let s=0,a=1;s<256;s++)t[s]=a,e[a]=s,a=a^a<<1^(a&128?283:0);const n=(s,a)=>s&&a?t[(e[s]+e[a])%255]:0;r[0]=99;for(let s=1;s<256;s++){const a=t[255-e[s]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[s]=o}for(let s=0;s<256;s++){const a=r[s],o=r.indexOf(s);Gr[s]=a<<24|a<<16|a<<8|a,Mt[s]=o<<24|o<<16|o<<8|o;const c=n(o,14),l=n(o,9),u=n(o,13),d=n(o,11),f=c<<24|l<<16|u<<8|d;Mi[s]=f,Ui[s]=f>>>8|f<<24,Oi[s]=f>>>16|f<<16,Ni[s]=f>>>24|f<<8}let i=1;for(let s=0;s<10;s++)Gp[s]=i<<24,i=i<<1^(i&128?283:0);Yp=!0};class Kp{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(vr/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(vr),this.out=new Uint8Array(vr),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(e.byteLength===16),y(t.byteLength===16),Yp||wC();const n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=n.getUint32(0,!1),this.roundkey[1]=n.getUint32(4,!1),this.roundkey[2]=n.getUint32(8,!1),this.roundkey[3]=n.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let s=4;s<44;s+=4){const a=this.roundkey[s-1];this.roundkey[s]=this.roundkey[s-4]^Gr[a>>>16&255]&4278190080^Gr[a>>>8&255]&16711680^Gr[a>>>0&255]&65280^Gr[a>>>24&255]&255^Gp[s/4-1],this.roundkey[s+1]=this.roundkey[s-3]^this.roundkey[s],this.roundkey[s+2]=this.roundkey[s-2]^this.roundkey[s+1],this.roundkey[s+3]=this.roundkey[s-1]^this.roundkey[s+2]}for(let s=0,a=40;s<a;s+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[s+o];this.roundkey[s+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let s=4;s<40;s+=4)for(let a=0;a<4;a++){const o=this.roundkey[s+a];this.roundkey[s+a]=Mi[Gr[o>>>24&255]&255]^Ui[Gr[o>>>16&255]&255]^Oi[Gr[o>>>8&255]&255]^Ni[Gr[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],i=this.inView.getUint32(12,!1)^this.roundkey[3];const s=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let l,u,d,f;for(let g=1;g<10;g++){const w=g*4;l=Mi[e>>>24]^Ui[i>>>16&255]^Oi[n>>>8&255]^Ni[t&255]^this.roundkey[w],u=Mi[t>>>24]^Ui[e>>>16&255]^Oi[i>>>8&255]^Ni[n&255]^this.roundkey[w+1],d=Mi[n>>>24]^Ui[t>>>16&255]^Oi[e>>>8&255]^Ni[i&255]^this.roundkey[w+2],f=Mi[i>>>24]^Ui[n>>>16&255]^Oi[t>>>8&255]^Ni[e&255]^this.roundkey[w+3],e=l,t=u,n=d,i=f}const h=Mt[e>>>24&255]&4278190080^Mt[i>>>16&255]&16711680^Mt[n>>>8&255]&65280^Mt[t>>>0&255]&255^this.roundkey[40],p=Mt[t>>>24&255]&4278190080^Mt[e>>>16&255]&16711680^Mt[i>>>8&255]&65280^Mt[n>>>0&255]&255^this.roundkey[41],m=Mt[n>>>24&255]&4278190080^Mt[t>>>16&255]&16711680^Mt[e>>>8&255]&65280^Mt[i>>>0&255]&255^this.roundkey[42],A=Mt[i>>>24&255]&4278190080^Mt[n>>>16&255]&16711680^Mt[t>>>8&255]&65280^Mt[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,A^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const yC=(r,e,t)=>{let n=!1,i=0;const s=2**16,a=16,o=new Kp;return new ReadableStream({pull:async c=>{n||(o.init(await e()),n=!0);const l=s+a;let u=r.requestSliceRange(i,0,l);if(u instanceof Promise&&(u=await u),!u||u.length===0)throw new Error("Invalid ciphertext.");const d=u.length;if(d%16!==0)throw new Error("Invalid ciphertext.");const f=d===l?d-a:d,h=ae(u,f),p=new Uint8Array(f);for(let m=0;m<f;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),p.set(o.out,m);if(f<d)c.enqueue(p),i+=f;else{const m=p[f-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const A=p.subarray(0,f-m);c.enqueue(A),c.close(),t()}},cancel:()=>{t()}})};/*!
81 * Copyright (c) 2026-present, Vanilagy and contributors
82 *
83 * This Source Code Form is subject to the terms of the Mozilla Public
84 * License, v. 2.0. If a copy of the MPL was not distributed with this
85 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
86 */class Ol extends Vr{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.pss
86hBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return Wp({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>{var i;return((i=n.info)==null?void 0:i.type)==="video"}),hasAudio:this.tracks.some(n=>{var i;return((i=n.info)==null?void 0:i.type)==="audio"}),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1;for(;;){let n=this.reader.requestSliceRange(e,Hr,Gn);if(n instanceof Promise&&(n=await n),!n)break;const i=e,s=En(n);if(!s)break;if(s.name==="ftyp"||s.name==="styp"){const a=ct(n,4);this.isQuickTime=a==="qt  "}else if(s.name==="moov"){let a=this.reader.requestSlice(n.filePos,s.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(const o of this.tracks){const c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>i+s.totalSize;break}else if(s.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const a=await this.input._initInput._getDemuxer();if(a.constructor!==Ol)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(const o of a.tracks){const c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(y(c.info),c.info.type==="video"&&c.info.width!==-1){const l=c;c.trackBacking=new jp(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){const l=c;c.trackBacking=new Xp(l),this.tracks.push(c)}}}t=!1;break}e=i+s.totalSize}if(t){y(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);n instanceof Promise&&(n=await n),y(n);const i=q(n),s=this.reader.fileSize-i;if(s>=0&&s<=this.reader.fileSize-Gn){let a=this.reader.requestSliceRange(s,Hr,Gn);if(a instanceof Promise&&(a=await a),a){const o=En(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})())}getSampleTableForTrack(e){var s,a;if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,((s=e.info)==null?void 0:s.type)==="audio"&&e.info.codec&&yt.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){y(((a=e.info)==null?void 0:a.type)==="audio");const o=Ar(e.info.codec),c=[],l=[];for(let u=0;u<t.sampleToChunk.length;u++){const d=t.sampleToChunk[u],f=t.sampleToChunk[u+1],h=(f?f.startChunkIndex:t.chunkOffsets.length)-d.startChunkIndex;for(let p=0;p<h;p++){const m=d.startSampleIndex+p*d.samplesPerChunk,A=m+d.samplesPerChunk,g=Me(t.sampleTimingEntries,m,v=>v.startIndex),w=t.sampleTimingEntries[g],b=Me(t.sampleTimingEntries,A,v=>v.startIndex),k=t.sampleTimingEntries[b],S=w.startDecodeTimestamp+(m-w.startIndex)*w.delta,B=k.startDecodeTimestamp+(A-k.startIndex)*k.delta-S,I=tt(c);I&&I.delta===B?I.count++:c.push({startIndex:d.startChunkIndex+p,startDecodeTimestamp:S,count:1,delta:B});const C=d.samplesPerChunk*o.sampleSize*e.info.numberOfChannels;l.push(C)}d.startSampleIndex=d.startChunkIndex,d.samplesPerChunk=1}
86t.sampleTimingEntries=c,t.sampleSizes=l}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const o of t.sampleTimingEntries)for(let c=0;c<o.count;c++)t.presentationTimestamps.push({presentationTimestamp:o.startDecodeTimestamp+c*o.delta,sampleIndex:o.startIndex+c});for(const o of t.sampleCompositionTimeOffsets)for(let c=0;c<o.count;c++){const l=o.startIndex+c,u=t.presentationTimestamps[l];u&&(u.presentationTimestamp+=o.offset)}t.presentationTimestamps.sort((o,c)=>o.presentationTimestamp-c.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let o=0;o<t.presentationTimestamps.length;o++)t.presentationTimestampIndexMap[t.presentationTimestamps[o].sampleIndex]=o}return t}async readFragment(e){var a;if(((a=this.lastReadFragment)==null?void 0:a.moofOffset)===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,Hr,Gn);t instanceof Promise&&(t=await t),y(t);const n=En(t);y((n==null?void 0:n.name)==="moof");let i=this.reader.requestSlice(e,n.totalSize);i instanceof Promise&&(i=await i),y(i),this.traverseBox(i);const s=this.lastReadFragment;y(s&&s.moofOffset===e);for(const[,o]of s.trackData){const c=o.track,{fragmentPositionCache:l}=c;if(!o.startTimestampIsFinal){const d=c.fragmentLookupTable.find(f=>f.moofOffset===s.moofOffset);if(d)Ql(o,d.timestamp);else{const f=Me(l,s.moofOffset-1,h=>h.moofOffset);if(f!==-1){const h=l[f];Ql(o,h.endTimestamp)}}o.startTimestampIsFinal=!0}const u=Me(l,o.startTimestamp,d=>d.startTimestamp);if((u===-1||l[u].moofOffset!==s.moofOffset)&&l.splice(u+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){const d=await Zp(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let f=0;f<Math.min(o.samples.length,d.length);f++){const h=d[f];o.samples[f].encryption=h}}}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Hr&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Hr;){const n=e.filePos,i=En(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=n+i.totalSize}}traverseBox(e){var a,o,c,l,u,d,f,h,p,m,A,g,w,b,k,S,x,B,I,C,v,R,M,z,W,H,U,j,ce,ee,fe,he,G,ue,we,_e,Ye,xe,ne,Pe,Ee,me,Fe,Qe,ze;const t=e.filePos,n=En(e);if(!n)return!1;const i=e.filePos,s=t+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mvhd":{const T=se(e);e.skip(3),T===1?(e.skip(16),this.movieTimescale=q(e),this.movieDurationInTimescale=fr(e)):(e.skip(8),this.movieTimescale=q(e),this.movieDurationInTimescale=q(e))}break;case"trak":{const T={id:-1,demuxer:this,trackBacking:null,disposition:{...Lr,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Bt,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=T,this.readContiguousBoxes(e.slice(i,n.contentSize)),T.id!==-1&&T.timescale!==-1&&T.info!==null){if(T.info.type==="video"&&T.info.width!==-1){const V=T;T.trackBacking=new jp(V),this.tracks.push(T)}else if(T.info.type==="audio"&&T.info.numberOfChannels!==-1){const V=T;T.trackBacking=new Xp(V),this.tracks.push(T)}}this.currentTrack=null}break;case"tkhd":{const T=this.currentTrack;if(!T)break;const V=se(e),O=!!(Jr(e)&1);if(T.disposition.default=O,V===0)e.skip(8),T.id=q(e),e.skip(4),T.durationInMovieTimescale=q(e);else if(V===1)e.skip(16),T.id=q(e),e.skip(4),T.durationInMovieTimescale=fr(e);else throw new Error(`Incorrect track header version ${V}.`);e.skip(16);const K=[Yn(e),Yn(e),Ml(e),Yn(e),Yn(e),Ml(e),Yn(e),Yn(e),Ml(e)],N=Ti(al(TC(K),90));y(N===0||N===90||N===180||N===270),T.rotation=N}break;case"elst":{const T=this.currentTrack;if(!T)break;const V=se(e);e.skip(3);let F=!1,O=0;const K=q(e);for(let N=0;N<K;N++){const X=V===1?fr(e):q(e),re=V===1?XI(e):ei(e),oe=Yn(e);if(X!==0){if(F){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(re===-1){O+=X;continue}if(oe!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}T.editListPreviousSegmentDurations=O,T.editListOffset=re,F=!0}}}break;case"mdhd":{const T=this.currentTrack;if(!T)break;const V=se(e);e.skip(3),V===0?(e.skip(8),T.timescale=q(e),T.durationInMediaTimescale=q(e)):V===1&&(e.skip(16),T.timescale=q(e),T.durationInMediaTimescale=fr(e));let F=At(e);if(F>0){T.languageCode="";for(let O=0;O<3;O++)T.languageCode=String.fromCharCode(96+(F&31))+T.languageCode,F>>=5;Cs(T.languageCode)||(T.languageCode=Bt)}}break;case"hdlr":{const T=this.currentTrack;if(!T)break;e.skip(8);const V=ct(e,4);V==="vide"?T.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:V==="soun"&&(T.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const T=this.currentTrack;if(!T)break;T.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(i,n.c
86ontentSize))}break;case"stsd":{const T=this.currentTrack;if(!T||T.info===null||T.sampleTable)break;const V=se(e);e.skip(3);const F=q(e);for(let O=0;O<F;O++){const K=e.filePos,N=En(e);if(!N)break;T.internalCodecId=N.name;const X=N.name.toLowerCase();if(T.info.type==="video"){e.skip(24),T.info.width=At(e),T.info.height=At(e),T.info.squarePixelWidth=T.info.width,T.info.squarePixelHeight=T.info.height,e.skip(50),T.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,K+N.totalSize-e.filePos));const re=X==="encv"?T.frmaCodecString:X;T.frmaCodecString=null,re==="avc1"||re==="avc3"?(T.info.codec="avc",T.info.avcType=re==="avc1"?1:3):re==="hvc1"||re==="hev1"?T.info.codec="hevc":re==="vp08"?T.info.codec="vp8":re==="vp09"?T.info.codec="vp9":re==="av01"?T.info.codec="av1":console.warn(re===null?"Unknown encrypted video codec due to missing frma box.":`Unsupported video codec (sample entry type '${N.name}').`)}else{e.skip(8);const re=At(e);e.skip(6);let oe=At(e),ie=At(e);e.skip(4);let ke=q(e)/65536,Ne=null;V===0&&re>0&&(re===1?(e.skip(4),ie=8*q(e),e.skip(8)):re===2&&(e.skip(4),ke=LA(e),oe=q(e),e.skip(4),ie=q(e),Ne=q(e),e.skip(8))),T.info.numberOfChannels=oe,T.info.sampleRate=ke,T.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,K+N.totalSize-e.filePos));const te=X==="enca"?T.frmaCodecString:X;if(T.frmaCodecString=null,te!=="mp4a")if(te==="opus")T.info.codec="opus",T.info.sampleRate=Fi;else if(te==="flac")T.info.codec="flac";else if(te==="ulaw")T.info.codec="ulaw";else if(te==="alaw")T.info.codec="alaw";else if(te==="ac-3")T.info.codec="ac3";else if(te==="ec-3")T.info.codec="eac3";else if(te==="twos")ie===8?T.info.codec="pcm-s8":ie===16?T.info.codec=T.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${ie} for codec 'twos'.`),T.info.codec=null);else if(te==="sowt")ie===8?T.info.codec="pcm-s8":ie===16?T.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${ie} for codec 'sowt'.`),T.info.codec=null);else if(te==="raw ")T.info.codec="pcm-u8";else if(te==="in24")T.info.codec=T.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(te==="in32")T.info.codec=T.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(te==="fl32")T.info.codec=T.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(te==="fl64")T.info.codec=T.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(te==="ipcm"){const be=T.info.pcmSampleSize;T.info.pcmLittleEndian?be===16?T.info.codec="pcm-s16":be===24?T.info.codec="pcm-s24":be===32?T.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${be}.`),T.info.codec=null):be===16?T.info.codec="pcm-s16be":be===24?T.info.codec="pcm-s24be":be===32?T.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${be}.`),T.info.codec=null)}else if(te==="fpcm"){const be=T.info.pcmSampleSize;T.info.pcmLittleEndian?be===32?T.info.codec="pcm-f32":be===64?T.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${be}.`),T.info.codec=null):be===32?T.info.codec="pcm-f32be":be===64?T.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${be}.`),T.info.codec=null)}else if(te==="lpcm"&&Ne!==null){const be=ie+7>>3,ht=!!(Ne&1),at=!!(Ne&2),vt=Ne&4?-1:0;ie>0&&ie<=64&&(ht?ie===32&&(T.info.codec=at?"pcm-f32be":"pcm-f32"):vt&1<<be-1?be===1?T.info.codec="pcm-s8":be===2?T.info.codec=at?"pcm-s16be":"pcm-s16":be===3?T.info.codec=at?"pcm-s24be":"pcm-s24":be===4&&(T.info.codec=at?"pcm-s32be":"pcm-s32"):be===1&&(T.info.codec="pcm-u8")),T.info.codec===null&&console.warn("Unsupported PCM format.")}else console.warn(te===null?"Unknown encrypted audio codec due to missing frma box.":`Unsupported audio codec (sample entry type '${N.name}').`)}e.filePos=K+N.totalSize}}break;case"frma":{const T=this.currentTrack;if(!T)break;const F=ct(e,4).toLowerCase();T.frmaCodecString=F}break;case"schm":{const T=this.currentTrack;if(!T)break;e.skip(4);const V=ct(e,4);V==="cenc"||V==="cens"||V==="cbcs"?T.encryptionInfo={scheme:V,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${V}'.`)}break;case"tenc":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;const V=se(e);e.skip(3),e.skip(1);const F=se(e);if(V>0?(T.encryptionInfo.defaultCryptByteBlock=F>>4,T.encryptionInfo.defaultSkipByteBlock=F&15):(T.encryptionInfo.defaultCryptByteBlock=0,T.encryptionInfo.defaultSkipByteBlock=0),T.encryptionInfo.defaultIsProtected=se(e)!==0,T.encryptionInfo.defaultPerSampleIvSize=se(e),T.encryptionInfo.defaultKid=ks(ae(e,16)),T.encryptionInfo.defaultIsProtected&&T.encryptionInfo.defaultPerSampleIvSize===0){const O=se(e),K=new Uint8Array(16);K.set(ae(e,O),0),T.encryptionInfo.defaultConstantIv=K}}break;case"avcC":{const T=this.currentTrack;if(!T)break;y(T.info),T.info.codecDescription=ae(e,n.contentSize)}break;case"hvcC":{const T=this.currentTrack;if(!T)break;y(T.info),T.info.codecDescription=ae(e,n.contentSize)}break;case"vpcC":{const T=this.currentTrack;if(!T)break;y(((a=T.info)==null?void 0:a.type)==="video"),e.skip(4);const V=se(e),F=se(e),O=se(e),K=O>>4,N=O>>1&7,X=O&1,re=se(e),oe=se(e),ie=se(e);T.info.vp9CodecInfo={profile:V,level:F,bitDepth:K,chromaSubsampling:N,videoFullRangeFlag:X,colourPrimaries:re,transferCharacteristics:oe,matrixCoefficients:ie}}break;case"av1C":{const T=this.currentTrack;if(!T)break;y(((o=T.info)==null?void 0:o.type)==="video"),e.skip(1);const V=se(e),F=V>>5,O=V&31,K=se(e),N=K>>7,X=K>>6&1,re=K>>5&1,oe=K>>4&1,ie=K>>3&1,ke=K>>2&1,Ne=K&3,te=F===2&&X?re?12:10:X?10:8;T.info.av1CodecInfo={profile:F,level:O,tier:N,bitDepth:te,monochrome:oe,chromaSubsamplingX:ie,chromaSubsamplingY:ke,chromaSamplePosition:Ne}}break;case"colr":{const T=this.currentTrack;if(!T||(y(((c=T.info)==null?void 0:c.type)==="video"),ct(e,4)!=="nclx"))break;const F=At(e),O=At(e),K=At(e),N=!!(se(e)&128);
86T.info.colorSpace={primaries:La[F],transfer:za[O],matrix:Wa[K],fullRange:N}}break;case"pasp":{const T=this.currentTrack;if(!T)break;y(((l=T.info)==null?void 0:l.type)==="video");const V=q(e),F=q(e);V>0&&F>0&&(V>F?T.info.squarePixelWidth=Math.round(T.info.width*V/F):T.info.squarePixelHeight=Math.round(T.info.height*F/V))}break;case"wave":this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"esds":{const T=this.currentTrack;if(!T)break;y(((u=T.info)==null?void 0:u.type)==="audio"),e.skip(4);const V=se(e);y(V===3),Ul(e),e.skip(2);const F=se(e),O=(F&128)!==0,K=(F&64)!==0,N=(F&32)!==0;if(O&&e.skip(2),K){const ke=se(e);e.skip(ke)}N&&e.skip(2);const X=se(e);y(X===4);const re=Ul(e),oe=e.filePos,ie=se(e);if(ie===64||ie===103?(T.info.codec="aac",T.info.aacCodecInfo={isMpeg2:ie===103,objectType:null}):ie===105||ie===107?T.info.codec="mp3":ie===221?T.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${ie}) - discarding track.`),e.skip(12),re>e.filePos-oe){const ke=se(e);y(ke===5);const Ne=Ul(e);if(T.info.codecDescription=ae(e,Ne),T.info.codec==="aac"){const te=Rs(T.info.codecDescription);te.numberOfChannels!==null&&(T.info.numberOfChannels=te.numberOfChannels),te.sampleRate!==null&&(T.info.sampleRate=te.sampleRate)}}}break;case"enda":{const T=this.currentTrack;if(!T)break;y(((d=T.info)==null?void 0:d.type)==="audio"),T.info.pcmLittleEndian=!!(At(e)&255)}break;case"pcmC":{const T=this.currentTrack;if(!T)break;y(((f=T.info)==null?void 0:f.type)==="audio"),e.skip(4);const V=se(e);T.info.pcmLittleEndian=!!(V&1),T.info.pcmSampleSize=se(e)}break;case"dOps":{const T=this.currentTrack;if(!T)break;y(((h=T.info)==null?void 0:h.type)==="audio"),e.skip(1);const V=se(e),F=At(e),O=q(e),K=Pu(e),N=se(e);let X;N!==0?X=ae(e,2+V):X=new Uint8Array(0);const re=new Uint8Array(19+X.byteLength),oe=new DataView(re.buffer);oe.setUint32(0,1332770163,!1),oe.setUint32(4,1214603620,!1),oe.setUint8(8,1),oe.setUint8(9,V),oe.setUint16(10,F,!0),oe.setUint32(12,O,!0),oe.setInt16(16,K,!0),oe.setUint8(18,N),re.set(X,19),T.info.codecDescription=re,T.info.numberOfChannels=V}break;case"dfLa":{const T=this.currentTrack;if(!T)break;y(((p=T.info)==null?void 0:p.type)==="audio"),e.skip(4);const V=127,F=128,O=e.filePos;for(;e.filePos<s;){const oe=se(e),ie=Jr(e);if((oe&V)===Wr.STREAMINFO){e.skip(10);const Ne=q(e),te=Ne>>>12,be=(Ne>>9&7)+1;T.info.sampleRate=te,T.info.numberOfChannels=be,e.skip(20)}else e.skip(ie);if(oe&F)break}const K=e.filePos;e.filePos=O;const N=ae(e,K-O),X=new Uint8Array(4+N.byteLength);new DataView(X.buffer).setUint32(0,1716281667,!1),X.set(N,4),T.info.codecDescription=X}break;case"dac3":{const T=this.currentTrack;if(!T)break;y(((m=T.info)==null?void 0:m.type)==="audio");const V=ae(e,3),F=new Ce(V),O=F.readBits(2);F.skipBits(8);const K=F.readBits(3),N=F.readBits(1);O<3&&(T.info.sampleRate=to[O]),T.info.numberOfChannels=Dl[K]+N}break;case"dec3":{const T=this.currentTrack;if(!T)break;y(((A=T.info)==null?void 0:A.type)==="audio");const V=ae(e,n.contentSize),F=gC(V);if(!F){console.warn("Invalid dec3 box contents, ignoring.");break}const O=Lp(F);O!==null&&(T.info.sampleRate=O),T.info.numberOfChannels=zp(F)}break;case"stts":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e);let F=0,O=0;for(let K=0;K<V;K++){const N=q(e),X=q(e);T.sampleTable.sampleTimingEntries.push({startIndex:F,startDecodeTimestamp:O,count:N,delta:X}),F+=N,O+=N*X}}break;case"ctts":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e);let F=0;for(let O=0;O<V;O++){const K=q(e),N=ei(e);T.sampleTable.sampleCompositionTimeOffsets.push({startIndex:F,count:K,offset:N}),F+=K}}break;case"stsz":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e),F=q(e);if(V===0)for(let O=0;O<F;O++){const K=q(e);T.sampleTable.sampleSizes.push(K)}else T.sampleTable.sampleSizes.push(V)}break;case"stz2":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4),e.skip(3);const V=se(e),F=q(e),O=ae(e,Math.ceil(F*V/8)),K=new Ce(O);for(let N=0;N<F;N++){const X=K.readBits(V);T.sampleTable.sampleSizes.push(X)}}break;case"stss":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4),T.sampleTable.keySampleIndices=[];const V=q(e);for(let F=0;F<V;F++){const O=q(e)-1;T.sampleTable.keySampleIndices.push(O)}T.sampleTable.keySampleIndices[0]!==0&&T.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e);for(let O=0;O<V;O++){const K=q(e)-1,N=q(e),X=q(e);T.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:K,samplesPerChunk:N,sampleDescriptionIndex:X})}let F=0;for(let O=0;O<T.sampleTable.sampleToChunk.length;O++)if(T.sampleTable.sampleToChunk[O].startSampleIndex=F,O<T.sampleTable.sampleToChunk.length-1){const N=T.sampleTable.sampleToChunk[O+1
86].startChunkIndex-T.sampleTable.sampleToChunk[O].startChunkIndex;F+=N*T.sampleTable.sampleToChunk[O].samplesPerChunk}}break;case"stco":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e);for(let F=0;F<V;F++){const O=q(e);T.sampleTable.chunkOffsets.push(O)}}break;case"co64":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const V=q(e);for(let F=0;F<V;F++){const O=fr(e);T.sampleTable.chunkOffsets.push(O)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(i,n.contentSize));break;case"mehd":{const T=se(e);e.skip(3);const V=T===1?fr(e):q(e);this.movieDurationInTimescale=V}break;case"trex":{e.skip(4);const T=q(e),V=q(e),F=q(e),O=q(e),K=q(e);this.fragmentTrackDefaults.push({trackId:T,defaultSampleDescriptionIndex:V,defaultSampleDuration:F,defaultSampleSize:O,defaultSampleFlags:K})}break;case"tfra":{const T=se(e);e.skip(3);const V=q(e),F=this.tracks.find(te=>te.id===V);if(!F)break;const O=q(e),K=(O&48)>>4,N=(O&12)>>2,X=O&3,re=[se,At,Jr,q],oe=re[K],ie=re[N],ke=re[X],Ne=q(e);for(let te=0;te<Ne;te++){const be=T===1?fr(e):q(e),ht=T===1?fr(e):q(e);oe(e),ie(e),ke(e),F.fragmentLookupTable.push({timestamp:be,moofOffset:ht})}F.fragmentLookupTable.sort((te,be)=>te.timestamp-be.timestamp);for(let te=0;te<F.fragmentLookupTable.length-1;te++){const be=F.fragmentLookupTable[te],ht=F.fragmentLookupTable[te+1];be.timestamp===ht.timestamp&&(F.fragmentLookupTable.splice(te+1,1),te--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(i,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(y(this.currentFragment),this.readContiguousBoxes(e.slice(i,n.contentSize)),this.currentTrack){const T=this.currentFragment.trackData.get(this.currentTrack.id);if(T){this.currentFragment.implicitBaseDataOffset=T.currentOffset,T.presentationTimestamps=T.samples.map((K,N)=>({presentationTimestamp:K.presentationTimestamp,sampleIndex:N})).sort((K,N)=>K.presentationTimestamp-N.presentationTimestamp);for(let K=0;K<T.presentationTimestamps.length;K++){const N=T.presentationTimestamps[K],X=T.samples[N.sampleIndex];if(T.firstKeyFrameTimestamp===null&&X.isKeyFrame&&(T.firstKeyFrameTimestamp=X.presentationTimestamp),K<T.presentationTimestamps.length-1){const oe=T.presentationTimestamps[K+1].presentationTimestamp-N.presentationTimestamp;X.duration=oe}}const V=T.samples[T.presentationTimestamps[0].sampleIndex],F=T.samples[tt(T.presentationTimestamps).sampleIndex];T.startTimestamp=V.presentationTimestamp,T.endTimestamp=F.presentationTimestamp+F.duration;const{currentFragmentState:O}=this.currentTrack;y(O),O.startTimestamp!==null&&(Ql(T,O.startTimestamp),T.startTimestampIsFinal=!0),O.encryptionAuxInfo&&!T.samples[0].encryption&&(T.encryptionAuxInfo=O.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if((g=this.input._formatOptions.isobmff)!=null&&g._suppressPsshParsing)break;const T=Vp(ae(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(T):this.currentTrack||this.psshBoxes.push(T)}break;case"tfhd":{y(this.currentFragment),e.skip(1);const T=Jr(e),V=!!(T&1),F=!!(T&2),O=!!(T&8),K=!!(T&16),N=!!(T&32),X=!!(T&65536),re=!!(T&131072),oe=q(e),ie=this.tracks.find(Ne=>Ne.id===oe);if(!ie)break;const ke=this.fragmentTrackDefaults.find(Ne=>Ne.trackId===oe);this.currentTrack=ie,ie.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:(ke==null?void 0:ke.defaultSampleDescriptionIndex)??null,defaultSampleDuration:(ke==null?void 0:ke.defaultSampleDuration)??null,defaultSampleSize:(ke==null?void 0:ke.defaultSampleSize)??null,defaultSampleFlags:(ke==null?void 0:ke.defaultSampleFlags)??null,startTimestamp:null,encryptionAuxInfo:null},V?ie.currentFragmentState.baseDataOffset=fr(e):re&&(ie.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),F&&(ie.currentFragmentState.sampleDescriptionIndex=q(e)),O&&(ie.currentFragmentState.defaultSampleDuration=q(e)),K&&(ie.currentFragmentState.defaultSampleSize=q(e)),N&&(ie.currentFragmentState.defaultSampleFlags=q(e)),X&&(ie.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const T=this.currentTrack;if(!T)break;y(T.currentFragmentState);const V=se(e);e.skip(3);const F=V===0?q(e):fr(e);T.currentFragmentState.startTimestamp=F}break;case"trun":{const T=this.currentTrack;if(!T)break;y(this.currentFragment),y(T.currentFragmentState);const V=se(e),F=Jr(e),O=!!(F&1),K=!!(F&4),N=!!(F&256),X=!!(F&512),re=!!(F&1024),oe=!!(F&2048),ie=q(e);let ke=null;O&&(ke=ei(e));let Ne=null;K&&(Ne=q(e));let te;if(this.currentFragment.trackData.has(T.id)?(te=this.currentFragment.trackData.get(T.id),ke!==null&&(te.currentOffset=T.currentFragmentState.baseDataOffset+ke)):(te={track:T,currentTimestamp:0,currentOffset:T.currentFragmentState.baseDataOffset+(ke??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(T.id,te)),ie===0){this.currentFragment.implicitBaseDataOffset=te.currentOffset;break}for(let be=0;be<ie;be++){let ht;N?ht=q(e):(y(T.currentFragmentState.defaultSampleDuration!==null),ht=T.currentFragmentState.defaultSampleDuration);let at;X?at=q(e):(y(T.currentFragmentState.defaultSampleSize!==null),at=T.currentFragmentState.defaultSampleSize);let vt;re?vt=q(e):(y(T.currentFragmentState.defaultSampleFlags!==null),vt=T.currentFragmentState.defaultSampleFlags),be===0&&Ne!==null&&(vt=Ne);let _n=0;
86oe&&(V===0?_n=q(e):_n=ei(e));const ua=!(vt&65536);te.samples.push({presentationTimestamp:te.currentTimestamp+_n,duration:ht,byteOffset:te.currentOffset,byteSize:at,isKeyFrame:ua,encryption:null}),te.currentOffset+=at,te.currentTimestamp+=ht}}break;case"saiz":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;if(e.skip(1),Jr(e)&1){const X=ct(e,4),re=q(e);if(X!==T.encryptionInfo.scheme||re!==0)break}const F=se(e),O=q(e);let K=null;F===0&&O>0&&(K=ae(e,O));const N=$p(T);N.defaultSampleInfoSize=F,N.sampleSizes=K,N.sampleCount=O}break;case"saio":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;const V=se(e);if(Jr(e)&1){const X=ct(e,4),re=q(e);if(X!==T.encryptionInfo.scheme||re!==0)break}const O=q(e);if(O===0)break;O>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let K=V===0?q(e):Number(fr(e));this.currentFragment&&(K+=this.currentFragment.moofOffset);const N=$p(T);N.offset=K}break;case"senc":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;y(this.currentFragment);const V=this.currentFragment.trackData.get(T.id);if(!V)break;e.skip(1);const O=!!(Jr(e)&2),K=q(e),N=T.encryptionInfo.defaultPerSampleIvSize;y(N!==null);for(let X=0;X<Math.min(K,V.samples.length);X++){const re=new Uint8Array(16);N>0?re.set(ae(e,N),0):re.set(T.encryptionInfo.defaultConstantIv,0);let oe=null;if(O){const ke=At(e);oe=[];for(let Ne=0;Ne<ke;Ne++){const te=At(e),be=q(e);oe.push({clearLen:te,protectedLen:be})}}const ie=V.samples[X];ie.encryption={iv:re,subsamples:oe}}}break;case"udta":{const T=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(const{boxInfo:V,slice:F}of T){if(V.name!=="meta"&&!this.currentTrack){const O=F.filePos;(w=this.metadataTags).raw??(w.raw={}),V.name[0]==="©"?(b=this.metadataTags.raw)[k=V.name]??(b[k]=Pr(F)):(S=this.metadataTags.raw)[x=V.name]??(S[x]=ae(F,V.contentSize)),F.filePos=O}switch(V.name){case"meta":F.skip(-V.headerSize),this.traverseBox(F);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=Jt.decode(ae(F,V.contentSize)):(B=this.metadataTags).title??(B.title=Pr(F));break;case"©des":this.currentTrack||((I=this.metadataTags).description??(I.description=Pr(F)));break;case"©ART":this.currentTrack||((C=this.metadataTags).artist??(C.artist=Pr(F)));break;case"©alb":this.currentTrack||((v=this.metadataTags).album??(v.album=Pr(F)));break;case"albr":this.currentTrack||((R=this.metadataTags).albumArtist??(R.albumArtist=Pr(F)));break;case"©gen":this.currentTrack||((M=this.metadataTags).genre??(M.genre=Pr(F)));break;case"©day":if(!this.currentTrack){const O=new Date(Pr(F));Number.isNaN(O.getTime())||((z=this.metadataTags).date??(z.date=O))}break;case"©cmt":this.currentTrack||((W=this.metadataTags).comment??(W.comment=Pr(F)));break;case"©lyr":this.currentTrack||((H=this.metadataTags).lyrics??(H.lyrics=Pr(F)));break}}}break;case"meta":{if(this.currentTrack)break;const V=q(e)!==0;this.currentMetadataKeys=new Map,V?this.readContiguousBoxes(e.slice(i,n.contentSize)):this.readContiguousBoxes(e.slice(i+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const T=q(e);for(let V=0;V<T;V++){const F=q(e);e.skip(4);const O=Jt.decode(ae(e,F-8));this.currentMetadataKeys.set(V+1,O)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const T=this.iterateContiguousBoxes(e.slice(i,n.contentSize));for(const{boxInfo:V,slice:F}of T){let O=V.name;const K=(O.charCodeAt(0)<<24)+(O.charCodeAt(1)<<16)+(O.charCodeAt(2)<<8)+O.charCodeAt(3);this.currentMetadataKeys.has(K)&&(O=this.currentMetadataKeys.get(K));const N=AC(F);switch((U=this.metadataTags).raw??(U.raw={}),(j=this.metadataTags.raw)[O]??(j[O]=N),O){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof N=="string"&&((ce=this.metadataTags).title??(ce.title=N));break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof N=="string"&&((ee=this.metadataTags).description??(ee.description=N));break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof N=="string"&&((fe=this.metadataTags).artist??(fe.artist=N));break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof N=="string"&&((he=this.metadataTags).album??(he.album=N));break;case"aART":case"album_artist":typeof N=="string"&&((G=this.metadataTags).albumArtist??(G.albumArtist=N));break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof N=="string"&&((ue=this.metadataTags).comment??(ue.comment=N));break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof N=="string"&&((we=this.metadataTags).genre??(we.genre=N));break;case"©lyr":case"lyrics":typeof N=="string"&&((_e=this.metadataTags).lyrics??(_e.lyrics=N));break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof N=="string"){const X=new Date(N);Number.isNaN(X.getTime())||((Ye=this.metadataTags).date??(Ye.date=X))}break;case"covr":case"com.apple.quicktime.artwork":N instanceof Wn?((xe=this.metadataTags).images??(xe.images=[]),this.metadataTags.images.push({data:N.data,kind:"coverFront",mimeType:N.mimeType})):N instanceof Uint8Array&&((ne=this.metadataTags).images??(ne.images=[]),this.metadataTags.images.push({data:N,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof N=="string"){const X=N.split("/"),re=Number.parseInt(X[0],10),oe=X[1]&&Number.parseInt(X[1],10);Number.isInteger(re)&&re>0&&((Pe=this.metadataTags).trackNumber??(Pe.trackNumber=re)),oe&&Number.isInteger(oe)&&oe>0&&((Ee=this.metadataTags).tracksTotal??(Ee.tracksTotal=oe))}break;case"trkn":if(N instanceof Uint8Array&&N.length>=6){const X=Ae(N),re=X.getUint16(2,!1),oe=X.getUint16(4,!1);re>0&&((me=this.metadataTags).trackNumber??(me.trackNumber=re)),oe>0&&((Fe=this.metadataTags).tracksTotal??(Fe.tracksTotal=oe))}break;case"disc":case"disk":if(N instanceof Uint8Array&&N.length>=6){const X=Ae(N),re=X.getUint16(2,!1),oe=X.getUint16(4,!1);re>0&&((Qe=this.metadataTags).discNumber??(Qe.discNumber=re)),oe>0&&((ze=this.metadataTags).discsTotal??(ze.discsTotal=oe))}break}}}break}return e.filePos=s,!0}}class qp{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let n=0;for(const i of e.tracks)if(i.trackBacking.getType()===t&&n++,i===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;y(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});
86return((t==null?void 0:t.timestamp)??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,n=>n.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ss(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Nl(i,n),a=await this.fetchPacketForSampleIndex(s,t);return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=Me(c.presentationTimestamps,n,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextPacket(e,t){const n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const a=s.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<a.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const n=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=bC(i,n),a=await this.fetchPacketForSampleIndex(s,t);
86return!Jp(i)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=Va(c.presentationTimestamps,f=>c.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=n),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&n<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},n,n,t)}async getNextKeyPacket(e,t){const n=this.packetToSampleIndex.get(e);if(n!==void 0){const s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=kC(s,n);return this.fetchPacketForSampleIndex(a,t)}const i=this.packetToFragmentLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,s=>{if(s===i.fragment){const o=s.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>i.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=s.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return y(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=EC(n,e);if(!i)return null;let s;if(t.metadataOnly)s=$t;else{let l=this.internalTrack.demuxer.reader.requestSlice(i.sampleOffset,i.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(s=ae(l,i.sampleSize),this.internalTrack.encryptionAuxInfo){y(this.internalTrack.encryptionInfo);const u=await Zp(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<u.length&&(s=await eg(this.internalTrack,u[e],s,null))}}const a=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=i.duration/this.internalTrack.timescale,c=new He(s,i.isKeyFrame?"key":"delta",a,o,e,i.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,n){if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).samples[t];y(s);let a;if(n.metadataOnly)a=$t;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(u instanceof Promise&&(u=await u),!u)return null;a=ae(u,s.byteSize),s.encryption&&(a=await eg(this.internalTrack,s.encryption,a,e))}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=new He(a,s.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,n,i,s){const a=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:A,correctSampleFound:g}=t(e);if(g)return this.fetchPacketInFragment(e,A,s);A!==-1&&(c=e,l=A)}const u=Me(this.internalTrack.fragmentLookupTable,n,A=>A.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=Me(this.internalTrack.fragmentPositionCache,n,A=>A.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max((d==null?void 0:d.moofOffset)??0,(h==null?void 0:h.moofOffset)??0)||null;let m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){const b=o.trackData.get(this.internalTrack.id);if(b&&b.startTimestamp>i)break}let A=a.reader.requestSliceRange(m,Hr,Gn);if(A instanceof Promise&&(A=await A),!A)break;const g=m,w=En(A);if(!w)break;if(w.name==="moof"){o=await a.readFragment(g);const{sampleIndex:b,correctSampleFound:k}=t(o);if(k)return this.fetchPacketInFragment(o,b,s);b!==-1&&(c=o,l=b)}m=g+w.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const A=this.internalTrack.fragmentLookupTable[u-1];y(!A||A.timestamp<d.timestamp);const g=(A==null?void 0:A.timestamp)??-1/0;return this.performFragmentedLookup(null,t,g,i,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class jp extends qp{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){var e,t,n,i;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(n=this.internalTrack.info.colorSpace)==null?void 0:n.matrix,fullRange:(i=this.internalTrack.info.colorSpace)==null?void 0:i.fullRange}}
86async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Rp(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Mp(t.data)}const e={codec:bl(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})()):null}}class Xp extends qp{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:El(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const Nl=(r,e)=>{if(r.presentationTimestamps){const t=Me(r.presentationTimestamps,e,n=>n.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=Me(r.sampleTimingEntries,e,i=>i.startDecodeTimestamp);if(t===-1)return-1;const n=r.sampleTimingEntries[t];return n.startIndex+Math.min(Math.floor((e-n.startDecodeTimestamp)/n.delta),n.count-1)}},bC=(r,e)=>{if(!r.keySampleIndices)return Nl(r,e);if(r.presentationTimestamps){const t=Me(r.presentationTimestamps,e,n=>n.presentationTimestamp);if(t===-1)return-1;for(let n=t;n>=0;n--){const i=r.presentationTimestamps[n].sampleIndex;if(Ts(r.keySampleIndices,i,a=>a)!==-1)return i}return-1}else{const t=Nl(r,e),n=Me(r.keySampleIndices,t,i=>i);return r.keySampleIndices[n]??-1}},EC=(r,e)=>{const t=Me(r.sampleTimingEntries,e,g=>g.startIndex),n=r.sampleTimingEntries[t];if(!n||n.startIndex+n.count<=e)return null;let s=n.startDecodeTimestamp+(e-n.startIndex)*n.delta;const a=Me(r.sampleCompositionTimeOffsets,e,g=>g.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=Me(r.sampleToChunk,e,g=>g.startSampleIndex),u=r.sampleToChunk[l];y(u);const d=u.startChunkIndex+Math.floor((e-u.startSampleIndex)/u.samplesPerChunk),f=r.chunkOffsets[d],h=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk;let p=0,m=f;if(r.sampleSizes.length===1)m+=c*(e-h),p+=c*u.samplesPerChunk;else for(let g=h;g<h+u.samplesPerChunk;g++){const w=r.sampleSizes[g];g<e&&(m+=w),p+=w}let A=n.delta;if(r.presentationTimestamps){const g=r.presentationTimestampIndexMap[e];y(g!==void 0),g<r.presentationTimestamps.length-1&&(A=r.presentationTimestamps[g+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:A,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:p,isKeyFrame:r.keySampleIndices?Ts(r.keySampleIndices,e,g=>g)!==-1:!0}},kC=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=Me(r.keySampleIndices,e,n=>n);return r.keySampleIndices[t+1]??-1},Ql=(r,e)=>{r.startTimestamp+=e,r.endTimestamp+=e;for(const t of r.samples)t.presentationTimestamp+=e;for(const t of r.presentationTimestamps)t.presentationTimestamp+=e},TC=r=>{const[e,t]=r,n=Math.atan2(t,e);return Number.isFinite(n)?n*(180/Math.PI):0},Jp=r=>r.sampleSizes.length===0,$p=r=>{var e;return r.currentFragmentState?(e=r.currentFragmentState).encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleC
86ount:0,offset:null,resolved:null}):r.encryptionAuxInfo??(r.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Zp=async(r,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let n=0;if(t.defaultSampleInfoSize>0)n=t.defaultSampleInfoSize*t.sampleCount;else{y(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)n+=t.sampleSizes[o]}let i=r.requestSlice(t.offset,n);if(i instanceof Promise&&(i=await i),!i)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;y(s!==null);const a=[];for(let o=0;o<t.sampleCount;o++){const c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],l=new Uint8Array(16);s>0?l.set(ae(i,s),0):l.set(e.defaultConstantIv,0);let u=null;if(c>s){const d=At(i);u=[];for(let f=0;f<d;f++){const h=At(i),p=q(i);u.push({clearLen:h,protectedLen:p})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},eg=async(r,e,t,n)=>{var c;y(r.encryptionInfo);const i=r.encryptionInfo;y(i.defaultKid!==null);const s=i.defaultKid;let a;const o=r.demuxer.decryptionKeyCache.get(s);if(o)a=await o;else{if(!((c=r.demuxer.input._formatOptions.isobmff)!=null&&c.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const l=(async()=>{let u=r.demuxer.psshBoxes;if(n){u=[...u,...n.psshBoxes].filter(f=>f.keyIds===null||f.keyIds.includes(s));for(let f=0;f<u.length-1;f++)for(let h=f+1;h<u.length;h++)Hp(u[f],u[h])&&(u.splice(h,1),h--)}const d=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:u});if(!(typeof d=="string"&&d.length===32&&wS.test(d)||d instanceof Uint8Array&&d.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return d instanceof Uint8Array?d:yS(d)})();r.demuxer.decryptionKeyCache.set(s,l),a=await l}return i.scheme==="cenc"||i.scheme==="cens"?SC(a,i,e,t):CC(a,i,e,t)},SC=async(r,e,t,n)=>{const i=new Uint8Array(16);i.set(t.iv,0);const s=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async p=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:i,length:64},s,p);return new Uint8Array(m)};if(!t.subsamples)return a(n);y(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=tg(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const p of o)for(const m of p.perSubsample)c+=m.length;const l=new Uint8Array(c);let u=0;for(const p of o)for(const m of p.perSubsample)l.set(n.subarray(m.offset,m.offset+m.length),u),u+=m.length;const d=await a(l),f=new Uint8Array(n);let h=0;for(const p of o)for(const m of p.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},CC=(r,e,t,n)=>{const i=new Kp;i.init({key:r,iv:t.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(y(s!==null&&a!==null),!t.subsamples){const u=new Uint8Array(n),d=Math.floor(n.length/16);for(let f=0;f<d;f++){const h=f*16;i.in.set(n.subarray(h,h+16)),i.decrypt(),u.set(i.out,h)}return u}if(s===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(n),c=tg(t.subsamples,s,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const u of c){i.iv[0]=l.getUint32(0,!1),i.iv[1]=l.getUint32(4,!1),i.iv[2]=l.getUint32(8,!1),i.iv[3]=l.getUint32(12,!1);for(const d of u.perSubsample){const f=d.length/16;for(let h=0;h<f;h++){const p=d.offset+h*16;i.in.set(n.subarray(p,p+16)),i.decrypt(),o.set(i.out,p)}}}return o},tg=(r,e,t)=>{const n=[],i=e!==0||t!==0;let s=0;for(const a of r){s+=a.clearLen;const o=[];if(!i)a.protectedLen>0&&o.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;else{let c=a.protectedLen,l=s;for(;c>0&&!(c<16*e);){const u=16*e;o.push({offset:l,length:u}),l+=u,c-=u;const d=Math.min(16*t,c);l+=d,c-=d}s+=a.protectedLen}n.push({perSubsample:o})}return n};/*!
87 * Copyright (c) 2026-present, Vanilagy and contributors
88 *
89 * This Source Code Form is subject to the terms of the Mozilla Public
90 * License, v. 2.0. If a copy of the MPL was not distributed with this
91 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
92 */class Ll{constructor(e){this.value=e}}class zl{constructor(e){this.value=e}}class rg{constructor(e){this.value=e}}class kn{constructor(e){this.value=e}}var _;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=2
921934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(_||(_={}));const IC=[_.EBML,_.Segment],Ms=[_.SeekHead,_.Info,_.Cluster,_.Tracks,_.Cues,_.Attachments,_.Chapters,_.Tags],lo=[...IC,...Ms],ng=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,ig=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,sg=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6,BC=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)};class xC{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=ng(e)){let n=0;switch(t){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,t=ig(e)){let n=0;for(let i=t-1;i>=0;i--)this.helperView.setUint8(n++,Number(e>>BigInt(i*8)&0xffn));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,t=sg(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=BC(e)){let n=0;switch(t){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);const i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),e.size!==-1){const s=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(s,n),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??ng(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??ig(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}
92else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof Ll)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof zl)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof rg){const t=e.size??sg(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof kn){const t=Ve.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Ut(e.data)}}const Wl=8,dr=2,Yr=2*Wl,ag=r=>{if(r.remainingLength<1)return null;const e=se(r);if(r.skip(-1),e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;return r.remainingLength<t?null:t},Us=r=>{if(r.remainingLength<1)return null;const e=se(r);if(e===0)return null;let t=1,n=128;for(;(e&n)===0;)t++,n>>=1;if(r.remainingLength<t-1)return null;let i=e&n-1;for(let s=1;s<t;s++)i*=256,i+=se(r);return i},Be=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let n=0;n<e;n++)t*=256,t+=se(r);return t},PC=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let n=0;n<e;n++)t<<=8n,t+=BigInt(se(r));return t},Vl=r=>{const e=ag(r);return e===null||r.remainingLength<e?null:Be(r,e)},og=r=>{if(r.remainingLength<1)return null;if(se(r)===255)return;r.skip(-1);const t=Us(r);if(t===null)return null;if(t!==72057594037927940)return t},Kr=r=>{y(r.remainingLength>=dr);const e=Vl(r);if(e===null)return null;const t=og(r);return t===null?null:{id:e,size:t}},Qi=(r,e)=>{const t=ae(r,e);let n=0;for(;n<e&&t[n]!==0;)n+=1;return String.fromCharCode(...t.subarray(0,n))},Os=(r,e)=>{const t=ae(r,e);let n=0;for(;n<e&&t[n]!==0;)n+=1;return Jt.decode(t.subarray(0,n))},Hl=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?$I(r):LA(r)},Gl=async(r,e,t,n)=>{const i=new Set(t);let s=e;for(;n===null||s<n;){let a=r.requestSliceRange(s,dr,Yr);if(a instanceof Promise&&(a=await a),!a)break;const o=Kr(a);if(!o)break;if(i.has(o.id))return{pos:s,found:!0};Tn(o.size),s=a.filePos+o.size}return{pos:n!==null&&n>s?n:s,found:!1}},cg=async(r,e,t,n)=>{const s=new Set(t);let a=e;for(;a<n;){let o=r.requestSliceRange(a,0,Math.min(65536,n-a));if(o instanceof Promise&&(o=await o),!o||o.length<Wl)break;for(let c=0;c<o.length-Wl;c++){o.filePos=a;const l=Vl(o);if(l!==null&&s.has(l))return a;a++}}return null},Zt={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function Tn(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*!
93 * Copyright (c) 2026-present, Vanilagy and contributors
94 *
95 * This Source Code Form is subject to the terms of the Mozilla Public
96 * License, v. 2.0. If a copy of the MPL was not distributed with this
97 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
98 */const lg=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const n=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(", ")}"`}return t};/*!
99 * Copyright (c) 2026-present, Vanilagy and contributors
100 *
101 * This Source Code Form is subject to the terms of the Mozilla Public
102 * License, v. 2.0. If a copy of the MPL was not distributed with this
103 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
104 */var qr;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(qr||(qr={}));var uo;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(uo||(uo={}));var Ns;
104(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(Ns||(Ns={}));const Yl=[{id:_.SeekHead,flag:"seekHeadSeen"},{id:_.Info,flag:"infoSeen"},{id:_.Tracks,flag:"tracksSeen"},{id:_.Cues,flag:"cuesSeen"}],ug=10*2**20;class vC extends Vr{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(n=>n.getDecoderConfig().then(i=>(i==null?void 0:i.codec)??null)));return lg({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(i=>{var s;return((s=i.info)==null?void 0:s.type)==="video"})),hasAudio:this.segments.some(n=>n.tracks.some(i=>{var s;return((s=i.info)==null?void 0:s.type)==="audio"})),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,dr,Yr);if(t instanceof Promise&&(t=await t),!t)break;const n=Kr(t);if(!n)break;const i=n.id;let s=n.size;const a=t.filePos;if(i===_.EBML){Tn(s);let o=this.reader.requestSlice(a,s);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(i===_.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(i===_.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Gl(this.reader,a,lo,this.reader.fileSize)).pos-a);const o=tt(this.segments);o&&(o.elementEndPos=a+s)}Tn(s),e=a+s}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(n,dr,Yr);if(o instanceof Promise&&(o=await o),!o)break;const c=n,l=Kr(o);if(!l||!Ms.includes(l.id)&&l.id!==_.Void){const p=await cg(this.reader,c,Ms,Math.min(this.currentSegment.elementEndPos??1/0,c+ug));if(p){n=p;continue}else break}const{id:u,size:d}=l,f=o.filePos,h=Yl.findIndex(p=>p.id===u);if(h!==-1){const p=Yl[h].flag;this.currentSegment[p]=!0,Tn(d);let m=this.reader.requestSlice(f,d);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(u===_.Tags||u===_.Attachments){u===_.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Tn(d);let p=this.reader.requestSlice(f,d);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}else if(u===_.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;n=f+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Yl.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,dr,Yr);if(l instanceof Promise&&(l=await l),!l)continue;const u=Kr(l);if(!u)continue;const{id:d,size:f}=u;if(d!==c.id)continue;Tn(f),this.currentSegment[c.flag]=!0;let h=this.reader.requestSlice(l.filePos,f);h instanceof Promise&&(h=await h),h&&this.readContiguousElements(h)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const i=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=i.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){const l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let s=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,s=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,t){var d;if(((d=t.lastReadCluster)==null?void 0:d.elementStartPos)===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,dr,Yr);n instanceof Promise&&(n=await n),y(n);const i=e,s=Kr(n);y(s);const a=s.id;y(a===_.Cluster);let o=s.size;const c=n.filePos;o===void 0&&(o=(await Gl(this.reader,c,lo,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const u={segment:t,elementStartPos:i,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const f=this.readContiguousElements(l,lo);u.elementEndPos=f}for(const[,f]of u.trackData){const h=f.track;y(f.blocks.length>0);let p=!1;for(let w=0;w<f.blocks.length;w++){const b=f.blocks[w];b.timestamp+=u.timestamp,p||(p=b.lacing!==qr.None)}f.presentationTimestamps=f.blocks.map((w,b)=>({timestamp:w.timestamp,blockIndex:b})).sort((w,b)=>w.timestamp-b.timestamp);for(let w=0;w<f.presentationTimestamps.length;w++){const b=f.presentationTimestamps[w],k=f.blocks[b.blockIndex];if(f.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(f.firstKeyFrameTimestamp=k.timestamp),w<f.presentationTimestamps.length-1){const S=f.presentationTimestamps[w+1];k.duration=S.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===qr.None&&(k.duration=h.defaultDuration)}p&&(this.expandLacedBlocks(f.blocks,h),f.presentationTimestamps=f.blocks.map((w,b)=>({timestamp:w.timestamp,blockIndex:b})).sort((w,b)=>w.timestamp-b.timestamp));const m=f.blocks[f.presentationTimestamps[0].blockIndex],A=f.blocks[tt(f.presentationTimestamps).blockIndex];f.startTimestamp=m.timestamp,f.endTimestamp=A.timestamp+A.duration;const g=Me(h.clusterPositionCache,f.startTimestamp,w=>w.startTimestamp);(g===-1||h.clusterPositionCache[g].elementStartPos!==i)&&h.clusterPositionCache.splice(g+1,0,{elementStartPos:u.elementStartPos,startTimestamp:f.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){const i=e.segment.tracks.find(s=>s.id===t);if(!i)return null;n={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(i.lacing===qr.None)continue;i.decoded||(i.data=this.decodeBlockData(t,i.data),i.decoded=!0);const s=Nt.tempFromBytes(i.data),a=[],o=se(s)+1;switch(i.lacing){case qr.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=se(s);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case qr.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case qr.Ebml:{const l=Us(s);y(l!==null);let u=l;a.push(u);let d=u;for(let f=1;f<o-1;f++){const h=s.bufferPos,p=Us(s);y(p!==null);const m=p,g=(1<<(s.bufferPos-h)*7-1)-1,w=m-g;u+=w,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:y(!1)}y(a.length===o),e.splice(n,1);const c=i.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){const u=a[l],d=ae(s,u),f=i.timestamp+c*l/o,h=c/o;e.splice(n+l,0,{timestamp:f,duration:h,isKeyFrame:i.isKeyFrame,data:d,lacing:qr.None,decoded:!0,mainAdditional:i.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===_.Tags&&!e.tagsSeen)){if(!(t.id===_.Attachments&&!e.attachmentsSeen))continue}let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,dr,Yr);if(n instanceof Promise&&(n=await n),!n)continue;const i=Kr(n);if(!i||i.id!==t.id)continue;const{size:s}=i;Tn(s),y(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,s);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===_.Tags?e.tagsSeen=!0:t.id===_.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=dr;){const n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){var o,c,l,u,d,f,h,p,m,A,g,w,b,k,S,x,B,I,C,v,R,M,z,W,H,U,j,ce,ee,fe,he,G,ue,we,_e,Ye,xe,ne,Pe,Ee,me,Fe,Qe,ze,T,V;const n=Kr(e);
104if(!n||t&&t.includes(n.id))return!1;const{id:i,size:s}=n,a=e.filePos;switch(Tn(s),i){case _.DocType:this.isWebM=Qi(e,s)==="webm";break;case _.Seek:{if(!this.currentSegment)break;const F={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(F),this.readContiguousElements(e.slice(a,s)),(F.id===-1||F.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case _.SeekID:{const F=(o=this.currentSegment)==null?void 0:o.seekEntries[this.currentSegment.seekEntries.length-1];if(!F)break;F.id=Be(e,s)}break;case _.SeekPosition:{const F=(c=this.currentSegment)==null?void 0:c.seekEntries[this.currentSegment.seekEntries.length-1];if(!F)break;F.segmentPosition=Be(e,s)}break;case _.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Be(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case _.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Hl(e,s)}break;case _.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Lr,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(F=>{var O;return((O=F.data)==null?void 0:O.type)!=="decompress"||F.scope!==uo.Block||F.data.algorithm!==Ns.HeaderStripping})&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const F=this.currentTrack.codecId.indexOf("/"),O=F===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,F);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const N=this.currentTrack.info.displayWidth*this.currentTrack.info.height,X=this.currentTrack.info.displayHeight*this.currentTrack.info.width;N>0&&X>0&&(N>X?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*N/X):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*X/N))}this.currentTrack.codecId===Zt.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Zt.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):O===Zt.vp8?this.currentTrack.info.codec="vp8":O===Zt.vp9?this.currentTrack.info.codec="vp9":O===Zt.av1&&(this.currentTrack.info.codec="av1");const K=this.currentTrack;this.currentTrack.trackBacking=new _C(K),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){O===Zt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Zt.mp3?this.currentTrack.info.codec="mp3":O===Zt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Fi):O===Zt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):O===Zt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):O===Zt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):O===Zt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const K=this.currentTrack;this.currentTrack.trackBacking=new FC(K),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case _.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Be(e,s)}break;
104case _.TrackType:{if(!this.currentTrack)break;const F=Be(e,s);F===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:F===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case _.FlagEnabled:{if(!this.currentTrack)break;Be(e,s)||(this.currentTrack=null)}break;case _.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Be(e,s)}break;case _.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Be(e,s)}break;case _.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Be(e,s)}break;case _.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Be(e,s)}break;case _.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Be(e,s)}break;case _.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Be(e,s)}break;case _.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Qi(e,s)}break;case _.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=ae(e,s)}break;case _.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Be(e,s)}break;case _.Name:{if(!this.currentTrack)break;this.currentTrack.name=Os(e,s)}break;case _.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Qi(e,s),Cs(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Bt)}break;case _.LanguageBCP47:{if(!this.currentTrack)break;const O=Qi(e,s).split("-")[0];O?this.currentTrack.languageCode=O:this.currentTrack.languageCode=Bt,this.currentTrack.hasLanguageBcp47=!0}break;case _.Video:{if(((u=(l=this.currentTrack)==null?void 0:l.info)==null?void 0:u.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case _.PixelWidth:{if(((f=(d=this.currentTrack)==null?void 0:d.info)==null?void 0:f.type)!=="video")break;this.currentTrack.info.width=Be(e,s)}break;case _.PixelHeight:{if(((p=(h=this.currentTrack)==null?void 0:h.info)==null?void 0:p.type)!=="video")break;this.currentTrack.info.height=Be(e,s)}break;case _.DisplayWidth:{if(((A=(m=this.currentTrack)==null?void 0:m.info)==null?void 0:A.type)!=="video")break;this.currentTrack.info.displayWidth=Be(e,s)}break;case _.DisplayHeight:{if(((w=(g=this.currentTrack)==null?void 0:g.info)==null?void 0:w.type)!=="video")break;this.currentTrack.info.displayHeight=Be(e,s)}break;case _.DisplayUnit:{if(((k=(b=this.currentTrack)==null?void 0:b.info)==null?void 0:k.type)!=="video")break;this.currentTrack.info.displayUnit=Be(e,s)}break;case _.AlphaMode:{if(((x=(S=this.currentTrack)==null?void 0:S.info)==null?void 0:x.type)!=="video")break;this.currentTrack.info.alphaMode=Be(e,s)===1}break;case _.Colour:{if(((I=(B=this.currentTrack)==null?void 0:B.info)==null?void 0:I.type)!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,s))}break;case _.MatrixCoefficients:{if(((v=(C=this.currentTrack)==null?void 0:C.info)==null?void 0:v.type)!=="video"||!this.currentTrack.info.colorSpace)break;const F=Be(e,s),O=Wa[F]??null;this.currentTrack.info.colorSpace.matrix=O}break;case _.Range:{if(((M=(R=this.currentTrack)==null?void 0:R.info)==null?void 0:M.type)!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=Be(e,s)===2}break;case _.TransferCharacteristics:{if(((W=(z=this.currentTrack)==null?void 0:z.info)==null?void 0:W.type)!=="video"||!this.currentTrack.info.colorSpace)break;const F=Be(e,s),O=za[F]??null;this.currentTrack.info.colorSpace.transfer=O}break;case _.Primaries:{if(((U=(H=this.currentTrack)==null?void 0:H.info)==null?void 0:U.type)!=="video"||!this.currentTrack.info.colorSpace)break;const F=Be(e,s),O=La[F]??null;this.currentTrack.info.colorSpace.primaries=O}break;case _.Projection:{if(((ce=(j=this.currentTrack)==null?void 0:j.info)==null?void 0:ce.type)!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case _.ProjectionPoseRoll:{if(((fe=(ee=this.currentTrack)==null?void 0:ee.info)==null?void 0:fe.type)!=="video")break;const O=-Hl(e,s);try{this.currentTrack.info.rotation=Ti(O)}catch{}}break;case _.Audio:{if(((G=(he=this.currentTrack)==null?void 0:he.info)==null?void 0:G.type)!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case _.SamplingFrequency:{if(((we=(ue=this.currentTrack)==null?void 0:ue.info)==null?void 0:we.type)!=="audio")break;this.currentTrack.info.sampleRate=Hl(e,s)}break;case _.Channels:{if(((Ye=(_e=this.currentTrack)==null?void 0:_e.info)==null?void 0:Ye.type)!=="audio")break;this.currentTrack.info.numberOfChannels=Be(e,s)}break;case _.BitDepth:{if(((ne=(xe=this.currentTrack)==null?void 0:xe.info)==null?void 0:ne.type)!=="audio")break;this.currentTrack.info.bitDepth=Be(e,s)}break;case _.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case _.CueTime:this.currentCueTime=Be(e,s);break;case _.CueTrackPositions:{if(this.currentCueTime===null)break;y(this.currentSegment);const F={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(F),this.readContiguousElements(e.slice(a,s)),(F.trackId===-1||F.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case _.CueTrack:{const F=(Pe=this.currentSegment)==null?void 0:Pe.cuePoints[this.currentSegment.cuePoints.length-1];if(!F)break;F.trackId=Be(e,s)}break;case _.CueClusterPosition:{const F=(Ee=this.currentSegment)==null?void 0:Ee.cuePoints[this.currentSegment.cuePoints.length-1];if(!F)break;y(this.currentSegment),F.clusterPosition=this.currentSegment.dataStartPos+Be(e,s)}break;case _.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Be(e,s)}break;case _.SimpleBlock:{if(!this.currentCluster)break;const F=Us(e);if(F===null)break;const O=this.getTrackDataInCluster(this.currentCluster,F);if(!O)break;const K=Pu(e),N=se(e),X=N>
104>1&3;let re=!!(N&128);((me=O.track.info)==null?void 0:me.type)==="audio"&&O.track.info.codec&&(re=!0);const oe=ae(e,s-(e.filePos-a)),ie=O.track.decodingInstructions.length>0;O.blocks.push({timestamp:K,duration:0,isKeyFrame:re,data:oe,lacing:X,decoded:!ie,mainAdditional:null})}break;case _.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case _.Block:{if(!this.currentCluster)break;const F=Us(e);if(F===null)break;const O=this.getTrackDataInCluster(this.currentCluster,F);if(!O)break;const K=Pu(e),X=se(e)>>1&3,re=ae(e,s-(e.filePos-a)),oe=O.track.decodingInstructions.length>0;this.currentBlock={timestamp:K,duration:0,isKeyFrame:!0,data:re,lacing:X,decoded:!oe,mainAdditional:null},O.blocks.push(this.currentBlock)}break;case _.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case _.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case _.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=ae(e,s)}break;case _.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Be(e,s)}break;case _.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Be(e,s)}break;case _.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case _.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case _.Targets:this.readContiguousElements(e.slice(a,s));break;case _.TargetTypeValue:Be(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case _.TagTrackUID:case _.TagEditionUID:case _.TagChapterUID:case _.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case _.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case _.TagName:this.currentSimpleTagName=Os(e,s);break;case _.TagString:{if(!this.currentSimpleTagName)break;const F=Os(e,s);this.processTagValue(this.currentSimpleTagName,F)}break;case _.TagBinary:{if(!this.currentSimpleTagName)break;const F=ae(e,s);this.processTagValue(this.currentSimpleTagName,F)}break;case _.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,s));const F=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(F.raw??(F.raw={}),F.raw[this.currentAttachedFile.fileUid.toString()]=new ja(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),(Fe=this.currentAttachedFile.fileMediaType)!=null&&Fe.startsWith("image/")&&this.currentAttachedFile.fileData){const O=this.currentAttachedFile.fileName;let K="unknown";if(O){const N=O.toLowerCase();N.startsWith("cover.")?K="coverFront":N.startsWith("back.")&&(K="coverBack")}F.images??(F.images=[]),F.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:K,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case _.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=PC(e,s)}break;case _.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Os(e,s)}break;
104case _.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Qi(e,s)}break;case _.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=ae(e,s)}break;case _.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Os(e,s)}break;case _.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((F,O)=>O.order-F.order)}break;case _.ContentEncoding:this.currentDecodingInstruction={order:0,scope:uo.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case _.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Be(e,s)}break;case _.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Be(e,s)}break;case _.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ns.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case _.ContentCompAlgo:{if(((ze=(Qe=this.currentDecodingInstruction)==null?void 0:Qe.data)==null?void 0:ze.type)!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Be(e,s)}break;case _.ContentCompSettings:{if(((V=(T=this.currentDecodingInstruction)==null?void 0:T.data)==null?void 0:V.type)!=="decompress")break;this.currentDecodingInstruction.data.settings=ae(e,s)}break;case _.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let n=t;for(const i of e.decodingInstructions)switch(y(i.data),i.data.type){case"decompress":switch(i.data.algorithm){case Ns.HeaderStripping:if(i.data.settings&&i.data.settings.length>0){const s=i.data.settings,a=new Uint8Array(s.length+n.length);a.set(s,0),a.set(n,s.length),n=a}break}break}return n}processTagValue(e,t){var i,s;if(!((i=this.currentSegment)!=null&&i.metadataTags))return;const n=this.currentSegment.metadataTags;if(n.raw??(n.raw={}),(s=n.raw)[e]??(s[e]=t),typeof t=="string")switch(e.toLowerCase()){case"title":n.title??(n.title=t);break;case"description":n.description??(n.description=t);break;case"artist":n.artist??(n.artist=t);break;case"album":n.album??(n.album=t);break;case"album_artist":n.albumArtist??(n.albumArtist=t);break;case"genre":n.genre??(n.genre=t);break;case"comment":n.comment??(n.comment=t);break;case"lyrics":n.lyrics??(n.lyrics=t);break;case"date":{const a=new Date(t);Number.isNaN(a.getTime())||(n.date??(n.date=a))}break;case"track_number":case"part_number":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(n.trackNumber??(n.trackNumber=o)),c&&Number.isInteger(c)&&c>0&&(n.tracksTotal??(n.tracksTotal=c))}break;case"disc_number":case"disc":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(n.discNumber??(n.discNumber=o)),c&&Number.isInteger(c)&&c>0&&(n.discsTotal??(n.discsTotal=c))}break}}}class dg{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let n=0;for(const i of e.segments)for(const s of i.tracks)if(s.trackBacking.getType()===t&&n++,s===this.internalTrack)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const n=await this.getFirstPacket({metadataOnly:!0});return t+=(n==null?void 0:n.timestamp)??0,t}
104async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ss(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=Me(s.presentationTimestamps,n,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextPacket(e,t){const n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){const s=i.trackData.get(this.internalTrack.id);if(n.blockIndex+1<s.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(i.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const n=this.intoTimescale(e);return this.performClusterLookup(null,i=>{const s=i.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=Va(s.presentationTimestamps,l=>s.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=n),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&n<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},n,n,t)}async getNextKeyPacket(e,t){const n=this.packetToClusterLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(n.cluster,i=>{if(i===n.cluster){const a=i.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>n.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const s=i.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){const a=s.blocks.findIndex(o=>o.isKeyFrame);return y(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){var d;if(t===-1)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];y(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0);const a=n.metadataOnly?$t:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,c=s.duration/this.internalTrack.segment.timestampFactor,l={};s.mainAdditional&&((d=this.internalTrack.info)==null?void 0:d.type)==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=n.metadataOnly?$t:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);const u=new He(a,s.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,s.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,n,i,s){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:g,correctBlockFound:w}=t(e);if(w)return this.fetchPacketInCluster(e,g,s);g!==-1&&(l=e,u=g)}const d=Me(this.internalTrack.cuePoints,n,g=>g.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=Me(this.internalTrack.clusterPositionCache,n,g=>g.startTimestamp),p=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max((f==null?void 0:f.clusterPosition)??0,(p==null?void 0:p.elementStartPos)??0)||null;let A;for(e?m===null||e.elementStartPos>=m?(A=e.elementEndPos,c=e):A=m:A=m??o.clusterSeekStartPos;o.elementEndPos===null||A<=o.elementEndPos-dr;){if(c){const I=c.trackData.get(this.internalTrack.id);if(I&&I.startTimestamp>i)break}let g=a.reader.requestSliceRange(A,dr,Yr);if(g instanceof Promise&&(g=await g),!g)break;const w=A,b=Kr(g);if(!b||!Ms.includes(b.id)&&b.id!==_.Void){const I=await cg(a.reader,w,Ms,Math.min(o.elementEndPos??1/0,w+ug));if(I){A=I;continue}else break}const k=b.id;let S=b.size;const x=g.filePos;if(k===_.Cluster){c=await a.readCluster(w,o),S=c.elementEndPos-x;const{blockIndex:I,correctBlockFound:C}=t(c);if(C)return this.fetchPacketInCluster(c,I,s);I!==-1&&(l=c,u=I)}S===void 0&&(y(k!==_.Cluster),S=(await Gl(a.reader,x,lo,o.elementEndPos)).pos-x);const B=x+S;if(o.elementEndPos===null){let I=a.reader.requestSliceRange(B,dr,Yr);if(I instanceof Promise&&(I=await I),!I)break;if(Vl(I)===_.Segment){o.elementEndPos=B;break}}A=B}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const g=this.internalTrack.cuePoints[d-1];y(!g||g.time<f.time);const w=(g==null?void 0:g.time)??-1/0;return this.performClusterLookup(null,t,w,i,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class _C extends dg{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){var e,t,n,i;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(n=this.internalTrack.info.colorSpace)==null?void 0:n.matrix,fullRange:(i=this.internalTrack.info.colorSpace)==null?void 0:i.fullRange}}
104async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const n={codec:bl({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Pl(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?_l(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Rp(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Mp(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class FC extends dg{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:El({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}/*!
105 * Copyright (c) 2026-present, Vanilagy and contributors
106 *
107 * This Source Code Form is subject to the terms of the Mozilla Public
108 * License, v. 2.0. If a copy of the MPL was not distributed with this
109 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
110 */const Kl=async(r,e,t,n=null)=>{let s=e;for(;t===null||s<t;){const a=t!==null?Math.min(65536,t-s):65536;let o=r.requestSliceRange(s,Vn,a);if(o instanceof Promise&&(o=await o),!o||o.length<Vn)break;for(;o.remainingLength>=Vn;){const c=o.filePos,l=q(o),u=r.fileSize!==null?r.fileSize-s:null,d=eo(l,u);if(d.header&&(!n||d.header.sampleRate===n.sampleRate&&d.header.mpegVersionId===n.mpegVersionId&&d.header.layer===n.layer&&Ds(d.header.channel)===Ds(n.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};/*!
111 * Copyright (c) 2026-present, Vanilagy and contributors
112 *
113 * This Source Code Form is subject to the terms of the Mozilla Public
114 * License, v. 2.0. If a copy of the MPL was not distributed with this
115 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
116 */class RC extends Vr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new zn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new DC(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,$r);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=ti(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Kl(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const n=Za(t.mpegVersionId,t.channel);let i=this.reader.requestSlice(e.startPos+n,4);if(i instanceof Promise&&(i=await i),i){const o=q(i);if(o===$a||o===Tl){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(l instanceof Promise&&(l=await l),l){const u=ae(l,12),d=Ae(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&Hn.FrameCount?d.getUint32(4,!1):null,fileSize:f&Hn.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,n=!1;for(;;){let i=this.reader.requestSlice(t,$r);
116if(i instanceof Promise&&(i=await i),!i)break;const s=ti(i);if(!s)break;n=!0;let a=this.reader.requestSlice(i.filePos,s.size);if(a instanceof Promise&&(a=await a),!a)break;vu(a,s,this.metadataTags),t=i.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Fo){let i=this.reader.requestSlice(this.reader.fileSize-Fo,Fo);i instanceof Promise&&(i=await i),y(i),ct(i,3)==="TAG"&&ZI(i,this.metadataTags)}return this.metadataTags}finally{e()}}}class DC{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(y(e.firstFrameHeader!==null),y(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const t=$S(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}
116async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Bt}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.firstFrameHeader),Ds(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Lr}}async getDecoderConfig(){return y(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Ds(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=$t;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ae(s,n.dataSize)}return new He(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const n=await this.demuxer.readingMutex.acquire();try{const i=Ts(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){const n=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Me(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
117 * Copyright (c) 2026-present, Vanilagy and contributors
118 *
119 * This Source Code Form is subject to the terms of the Mozilla Public
120 * License, v. 2.0. If a copy of the MPL was not distributed with this
121 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
122 */const ql=1399285583,MC=79764919,fg=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^MC:e<<1;fg[r]=e>>>0&4294967295}const hg=r=>{const e=Ae(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let n=0;for(let i=0;i<r.length;i++){const s=r[i];n=(n<<8^fg[n>>>24^s])>>>0}return e.setUint32(22,t,!0),n},mg=(r,e,t)=>{let n=0,i=null;if(r.length>0)if(e.codec==="vorbis"){y(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<CS(s-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t;const u=e.vorbisInfo.modeBlockflags[c];if(i=e.vorbisInfo.blocksizes[u],u===1){const d=(o|1)+1,f=r[0]&d?1:0;l=e.vorbisInfo.blocksizes[f]}n=l!==null?l+i>>2:0}else e.codec==="opus"&&(n=hC(r).durationInSamples);return{durationInSamples:n,vorbisBlockSize:i}},pg=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*!
123 * Copyright (c) 2026-present, Vanilagy and contributors
124 *
125 * This Source Code Form is subject to the terms of the Mozilla Public
126 * License, v. 2.0. If a copy of the MPL was not distributed with this
127 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
128 */const Kn=27,Li=282,gg=Li+65025,Qs=r=>{const e=r.filePos;if(ji(r)!==ql)return null;r.skip(1);const n=se(r),i=JI(r),s=ji(r),a=ji(r),o=ji(r),c=se(r),l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=se(r);const u=27+c,d=l.reduce((h,p)=>h+p,0),f=u+d;return{headerStartPos:e,totalSize:f,dataStartPos:e+u,dataSize:d,headerType:n,granulePosition:i,serialNumber:s,sequenceNumber:a,checksum:o,lacingValues:l}},UC=(r,e)=>{for(;r.filePos<e-3;){const t=ji(r),n=t&255,i=t>>>8&255,s=t>>>16&255,a=t>>>24&255,o=79;if(!(n!==o&&i!==o&&s!==o&&a!==o)){if(r.skip(-4),t===ql)return!0;r.skip(1)}}return!1};/*!
129 * Copyright (c) 2026-present, Vanilagy and contributors
130 *
131 * This Source Code Form is subject to the terms of the Mozilla Public
132 * License, v. 2.0. If a copy of the MPL was not distributed with this
133 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
134 */class OC extends Vr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Kn,Li);if(t instanceof Promise&&(t=await t),!t)break;const n=Qs(t);if(!n||!!!(n.headerType&2))break;
134this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(const t of this.bitstreams){const n=await this.readPacket(t.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,t):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,t),t.codecInfo.codec!==null&&this.trackBackings.push(new NC(t,this)))}})())}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;const i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||(n=await this.findNextPacketStart(i),!n))return;const s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||i.data[0]!==3||s.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(i.data.length);const c=new Uint8Array(1+a.length+e.data.length+i.data.length+s.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(i.data,1+a.length+e.data.length),c.set(s.data,1+a.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=s;const l=Ae(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const u=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(u&15),1<<(u>>4)],modeBlockflags:Up(s.data).modeBlockflags},Fl(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const n=await this.findNextPacketStart(e);if(!n)return;const i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const s=so(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=Fi,t.codecInfo.opusInfo={preSkip:s.preSkip},Fl(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){y(t<e.lacingValues.length);let n=0;for(let d=0;d<t;d++)n+=e.lacingValues[d];let i=e,s=n,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(i.dataStartPos,i.dataSize);d instanceof Promise&&(d=await d),y(d);const f=ae(d,i.dataSize);for(;;){if(a===i.lacingValues.length){o.push(f.subarray(n,s));break}const p=i.lacingValues[a];if(s+=p,p<255){o.push(f.subarray(n,s));break e}a++}let h=i.headerStartPos+i.totalSize;for(;;){let p=this.reader.requestSliceRange(h,Kn,Li);if(p instanceof Promise&&(p=await p),!p)return null;const m=Qs(p);if(!m)return null;if(i=m,i.serialNumber===e.serialNumber)break;h=i.headerStartPos+i.totalSize}n=0,s=0,a=0}const c=o.reduce((d,f)=>d+f.length,0);if(c===0)return null;const l=new Uint8Array(c);let u=0;for(let d=0;d<o.length;d++){const f=o[d];l.set(f,u),u+=f.length}return{data:l,endPage:i,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(n,Kn,Li);if(i instanceof Promise&&(i=await i),!i)return null;const s=Qs(i);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return pg({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class NC{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new zn,this.internalSampleRate=e.codecInfo.codec==="opus"?Fi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return y(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
134async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Bt}getDisposition(){return{...Lr,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:s}=mg(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new He(n.metadataOnly?$t:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),a}async getFirstPacket(e){y(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec==="opus"&&(y(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);const i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const n=this.encodedPacketToMetadata.get(e);if(!n)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(n.packet);if(!i)return null;const s=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:s,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const n=Ss(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let s=i.startPage,a=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<a;){const w=s.headerStartPos,b=Math.floor((w+a)/2);let k=b;for(;;){const S=Math.min(k+gg,a-Kn);let x=this.demuxer.reader.requestSlice(k,S-k);if(x instanceof Promise&&(x=await x),y(x),!UC(x,S)){a=b+Kn;continue e}let I=this.demuxer.reader.requestSliceRange(x.filePos,Kn,Li);I instanceof Promise&&(I=await I),y(I);const C=Qs(I);y(C);let v=!1;if(C.serialNumber===this.bitstream.serialNumber)v=!0;else{let M=this.demuxer.reader.requestSlice(C.headerStartPos,C.totalSize);M instanceof Promise&&(M=await M),y(M);const z=ae(M,C.totalSize);v=hg(z)===C.checksum}if(!v){k=C.headerStartPos+4;continue}if(v&&C.serialNumber!==this.bitstream.serialNumber){k=C.headerStartPos+C.totalSize;continue}if(C.granulePosition===-1){k=C.headerStartPos+C.totalSize;continue}this.granulePositionToTimestampInSamples(C.granulePosition)>n?a=C.headerStartPos:(s=C,o.push(C));continue e}}let c=i.startPage;for(const w of o){if(w.granulePosition===s.granulePosition)break;(!c||w.headerStartPos>c.headerStartPos)&&(c=w)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){const w=l.headerStartPos+l.totalSize;let b=this.demuxer.reader.requestSliceRange(w,Kn,Li);b instanceof Promise&&(b=await b),y(b);const k=Qs(b);y(k),l=k,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}y(l.granulePosition!==-1);let d=null,f,h,p=l,m=0;if(l.headerStartPos===i.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{f=0,h=!1;for(let k=l.lacingValues.length-1;k>=0;k--)if(l.lacingValues[k]<255){d=k+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const w={data:$t,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(w)){const k=wg(u,l,d);
134y(k);const S=Ag(u,k.page,k.segmentIndex);S&&(l=S.page,d=S.segmentIndex)}else for(;;){const k=wg(u,l,d);if(!k)break;const S=Ag(u,k.page,k.segmentIndex);if(!S)break;if(l=S.page,d=S.segmentIndex,k.page.headerStartPos!==p.headerStartPos){p=k.page,m=k.segmentIndex;break}}}let A=null,g=null;for(;l!==null;){y(d!==null);const w=await this.demuxer.readPacket(l,d);if(!w)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let S=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f,vorbisLastBlocksize:(g==null?void 0:g.vorbisBlockSize)??null},t);y(S);let x=this.encodedPacketToMetadata.get(S);if(y(x),!h&&w.endPage.headerStartPos===p.headerStartPos&&w.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,S=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f-x.durationInSamples,vorbisLastBlocksize:(g==null?void 0:g.vorbisBlockSize)??null},t),y(S),x=this.encodedPacketToMetadata.get(S),y(x)):f+=x.durationInSamples,A=S,g=x,h&&(Math.max(f,0)>n||Math.max(x.timestampInSamples,0)===n))break}const k=await this.demuxer.findNextPacketStart(w);if(!k)break;l=k.startPage,d=k.startSegmentIndex}return A}async getPacketSequential(e,t){const n=await this.sequentialScanMutex.acquire();try{const i=Ss(e*this.internalSampleRate);e=i/this.internalSampleRate;const s=Me(this.sequentialScanCache,i,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const l=this.encodedPacketToMetadata.get(a);y(l),this.sequentialScanCache.length>0&&y(tt(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ag=(r,e,t)=>{let n=e,i=t;e:for(;;){for(i--,i;i>=0;i--)if(n.lacingValues[i]<255){i++;break e}if(y(i===-1),!(n.headerType&1)){i=0;break}const a=ap(r,o=>o.headerStartPos<n.headerStartPos);if(!a)return null;n=a,i=n.lacingValues.length}if(y(i!==-1),i===n.lacingValues.length){const s=r[r.indexOf(n)+1];y(s),n=s,i=0}return{page:n,segmentIndex:i}},wg=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const n=ap(r,i=>i.headerStartPos<e.headerStartPos);return n?{page:n,segmentIndex:n.lacingValues.length-1}:null};/*!
135 * Copyright (c) 2026-present, Vanilagy and contributors
136 *
137 * This Source Code Form is subject to the terms of the Mozilla Public
138 * License, v. 2.0. If a copy of the MPL was not distributed with this
139 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
140 */var er;(function(r){r[r.PCM=1]="PCM",r[r.IEEE_FLOAT=3]="IEEE_FLOAT",r[r.ALAW=6]="ALAW",r[r.MULAW=7]="MULAW",r[r.EXTENSIBLE=65534]="EXTENSIBLE"})(er||(er={}));class QC extends Vr{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),y(e);const t=ct(e,4),n=t!=="RIFX",i=t==="RF64",s=In(e,n);let a=i?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ct(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,u=e.filePos;for(;a===null||u<a;){let f=this.reader.requestSlice(u,8);if(f instanceof Promise&&(f=await f),!f)break;const h=ct(f,4),p=In(f,n),m=f.filePos;if(i&&c===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(m,p,n);else if(h==="data"){if(l??(l=p),this.dataStart=f.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let A=this.reader.requestSlice(m,p);if(A instanceof Promise&&(A=await A),!A)break;const g=QA(A,n);l=QA(A,n),a=Math.min(g+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,p,n):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,p);u=m+p+(p&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new LC(this))})())}async parseFmtChunk(e,t,n){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let s=Zs(i,n);const a=Zs(i,n),o=In(i,n);i.skip(4);const c=Zs(i,n);let l;if(t===14?l=8:l=Zs(i,n),t>=18&&s!==357){const u=Zs(i,n),d=t-18;if(Math.min(d,u)>=22&&s===er.EXTENSIBLE){i.skip(6);const h=ae(i,16);s=h[0]|h[1]<<8}}(s===er.MULAW||s===er.ALAW)&&(l=8),this.audioInfo={format:s,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}
140}async parseListChunk(e,t,n){var o,c,l,u,d,f,h,p,m,A,g;let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const s=ct(i,4);if(s!=="INFO"&&s!=="INF0")return;let a=i.filePos;for(;a<=e+t-8;){i.filePos=a;const w=ct(i,4),b=In(i,n),k=ae(i,b);let S=0;for(let B=0;B<k.length&&k[B]!==0;B++)S++;const x=String.fromCharCode(...k.subarray(0,S));switch((o=this.metadataTags).raw??(o.raw={}),this.metadataTags.raw[w]=x,w){case"INAM":case"TITL":(c=this.metadataTags).title??(c.title=x);break;case"TIT3":(l=this.metadataTags).description??(l.description=x);break;case"IART":(u=this.metadataTags).artist??(u.artist=x);break;case"IPRD":(d=this.metadataTags).album??(d.album=x);break;case"IPRT":case"ITRK":case"TRCK":{const B=x.split("/"),I=Number.parseInt(B[0],10),C=B[1]&&Number.parseInt(B[1],10);Number.isInteger(I)&&I>0&&((f=this.metadataTags).trackNumber??(f.trackNumber=I)),C&&Number.isInteger(C)&&C>0&&((h=this.metadataTags).tracksTotal??(h.tracksTotal=C))}break;case"ICRD":case"IDIT":{const B=new Date(x);Number.isNaN(B.getTime())||((p=this.metadataTags).date??(p.date=B))}break;case"YEAR":{const B=Number.parseInt(x,10);Number.isInteger(B)&&B>0&&((m=this.metadataTags).date??(m.date=new Date(B,0,1)))}break;case"IGNR":case"GENR":(A=this.metadataTags).genre??(A.genre=x);break;case"ICMT":case"CMNT":case"COMM":(g=this.metadataTags).comment??(g.comment=x);break}a+=8+b+(b&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;const i=ti(n);if(i){const s=t-$r;if(i.size=Math.min(i.size,s),i.size>0){const a=n.slice(e+$r,i.size);vu(a,i,this.metadataTags)}}}getCodec(){if(y(this.audioInfo),this.audioInfo.format===er.MULAW)return"ulaw";if(this.audioInfo.format===er.ALAW)return"alaw";if(this.audioInfo.format===er.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===er.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const zi=2048;class LC{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return y(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
140async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Bt}getDisposition(){return{...Lr}}async getPacketAtIndex(e,t){y(e>=0),y(this.demuxer.audioInfo);const n=e*zi*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;const i=Math.min(zi*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);if(c instanceof Promise&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=$t;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,i);c instanceof Promise&&(c=await c),y(c),s=ae(c,i)}const a=e*zi/this.demuxer.audioInfo.sampleRate,o=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new He(s,"key",a,o,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){y(this.demuxer.audioInfo);const n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/zi,(this.demuxer.dataSize-1)/(zi*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;const i=await this.getPacketAtIndex(n,t);if(i)return i;if(n===0)return null;y(this.demuxer.reader.fileSize===null);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const a=await this.getNextPacket(s,t);if(!a)break;s=a}return s}getNextPacket(e,t){y(this.demuxer.audioInfo);const n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/zi);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
141 * Copyright (c) 2026-present, Vanilagy and contributors
142 *
143 * This Source Code Form is subject to the terms of the Mozilla Public
144 * License, v. 2.0. If a copy of the MPL was not distributed with this
145 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
146 */const Ls=7,Sn=9,jr=r=>{const e=r.filePos,t=ae(r,9),n=new Ce(t);if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;const a=n.readBits(1),o=n.readBits(2)+1,c=n.readBits(4);if(c===15)return null;n.skipBits(1);const l=n.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);const u=n.readBits(13);n.skipBits(11);const d=n.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let f=null;return a===1?r.filePos-=2:f=n.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:f,startPos:e}};/*!
147 * Copyright (c) 2026-present, Vanilagy and contributors
148 *
149 * This Source Code Form is subject to the terms of the Mozilla Public
150 * License, v. 2.0. If a copy of the MPL was not distributed with this
151 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
152 */const fo=1024;class zC extends Vr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new zn,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new WC(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,$r);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=ti(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Ls,Sn);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=jr(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const n=gn[t.samplingFrequencyIndex];y(n!==void 0);const i=fo/n,s={timestamp:this.nextTimestampInSamples/n,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=fo,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let n=this.reader.requestSlice(t,$r);
152if(n instanceof Promise&&(n=await n),!n)break;const i=ti(n);if(!i)break;let s=this.reader.requestSlice(n.filePos,i.size);if(s instanceof Promise&&(s=await s),!s)break;vu(s,i,this.metadataTags),t=n.filePos+i.size}return this.metadataTags}finally{e()}}}class WC{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/fo}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Bt}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=_i[this.demuxer.firstFrameHeader.channelConfiguration];return y(e!==void 0),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=gn[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(e!==void 0),e}getDisposition(){return{...Lr}}async getDecoderConfig(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;const n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=$t;else{let s=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(s instanceof Promise&&(s=await s),!s)return null;i=ae(s,n.dataSize)}return new He(i,"key",n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const n=await this.demuxer.readingMutex.acquire();try{const i=Ts(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(i===-1)throw new Error("Packet was not created from this track.");const s=i+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{n()}}async getPacket(e,t){const n=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Me(this.demuxer.loadedSamples,e,s=>s.timestamp);if(i===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
153 * Copyright (c) 2026-present, Vanilagy and contributors
154 *
155 * This Source Code Form is subject to the terms of the Mozilla Public
156 * License, v. 2.0. If a copy of the MPL was not distributed with this
157 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
158 */const yg=r=>r===0?null:r===1?192:r>=2&&r<=5?144*2**r:r===6?"uncommon-u8":r===7?"uncommon-u16":r>=8&&r<=15?2**r:null,VC=(r,e)=>{switch(r){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},bg=r=>{let e=0;const t=new Ce(ae(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const n=[],i=e-1,s=new Ce(ae(r,i)),a=8-e-1;for(let c=0;c<a;c++)n.unshift(t.readBits(1));for(let c=0;c<i;c++)for(let l=0;l<8;l++){const u=s.readBits(1);l<2||n.unshift(u)}return n.reduce((c,l,u)=>c|l<<u,0)},Eg=(r,e)=>{if(e==="uncommon-u16")return At(r)+1;if(e==="uncommon-u8")return se(r)+1;if(typeof e=="number")return e;Ut(e),y(!1)},HC=(r,e)=>e==="uncommon-u16"?At(r):e==="uncommon-u16-10"?At(r)*10:e==="uncommon-u8"?se(r):typeof e=="number"?e:null,GC=r=>{let t=0;for(const n of r){t^=n;for(let i=0;i<8;i++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};/*!
159 * Copyright (c) 2026-present, Vanilagy and contributors
160 *
161 * This Source Code Form is subject to the terms of the Mozilla Public
162 * License, v. 2.0. If a copy of the MPL was not distributed with this
163 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
164 */class YC extends Vr{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new zn,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),y(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??(this.metadataPromise=(async()=>{var t;for(;this.reader.fileSize===null||e<this.reader.fileSize;){let n=this.reader.requestSlice(e,4);
164if(n instanceof Promise&&(n=await n),e+=4,n===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);y(n);const i=se(n),s=Jr(n),a=(i&128)!==0;switch(i&127){case Wr.STREAMINFO:{let c=this.reader.requestSlice(e,s);if(c instanceof Promise&&(c=await c),y(c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const l=ae(c,34),u=new Ce(l),d=u.readBits(16),f=u.readBits(16),h=u.readBits(24),p=u.readBits(24),m=u.readBits(20),A=u.readBits(3)+1;u.readBits(5);const g=u.readBits(36);u.skipBits(128);const w=new Uint8Array(42);w.set(new Uint8Array([102,76,97,67]),0),w.set(new Uint8Array([128,0,0,34]),4),w.set(l,8),this.audioInfo={numberOfChannels:A,sampleRate:m,totalSamples:g,minimumBlockSize:d,maximumBlockSize:f,minimumFrameSize:h,maximumFrameSize:p,description:w},this.trackBacking=new KC(this);break}case Wr.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,s);c instanceof Promise&&(c=await c),y(c),Fl(ae(c,s),this.metadataTags);break}case Wr.PICTURE:{let c=this.reader.requestSlice(e,s);c instanceof Promise&&(c=await c),y(c);const l=q(c),u=q(c),d=Jt.decode(ae(c,u)),f=q(c),h=Jt.decode(ae(c,f));c.skip(16);const p=q(c),m=ae(c,p);(t=this.metadataTags).images??(t.images=[]),this.metadataTags.images.push({data:m,mimeType:d,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:h});break}}if(e+=s,a){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame({startPos:e,isFirstPacket:t}){y(this.audioInfo);const n=6,i=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+i+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+i,u=await this.reader.requestSliceRange(e,i,l);if(!u)return null;const d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-n)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(se(u)===255){const h=u.filePos,p=se(u),m=this.blockingBit===1?249:248;if(p!==m){u.filePos=h;continue}u.skip(-2);const A=u.filePos-e,g=this.readFlacFrameHeader({slice:u,isFirstPacket:!1});if(!g){u.filePos=h;continue}if(this.blockingBit===0){if(g.num-d.num!==1){u.filePos=h;continue}}else if(g.num-d.num!==d.blockSize){u.filePos=h;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:A,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const n=e.filePos,i=ae(e,4),s=new Ce(i);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){y(t);const A=s.readBits(1);this.blockingBit=A}else if(this.blockingBit===1){if(y(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(y(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=yg(s.readBits(4));if(!o)return null;y(this.audioInfo);const c=VC(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const u=bg(e),d=Eg(e,o),f=HC(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const h=e.filePos-n,p=se(e);e.skip(-h),e.skip(-1);const m=GC(ae(e,h));return p!==m?null:{num:u,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),y(this.lastLoadedPos!==null),y(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(s),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class KC{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Bt}
164getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Lr}}async getDecoderConfig(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(y(this.demuxer.audioInfo),e<0)return null;const n=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Me(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(i===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[i],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(i,t)}}finally{n()}}async getNextPacket(e,t){const n=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const n=this.demuxer.loadedSamples[e];if(!n)return null;let i;if(t.metadataOnly)i=$t;else{let o=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;i=ae(o,n.byteSize)}y(this.demuxer.audioInfo);const s=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new He(i,"key",s,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*!
165 * Copyright (c) 2026-present, Vanilagy and contributors
166 *
167 * This Source Code Form is subject to the terms of the Mozilla Public
168 * License, v. 2.0. If a copy of the MPL was not distributed with this
169 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
170 */const wr=9e4,Wt=188,kg=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};/*!
171 * Copyright (c) 2026-present, Vanilagy and contributors
172 *
173 * This Source Code Form is subject to the terms of the Mozilla Public
174 * License, v. 2.0. If a copy of the MPL was not distributed with this
175 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
176 */const Tg="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Sg=new Set;class qC extends Vr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{const e=Wt+16+1;let t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),y(t);const n=ae(t,e);if(n[0]===71&&n[Wt]===71)this.packetOffset=0,this.packetStride=Wt;else if(n[0]===71&&n[Wt+16]===71)this.packetOffset=0,this.packetStride=Wt+16;else if(n[4]===71&&n[4+Wt+4]===71)this.packetOffset=4,this.packetStride=Wt+4;else throw new Error("Unreachable.");const i=256;this.minReferencePointByteDistance=i*this.packetStride;let s=this.packetOffset,a=null,o=!1,c=!1;for(;;){const l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;
176continue}const u=await this.readSection(s,!0,!c);if(!u)break;const d=3,f=32;let h=!1;if(!c&&u.pid!==0&&!(u.payload[0]===0&&u.payload[1]===0&&u.payload[2]===1)){const A=new Ce(u.payload),g=A.readAlignedByte();A.skipBits(8*g),h=A.readBits(8)===2}if(u.pid===0&&!o){const m=new Ce(u.payload),A=m.readAlignedByte();m.skipBits(8*A),m.skipBits(14);const g=m.readBits(10);for(m.skipBits(40);8*(g+d)-m.pos>f;){const w=m.readBits(16);m.skipBits(3);const b=m.readBits(13);if(w!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=b}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||h)&&!c){const m=new Ce(u.payload),A=m.readAlignedByte();m.skipBits(8*A),m.skipBits(12);const g=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const w=m.readBits(10);for(m.skipBits(8*w);8*(g+d)-m.pos>f;){const b=m.readBits(8);m.skipBits(3);const k=m.readBits(13);m.skipBits(6);const S=m.readBits(10),x=m.pos+8*S;let B=!1,I=!1;for(;m.pos<x;){const v=m.readBits(8),R=m.readBits(8);v===106?B=!0:(v===122||v===204)&&(I=!0),m.skipBits(8*R)}let C=null;switch(b){case 27:case 36:C={type:"video",codec:b===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let v;if(b===3||b===4)v="mp3";else if(b===15)v="aac";else if(b===129)v="ac3";else if(b===135)v="eac3";else throw new Error("Unreachable.");C={type:"audio",codec:v,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:I?C={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:B&&(C={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:Sg.has(b)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${b.toString(16)} are not currently supported.`),Sg.add(b))}C&&this.elementaryStreams.push({demuxer:this,pid:k,streamType:b,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:C,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(A=>A.pid===u.pid);e:if(m&&!m.initialized){const A=Wi(u,!0);if(!A)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=u,m.canBeTrustedWithKeyPackets=u.randomAccessIndicator===1,this.input._initInput){const b=(await this.input._initInput._getDemuxer()).elementaryStreams.find(k=>k.pid===u.pid&&k.info.codec===m.info.codec);if(b){m.info=b.info,m.initialized=!0;break e}}const g=new zs(m,A);if(m.info.type==="video"){for(;;){const w=g;if(w.suppliedPacket=null,await g.markNextPacket(),m.info.codec==="avc"){if(!g.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Pl(g.suppliedPacket.data),!m.info.avcCodecInfo)continue;const b=m.info.avcCodecInfo.sequenceParameterSets[0];y(b);const k=vl(b);m.info.width=k.displayWidth,m.info.height=k.displayHeight;const S=k.pixelAspectRatio.num,x=k.pixelAspectRatio.den;S>0&&x>0&&(S>x?(m.info.squarePixelWidth=Math.round(m.info.width*S/x),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*x/S))),m.info.colorSpace={primaries:La[k.colourPrimaries],transfer:za[k.transferCharacteristics],matrix:Wa[k.matrixCoefficients],fullRange:!!k.fullRangeFlag},m.info.reorderSize=k.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!g.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=_l(g.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const k=m.info.hevcCodecInfo.arrays.find(x=>x.nalUnitType===pt.SPS_NUT).nalUnits[0];y(k);const S=_p(k);m.info.width=S.displayWidth,m.info.height=S.displayHeight,S.pixelAspectRatio.num>S.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*S.pixelAspectRatio.num/S.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*S.pixelAspectRatio.den/S.pixelAspectRatio.num)),m.info.colorSpace
176={primaries:La[S.colourPrimaries],transfer:za[S.transferCharacteristics],matrix:Wa[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},m.info.reorderSize=S.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:bl({width:m.info.width,height:m.info.height,codec:m.info.codec,codecDescription:null,colorSpace:m.info.colorSpace,avcType:1,avcCodecInfo:m.info.avcCodecInfo,hevcCodecInfo:m.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:m.info.width,codedHeight:m.info.height,colorSpace:m.info.colorSpace},(m.info.width!==m.info.squarePixelWidth||m.info.height!==m.info.squarePixelHeight)&&(m.info.decoderConfig.displayAspectWidth=m.info.squarePixelWidth,m.info.decoderConfig.displayAspectHeight=m.info.squarePixelHeight),m.initialized=!0}else{if(await g.markNextPacket(),!g.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const w=Nt.tempFromBytes(g.suppliedPacket.data),b=jr(w);if(!b)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:b.objectType},m.info.numberOfChannels=_i[b.channelConfiguration],m.info.sampleRate=gn[b.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const w=q(Nt.tempFromBytes(g.suppliedPacket.data)),b=eo(w,g.suppliedPacket.data.byteLength);if(!b.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Ds(b.header.channel),m.info.sampleRate=b.header.sampleRate}else if(m.info.codec==="ac3"){const w=Op(g.suppliedPacket.data);if(!w)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(w.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Dl[w.acmod]+w.lfeon,m.info.sampleRate=to[w.fscod]}else if(m.info.codec==="eac3"){const w=Qp(g.suppliedPacket.data);if(!w)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const b=Lp(w);if(b===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=zp(w),m.info.sampleRate=b}else throw new Error("Unhandled.");m.info.decoderConfig={codec:El({codec:m.info.codec,codecDescription:null,aacCodecInfo:m.info.aacCodecInfo}),numberOfChannels:m.info.numberOfChannels,sampleRate:m.info.sampleRate},m.initialized=!0}}}if(c&&this.elementaryStreams.every(m=>m.initialized))break;s+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const l of this.elementaryStreams)l.info.type==="video"?this.trackBackingEntries.push(new jC(l)):this.trackBackingEntries.push(new XC(l))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(n=>(n==null?void 0:n.codec)??null)));return kg(e)}async readSection(e,t,n=!1){let i=e,s=e;const a=[];let o=0,c=null,l=!0,u=0;for(;;){const f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(c){if(f.pid!==c.pid){if(n)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;c=f}const h=!!(f.adaptationFieldControl&2),p=!!(f.adaptationFieldControl&1);let m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(u=f.body[1]>>6&1)),p&&(m===0?(a.push(f.body),o+=f.body.byteLength):(a.push(f.body.subarray(m)),o+=f.body.byteLength-m)),i=s,!t&&o>=64){l=!1;break}if(Ts(this.sectionEndPositions,i,g=>g)!==-1){l=!1;break}}if(l){const f=Me(this.sectionEndPositions,i,h=>h);this.sectionEndPositions.splice(f+1,0,i)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((p,m)=>p+m.length,0);d=new Uint8Array(f);let h=0;for(const p of a)d.set(p,h),h+=p.length}return{startPos:e,endPos:t?i:null,pid:c.pid,payload:d,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);
176if(t instanceof Promise&&(t=await t),!t)return null;if(se(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=At(t),s=i>>14&1,a=i&8191,c=se(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,Wt);if(t instanceof Promise&&(t=await t),!t)return null;const n=ae(t,Wt);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=(n[1]<<8)+n[2],a=s>>14&1,o=s&8191,l=n[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:l,body:n.subarray(4)}}}const qn=(r,e)=>{if(r.payload.byteLength<3)return null;const t=new Ce(r.payload);if(t.readBits(24)!==1)return null;const i=t.readBits(8);if(t.skipBits(16),i===188||i===190||i===191||i===240||i===241||i===255||i===242||i===248)return null;t.skipBits(8);const s=t.readBits(2);t.skipBits(14);let a=null;if(s===2||s===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(Tg);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Wi=(r,e)=>{y(r.endPos!==null);const t=qn(r,e);if(!t)return null;const n=new Ce(r.payload);n.skipBits(32);const i=n.readBits(16),s=6;n.skipBits(16);const a=n.readBits(8),o=n.pos+8*a;n.pos=o;const c=o/8;y(Number.isInteger(c));const l=r.payload.subarray(c,i>0?s+i:r.payload.byteLength);return{...t,data:l}};class ho{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let n=0;for(const i of e.trackBackingEntries)if(i.getType()===t&&n++,y(i instanceof ho),i.elementaryStream===this.elementaryStream)break;return n}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Bt}getDisposition(){return{...Lr,primary:!1}}getTimeResolution(){return wr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
176async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let i;return this.allPacketsAreKeyPackets()?i="key":i=e.randomAccessIndicator===1?"key":"delta",new He(n.metadataOnly?$t:e.data,i,e.pts/wr,Math.max(t/wr,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;y(t);const n=Wi(t,!0);y(n);const i=new zs(this.elementaryStream,n),s=new Xl(this,i),a=await s.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){const u=await n.readNext();if(!u)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}const i=this.packetSectionStarts.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");const a=await this.elementaryStream.demuxer.readSection(i,!0);y(a);const o=Wi(a,!0);y(o);const c=new zs(this.elementaryStream,o);n=new Xl(this,c);const l=e.sequenceNumber;for(;;){const u=await n.readNext();if(!u)return null;if(u.packet.sequenceNumber>l){const d=this.createEncodedPacket(u.packet,u.duration,t);return this.packetBuffers.set(d,n),this.packetSectionStarts.set(d,u.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type==="key")return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){var k;const i=Ss(e*wr),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(S,x,B)=>{let I=S;for(;I<x;){const C=await s.readPacketHeader(I);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){const v=await s.readSection(I,B);if(!v)return null;const R=qn(v,!1);if(R&&R.pts!==null)return{pesPacketHeader:R,section:v}}I+=s.packetStride}return null},u=this.elementaryStream.firstSection;y(u);const d=qn(u,!0);if(y(d),i<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,p=Me(h,i,S=>S.pts),m=p!==-1?h[p]:null;if(m&&i-m.pts<wr/2)f=m.sectionStartPos;else{let S=0;if(a.fileSize!==null){const x=Math.ceil(a.fileSize/o);if(x>1){let B=0,I=x-1;for(S=B;B<=I;){const C=Math.floor((B+I)/2),v=ol(C*o,s.packetStride)+d.sectionStartPos,R=v+o,M=await l(v,R,!1);if(!M){I=C-1;continue}M.pesPacketHeader.pts<=i?(S=C,B=C+1):I=C-1}}}f=ol(S*o,s.packetStride)+d.sectionStartPos}const A=await l(f,a.fileSize??1/0,!1);let g=(A==null?void 0:A.pesPacketHeader)??null;g||(g=d);const w=this.getReorderSize(),b=async(S,x)=>{var U;const B=await s.readSection(S,!0);y(B);const I=Wi(B,!0);y(I);const C=new zs(this.elementaryStream,I),v=new Xl(this,C);for(;!((((U=tt(v.presentationOrderPackets))==null?void 0:U.pts)??-1/0)>=i||!await v.readNextPacket()););const R=Va(v.presentationOrderPackets,x);if(R===-1)return null;const M=v.presentationOrderPackets[R],z=R===0?0:M.pts-v.presentationOrderPackets[R-1].pts;for(;v.decodeOrderPackets[0]!==M;)v.decodeOrderPackets.shift();v.lastDuration=z;const W=await v.readNext();y(W);const H=this.createEncodedPacket(W.packet,W.duration,n);return this.packetBuffers.set(H,v),this.packetSectionStarts.set(H,W.packet.sectionStartPos),H};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let S=g.sectionStartPos+s.packetStride;for(;;){const x=await s.readPacketHeader(S);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){const B=await s.readSection(S,!1);if(B){const I=qn(B,!1);if(I&&I.pts!==null){if(I.pts>i)break e;g=I,jl(this.elementaryStream,g);break}}}S+=s.packetStride}}e:for(let S=0;S<w+1;S++){let x=g.sectionStartPos-s.packetStride;for(;x>=s.packetOffset;){const B=await s.readPacketHeader(x);if(!B)break e;if(B.pid===c&&B.payloadUnitStartIndicator===1){const I=await s.readSection(x,!1);if(I){const C=qn(I,!1);if(C&&C.pts!==null){g=C;break}}}x-=s.packetStride}}return b(g.sectionStartPos,S=>S.pts<=i)}else{let S=f,x=null;const B=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let I=null;const C=S<=d.sectionStartPos;let v,R=null;if(C)v=d,R=u;else{const W=await l(S,a.fileSize??1/0,B);v=(W==null?void 0:W.pesPacketHeader)??null,R=(W==null?void 0:W.section)??null}let M=!1,z=0;e:for(;v&&!(x!==null&&v.sectionStartPos>=x);){if(v.pts<=i){let H;if(this.elementaryStream.canBeTrustedWithKeyPackets)H=v.randomAccessIndicator===1;else{y(R);const U=Wi(R,!0);y(U);const j=new zs(this.elementaryStream,U);await j.markNextPacket(),H=((k=j.suppliedPacket)==null?void 0:k.randomAccessIndicator)===1}H&&(I=v)}if(v.pts>i&&(M=!0),M&&(z++,z>w))break;let W=v.sectionStartPos+s.packetStride;for(;;){const H=await s.readPacketHeader(W);if(!H)break e;if(H.pid===c&&H.payloadUnitStartIndicator===1){const U=await s.readSection(W,B);if(U){const j=qn(U,!1);if(j&&j.pts!==null){v=j,R=U,jl(this.elementaryStream,v);break}}}W+=s.packetStride}}if(I){let W=I;if(z===0)e:for(let U=0;U<w;U++){let j=W.sectionStartPos-s.packetStride;for(;j>=s.packetOffset;){const ce=await s.readPacketHeader(j);if(!ce)break e;
176if(ce.pid===c&&ce.payloadUnitStartIndicator===1){const ee=await s.readSection(j,B);if(ee){const fe=qn(ee,!1);if(fe&&fe.pts!==null){W=fe;break}}}j-=s.packetStride}}const H=await b(W.sectionStartPos,U=>U.pts<=i&&U.randomAccessIndicator===1);return y(H),H}if(C)return null;x=S,S=Math.max(ol(S-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class jC extends ho{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class XC extends ho{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const jl=(r,e)=>{const t=r.referencePesPackets,n=Me(t,e.sectionStartPos,i=>i.sectionStartPos);if(n>=0){const i=t[n];if(e.pts<=i.pts)return!1;const s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-i.sectionStartPos<s)return!1;if(n<t.length-1){const a=t[n+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(n+1,0,e),!0};class zs{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return y(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let n;if(this.pesPackets.length===0)n=this.startingPesPacket;else{let i=tt(this.pesPackets).sectionEndPos;for(y(i!==null);;){const s=await this.demuxer.readPacketHeader(i);if(!s)return;if(s.pid===this.pid){const a=await this.demuxer.readSection(i,!0);if(!a)return;const o=Wi(a,!1);if(o){n=o;break}}i+=this.demuxer.packetStride}}this.pesPackets.push(n),this.endPos+=n.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,i=n+e;if(this.currentPos+=e,i<=t.data.byteLength)return t.data.subarray(n,i);const s=new Uint8Array(e);s.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){s.set(o.data.subarray(0,c),a);break}s.set(o.data,a),a+=o.data.byteLength}return s}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){const t=this.getCurrentPesPacket(),n=this.currentPesPacketPos+t.data.byteLength;if(e<n)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){y(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const t=e.info.codec,n=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let i=null;for(;;){let s=this.ensureBuffered(n);if(s instanceof Promise&&(s=await s),s===0)break;const a=this.currentPos,o=this.readBytes(s),c=o.byteLength;let l=0;for(;l<c;){const u=o.indexOf(0,l);if(u===-1||u>=c)break;l=u;const d=a+l;if(l+4>=c){this.seekTo(d);break}const f=o[l+1],h=o[l+2],p=o[l+3];let m=0,A=null;if(f===0&&h===0&&p===1?(m=4,A=o[l+4]):f===0&&h===1&&(m=3,A=p),m===0){l++;continue}const g=d;if(i===null){i=g,l+=m;continue}if(A!==null){const w=t==="avc"?Di(A):bn(A);
176if(t==="avc"?w===ur.AUD:w===pt.AUD_NUT){const k=g-i;return this.seekTo(i),this.supplyPacket(k,0)}}l+=m}if(s<n)break}if(i!==null){const s=this.endPos-i;return this.seekTo(i),this.supplyPacket(s,0)}}else{const t=e.info.codec,n=128;for(;;){let i=this.ensureBuffered(n);i instanceof Promise&&(i=await i);const s=this.currentPos;for(;this.currentPos-s<i;){const a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Sn);if(c instanceof Promise&&(c=await c),c<Sn)return;const l=this.readBytes(Sn),u=jr(Nt.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(fo*wr/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Vn);if(c instanceof Promise&&(c=await c),c<Vn)return;const l=this.readBytes(Vn),u=Ae(l).getUint32(0),d=eo(u,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);f instanceof Promise&&(f=await f);const h=d.header.audioSamplesInFrame*wr/e.info.sampleRate;return this.supplyPacket(f,Math.round(h))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}const f=mC[3*d+u];y(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),c instanceof Promise&&(c=await c);const h=Math.round(pC*wr/e.info.sampleRate);return this.supplyPacket(c,h)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}const d=(((l[2]&7)<<8|l[3])+1)*2,h=l[4]>>6===3?3:l[4]>>4&3,p=Np[h];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);const m=p*256,A=Math.round(m*wr/e.info.sampleRate);return this.supplyPacket(c,A)}else throw new Error("Unhandled.")}if(i<n)break}}}supplyPacket(e,t){const n=this.getCurrentPesPacket();let i;if(this.lastSuppliedPesPacket===n)y(this.nextPts!==null),i=this.nextPts;else{if(n.pts===null)throw new Error(Tg);i=n.pts,jl(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=i+t;const s=n.sectionStartPos,a=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=n.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const l=ao(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:i,data:o,sequenceNumber:a,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Xl{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),y(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);y(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const i=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(i))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[t].pts&&(t=i);const n=this.reorderBuffer[t];this.presentationOrderPackets.push(n),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>
176e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*!
177 * Copyright (c) 2026-present, Vanilagy and contributors
178 *
179 * This Source Code Form is subject to the terms of the Mozilla Public
180 * License, v. 2.0. If a copy of the MPL was not distributed with this
181 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
182 */const Vi="application/vnd.apple.mpegurl",Cg="#EXT-X-STREAM-INF:",Ig="#EXT-X-I-FRAME-STREAM-INF:",Bg="#EXT-X-MEDIA:",Jl="#EXTINF:",xg="#EXT-X-MAP:",Pg="#EXT-X-KEY:",vg="#EXT-X-MEDIA-SEQUENCE:",_g="#EXT-X-BYTERANGE:",Fg="#EXT-X-PROGRAM-DATE-TIME:",JC="#EXT-X-DISCONTINUITY",Rg="#EXT-X-TARGETDURATION:",$C="#EXT-X-ENDLIST",Dg="#EXT-X-PLAYLIST-TYPE:",ZC="#EXT-X-I-FRAMES-ONLY",Mg=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class Ws{constructor(e){this._attributes={};let t="",n="",i=!1,s=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?s=!s:o==="="&&!i&&!s?i=!0:o===","&&!s?(t&&(this._attributes[t.trim().toLowerCase()]=n),t="",n="",i=!1):i?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}}/*!
183 * Copyright (c) 2026-present, Vanilagy and contributors
184 *
185 * This Source Code Form is subject to the terms of the Mozilla Public
186 * License, v. 2.0. If a copy of the MPL was not distributed with this
187 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
188 */class eI{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}
188async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const n=xs(e,i=>i.getType()==="video")+1;e.push(new Og(this,t,n))}else if(t.type==="audio"){const n=xs(e,i=>i.getType()==="audio")+1;e.push(new Ng(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const n=await this.getInputForSegment(this.firstSegment).getTracks();for(const i of n)if(i.type==="video"){const s=xs(e,a=>a.getType()==="video")+1;e.push(new Og(this,{id:e.length+1,type:"video"},s))}else if(i.type==="audio"){const s=xs(e,a=>a.getType()==="audio")+1;e.push(new Ng(this,{id:e.length+1,type:"audio"},s))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(t!==void 0)return t;const n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){const n=e.firstSegment??e;let i;if(this.firstSegmentFirstTimestamps.has(n))i=this.firstSegmentFirstTimestamps.get(n);else{const l=this.getInputForSegment(n);i=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(n,i)}if(n===e)return n.timestamp-i;const s=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,c=s-i-a;return Math.abs(c)<=Math.min(.25,a)?n.timestamp-i:e.timestamp-s}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class Ug{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var i;if((i=this.segmentedInput).firstSegment??(i.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const n=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number);if(!n)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=n})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t;return((t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??null})}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}
188getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,n){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const i=await this.segmentedInput.getMediaOffset(t,n.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Ci(e.timestamp+i,await n.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:n,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),y(this.segmentedInput.firstSegment),y(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){const i=this.packetInfos.get(e);if(!i)throw new Error("Packet was not created from this track.");const s=n?await i.track._backing.getNextKeyPacket(i.sourcePacket,t):await i.track._backing.getNextPacket(i.sourcePacket,t);if(s)return this.createAdjustedPacket(s,i.segment,i.track);let a=i.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(f=>f.type===i.track.type&&f.number===i.track.number);if(!u){a=o;continue}const d=await u._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,u):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){const s=this.segmentedInput.getInputForSegment(i),o=(await s.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(i,s),l=e-c,u=n?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!u){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(u,i,o)}return null}}class Og extends Ug{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}
188async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ng extends Ug{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}var mo=Object.freeze({__proto__:null});/*!
189 * Copyright (c) 2026-present, Vanilagy and contributors
190 *
191 * This Source Code Form is subject to the terms of the Mozilla Public
192 * License, v. 2.0. If a copy of the MPL was not distributed with this
193 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
194 */ml();const Qg=typeof mo<"u"?mo:void 0,Lg=0,zg=1/0;let jn=null;typeof FinalizationRegistry<"u"&&(jn=new FinalizationRegistry(r=>{r()}));class tr extends _s{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Gt;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Lg,zg),e=this._getFileSize(),y(e!==void 0)),e})())}async getSize(){if(this._disposed)throw new Gt;
194const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Yg(this,e,t)}_dispatchRead(e,t){var n;(n=this.onread)==null||n.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new po(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class po{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),(t=e._refFinalizationRegistry)==null||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var t;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;y(e._refCount>0),e._decrementRefCount(),(t=e._refFinalizationRegistry)==null||t.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Xn extends tr{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),n=i=>{var a;if(!(i instanceof tr||i instanceof po))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=i instanceof tr?i.ref():i;return(a=s.source)._usedForHls||(a._usedForHls=this._usedForHls),s};return t instanceof Promise?t.then(n):n(t)}}const Wg=(r,e)=>r.path===e.path;class Vg extends Xn{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,n,i){if(!this._root){if(!this._rootRequest){const s=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof tr?o.ref():o;return this._root=c,this._rootRequest=null,c};s instanceof Promise?this._rootRequest=s.then(a):(a(s),y(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,t,n,i))}return this._root.source._read(e,t,n,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class tI extends tr{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=je(e),this._view=Ae(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class rI extends tr{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!xi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new ru({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:tu.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,i){return this._orchestrator.read(e,t,n,i)}async _runWorker(e){y(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!Bs()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:n,value:i}=await t.read();
194if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{const n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t==null?void 0:t.cancel())}_dispose(){this._orchestrator.dispose()}}const nI=.5*2**20,iI=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let i=null;try{typeof window<"u"&&typeof window.location<"u"&&(i=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&i!==null&&i!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),Hg=new Set;class $l extends Xn{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!xi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");const n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,s=>new $l(s.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??iI;const i=2;this._orchestrator=new ru({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??i,runWorker:this._runWorker.bind(this),prefetchProfile:tu.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,n,i){return this._orchestrator.read(e,t,n,i)}async _runWorker(e){for(;;){const t=new AbortController,n=await xS(this._options.fetchFn??fetch,this._url,BS(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);e:if(this._orchestrator.fileSize===null){const s=n.headers.get("Content-Range");if(s){const o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=n.headers.get("Content-Length");
194a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,n.status!==206){if(!this._usedForHls){const s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Hg.has(s.origin)||(console.log(this._usedForHls,this._url,s.pathname),console.warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Hg.add(s.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const i=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await i.read()}catch(c){if(this._disposed)throw c;const l=this._getRetryDelay(1,c,this._url);if(l!==null){console.error("Error while reading response stream. Attempting to resume.",c),await Al(1e3*l);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}}class Zl extends Xn{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!xi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Qg.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,n=>new Zl(n.path,t)),this._fileHandle=null,this._customSource=new eu({getSize:async()=>{const n=await Qg.fs.open(e,"r");return this._fileHandle=n,jn==null||jn.register(this,()=>{n.close()},this),(await n.stat()).size},read:async(n,i)=>{y(this._fileHandle);const s=new Uint8Array(i-n);return await this._fileHandle.read(s,0,i-n,n),s},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t,n,i){return this._customSource._read(e,t,n,i)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,jn==null||jn.unregister(this))}}class eu extends tr{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!xi(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new ru({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:tu[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,n,i){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,n,i);const s=this._options.getSize();if(s instanceof Promise)return s.then(a=>{if(!Number.isInteger(a)||a<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");
194return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,n,i)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,this._orchestrator.read(e,t,n,i)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,n=e.targetPos;let i=this._options.read(e.currentPos,n);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=je(i),i.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${i.length}.`);this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else if(i instanceof ReadableStream){const s=i.getReader();for(;e.currentPos<n&&!e.aborted;){const{done:a,value:o}=await s.read();if(a){if(e.currentPos<n)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-t} bytes, but got ${e.currentPos-t}`);break}if(!(o instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const c=je(o);this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){var e,t;this._orchestrator.dispose(),(t=(e=this._options).dispose)==null||t.call(e)}}const sI=eu;class Gg extends tr{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!xi(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const n=Me(this._cache,e,u=>u.start),i=n!==-1?this._cache[n]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let s=e;const a=new Uint8Array(t-e);if(n!==-1)for(let u=n;u<this._cache.length;u++){const d=this._cache[u];if(d.start>=t)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const h=Math.min(t,d.end);f<h&&(a.set(d.bytes.subarray(f-d.start,h-d.start),f-e),s=h)}if(s===t)return{bytes:a,view:Ae(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=rt();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else throw u})),o}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const n=this._currentIndex,i=this._currentIndex+t.byteLength;this._dispatchRead(n,i);for(let s=0;s<this._pendingSlices.length;s++){const a=this._pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.end);o<c&&(a.bytes.set(t.subarray(o-n,c-n),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:Ae(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:i,bytes:t,view:Ae(t),age:0});this._cache.length>0;){const s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){var e;this._pendingSlices.length=0,this._cache.length=0,(e=this._reader)==null||e.cancel()}}const tu={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const i of t){const a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-8388608);if(hl(r,e,a,i.targetPos)){const o=i.targetPos-i.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,i.startPos+u)}}return e=Math.max(e,r+nI),{start:r,end:e}}};class ru{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,n,i){y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,n),o=Math.min(s.end,this.fileSize??1/0,i);y(a<=e&&t<=o);let c=null;const l=Me(this.cache,e,S=>S.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=Me(this.cache,a,S=>S.start),f=c?null:new Uint8Array(t-e);let h=0,p=a;const m=[];
194if(d!==-1){for(let S=d;S<this.cache.length;S++){const x=this.cache[S];if(x.start>=o)break;if(x.end<=a)continue;const B=Math.max(a,x.start),I=Math.min(o,x.end);if(y(B<=I),p<B&&m.push({start:p,end:B}),p=I,f){const C=Math.max(e,x.start),v=Math.min(t,x.end);if(C<v){const R=C-e;f.set(x.bytes.subarray(C-x.start,v-x.start),R),R===h&&(h=v-e)}}x.age=this.nextAge++}p<o&&m.push({start:p,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:Ae(f),offset:e}),m.length===0)return y(c),c;const{promise:A,resolve:g,reject:w}=rt(),b=[];for(const S of m){const x=Math.max(e,S.start),B=Math.min(t,S.end);x===S.start&&B===S.end?b.push(S):x<B&&b.push({start:x,end:B})}const k=f&&{start:e,bytes:f,holes:b,resolve:g,reject:w};e:for(const S of m){for(const I of this.workers)if(this.checkHoleAgainstWorker(I,S,k?[k]:[])){this.checkQueuedReadsAgainstWorker(I);continue e}const x=S.end<o||this.fileSize!==null,B=this.createWorker(S.start,S.end,x);if(B)k&&(B.pendingSlices=[k]),this.runWorker(B);else{let I=Me(this.queuedReads,S.start,v=>v.hole.start),C=I!==-1?this.queuedReads[I]:null;for(C&&S.start<=C.hole.end?(C.hole.end=Math.max(C.hole.end,S.end),C.strictTarget&&(C.strictTarget=x),k&&C.pendingSlices.push(k)):(I++,C={hole:{start:S.start,end:S.end},strictTarget:x,pendingSlices:k?[k]:[],age:this.nextAge++},this.queuedReads.splice(I,0,C));I+1<this.queuedReads.length;){const v=this.queuedReads[I+1];if(v.hole.start>C.hole.end)break;C.hole.end=Math.max(C.hole.end,v.hole.end),C.pendingSlices.push(...v.pendingSlices),C.strictTarget&&(C.strictTarget=v.strictTarget),C.age=Math.min(C.age,v.age),this.queuedReads.splice(I+1,1)}}}return c||(y(f),c=A.then(S=>S&&{bytes:S,view:Ae(S),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(hl(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let s=0;s<n.length;s++){const a=n[s];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){const i=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,i.hole,i.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,t,n){if(this.workers.length>=this.options.maxWorkerCount){let s=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!s||c.age<s.age)&&(a=o,s=c)}if(s)y(a!==null),y(s.pendingSlices.length===0),this.workers.splice(a,1);else return null}const i={startPos:e,currentPos:e,targetPos:t,strictTarget:n,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){y(!e.running),y(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(n=>n.reject(t)),e.pendingSlices.length=0;else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let s=1;s<this.queuedReads.length;s++)this.queuedReads[s].age<this.queuedReads[t].age&&(t=s);const n=this.queuedReads[t];this.queuedReads.splice(t,1);const i=this.createWorker(n.hole.start,n.hole.end,n.strictTarget);y(i),i.pendingSlices=n.pendingSlices,this.runWorker(i)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){const i=this.workers[n];if(i!==e){for(const s of i.pendingSlices)t.add(s);i.aborted=!0,i.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let n=0;n<this.queuedReads.length;n++){const i=this.queuedReads[n];for(const s of i.pendingSlices)t.add(s)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){y(!e.aborted);const n=e.currentPos,i=n+t.length;this.insertIntoCache({start:n,end:i,bytes:t,view:Ae(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let s=0;s<e.pendingSlices.length;s++){const a=e.pendingSlices[s],o=Math.max(n,a.start),c=Math.min(i,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-n,c-n),o-a.start);for(let l=0;l<a.holes.length;l++){const u=a.holes[l];
194n<=u.start&&i>u.start&&(u.start=i),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(s,1),s--)}for(let s=0;s<this.workers.length;s++){const a=this.workers[s];e===a||a.running||hl(n,i,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),s--)}}supplyFileSize(e){y(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){const i=t.pendingSlices[n];for(const s of i.holes)if(s.end>e){i.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){const n=this.queuedReads[t];if(n.hole.start>=e){for(const i of n.pendingSlices)i.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let i=0;i<n.pendingSlices.length;i++){const s=n.pendingSlices[i];s.start>=e&&(s.resolve(null),n.pendingSlices.splice(i,1),i--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);y(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=Me(this.cache,e.start,n=>n.start)+1;if(t>0){const n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){const i=new Uint8Array(e.end-n.start);i.set(n.bytes,0),i.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=i,n.view=Ae(i),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){const i=this.cache[n];if(e.end<=i.start)break;if(e.end>=i.end){this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length,n--;continue}const s=new Uint8Array(i.end-e.start);s.set(e.bytes,0),s.set(i.bytes,i.start-e.start),this.currentCacheSize-=e.end-i.start,e.bytes=s,e.view=Ae(s),e.end=i.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let n=0,i=this.cache[0];for(let s=1;s<this.cache.length;s++){const a=this.cache[s];a.age<i.age&&(n=s,i=a)}if(this.currentCacheSize-i.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(n,1),this.currentCacheSize-=i.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class Yg extends tr{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:It(e-this._offset,0,this._length??1/0)}_read(e,t,n,i){if(this._length!==null&&t>this._length)return null;const s=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+i);return s instanceof Promise?s.then(a=>a?(a.offset-=this._offset,a):null):s?(s.offset-=this._offset,s):null}_dispose(){var e;(e=this._ref)==null||e.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}/*!
195 * Copyright (c) 2026-present, Vanilagy and contributors
196 *
197 * This Source Code Form is subject to the terms of the Mozilla Public
198 * License, v. 2.0. If a copy of the MPL was not distributed with this
199 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
200 */var Kg=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},qg=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}
200if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});const aI=/^0[xX][0-9a-fA-F]+$/,oI=/^data:.*;base64,/i;class jg extends eI{constructor(e,t,n,i){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await Al(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const g={stack:[],error:void 0,hasError:!1};try{const w=Kg(g,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),k=await new _o(w.source).requestEntireFile();y(k),e=zA(k,k.length,{ignore:Mg})}catch(w){g.error=w,g.hasError=!0}finally{qg(g)}}let t=!1,n=0,i=null,s=null,a=0,o=null,c=null,l=null,u=null,d=null,f=null,h=!1,p=tt(this.segments)??null;const m=g=>{const w=g.indexOf("@"),b=Number(w===-1?g:g.slice(0,w));if(!Number.isInteger(b)||b<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${g}'.`);let k=null;if(w!==-1&&(k=Number(g.slice(w+1)),!Number.isInteger(k)||k<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${g}'.`);return{length:b,offset:k}},A=g=>{a=g,p&&(y(p.sequenceNumber!==null),p.sequenceNumber<g&&(n=p.timestamp+p.duration,o=p.firstSegment,c=p.initSegment,d=p.lastProgramDateTimeSeconds,p=null))};for(let g=0;g<e.length;g++){const w=e[g];if(!t){if(w!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0;continue}if(!w.startsWith("#")){if(!p){if(i===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let b=s;if(b&&b.method==="AES-128"&&!b.iv){const B=new Uint8Array(vr),I=Ae(B);I.setUint32(8,Math.floor(a/2**32)),I.setUint32(12,a),b={...b,iv:B}}const S={path:Dt(this.path,w),offset:(u==null?void 0:u.offset)??0,length:(u==null?void 0:u.length)??null},x={timestamp:n,relativeToUnixEpoch:d!==null,firstSegment:o,sequenceNumber:a,location:S,duration:i,encryption:b,initSegment:c,lastProgramDateTimeSeconds:d};o??(o=x),n+=i,this.segments.push(x)}i=null,u===null?l=null:u=null,A(a+1)}if(w.startsWith(Jl)){if(p){h=!0;continue}h||(d===null&&a>0&&f!==null&&(n=a*f),h=!0);const b=w.slice(Jl.length),k=b.indexOf(","),S=k===-1?b:b.slice(0,k),x=Number(S);if(!Number.isFinite(x)||x<0)throw new Error(`Invalid #EXTINF tag duration '${S}'.`);i=x}else if(w.startsWith(xg)){const b=new Ws(w.slice(xg.length)),k=b.get("uri");if(!k)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const S=b.get("byterange");let x=null;if(S!==null&&(x=m(S)),x&&x.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const I={path:Dt(this.path,k),offset:(x==null?void 0:x.offset)??0,length:(x==null?void 0:x.length)??null};if((s==null?void 0:s.method)==="AES-128"&&!s.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");c={timestamp:n,relativeToUnixEpoch:d!==null,firstSegment:null,sequenceNumber:null,location:I,duration:0,encryption:s,initSegment:null,lastProgramDateTimeSeconds:d}}i=null,u===null?l=null:u=null}else if(w.startsWith(Pg)){const b=new Ws(w.slice(Pg.length)),k=b.get("method");if(k==="NONE")s=null;else if(k==="AES-128"){const S=b.get("uri");if(!S)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let x=null;const B=b.get("iv");if(B){if(!aI.test(B))throw new Error(`Unsupported IV format '${B}'.`);let C=B.slice(2);C=C.padStart(vr*2,"0"),x=new Uint8Array(vr);for(let v=0;v<vr;v++){const R=-vr*2+v;x[v]=parseInt(C.slice(R,R+2),16)}}const I=b.get("keyformat")??"identity";if(I!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");s={method:"AES-128",keyUri:Dt(this.path,S),iv:x,keyFormat:I}}else if(k==="SAMPLE-AES"||k==="SAMPLE-AES-CTR"){const S=b.get("uri");if(!S)throw new Error(`Invalid #EXT-X-KEY: ${k} requires a URI attribute.`);if((b.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let B=null;if(oI.test(S)){const I=S.indexOf(","),C=qa(S.slice(I+1));if(C.length>=8&&C[4]===112&&C[5]===115&&C[6]===115&&C[7]===104){const v=Ae(C).getUint32(0);B=Vp(C.subarray(8,Math.min(v,C.length)))}}s={method:k,psshBox:B}}else throw new Error(`Unsupported encryption method '${k}'. If you think this method should be supported, please raise an issue.`)}else if(w.startsWith(vg)){const b=w.slice(vg.length),k=Number(b);if(!Number.isInteger(k)||k<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${b}'.`);A(k)}else if(w.startsWith(_g)){const b=m(w.slice(_g.length));if(b.offset===null){if(l===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");b.offset=l}u=b,l=b.offset+b.length}else if(w.startsWith(Fg)){if(p)continue;const b=w.slice(Fg.length),k=Date.parse(b);if(!Number.isFinite(k))continue;const S=k/1e3;if(d===S)continue;if(d===null&&this.segments.length>0){const x=tt(this.segments),B=x.timestamp+x.duration,I=S-B;for(const C of this.segments)C.timestamp+=I,C.relativeToUnixEpoch=!0;n+=I}d=S,n=S}
200else if(w===JC)o=null;else if(w.startsWith(Rg)){const b=w.slice(Rg.length),k=Number(b);if(!Number.isFinite(k)||k<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${b}'.`);this.refreshInterval=k,f=k}else if(w===$C){this.streamHasEnded=!0;break}else w.startsWith(Dg)&&w.slice(Dg.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!t)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const i=Me(this.segments,e,a=>a.timestamp);if(i===-1)return null;if(i<this.segments.length-1||this.streamHasEnded||n)return this.segments[i];const s=this.segments[i];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){const n=this.segments.indexOf(e);y(n!==-1);const i=n+1;let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return y(t!==-1),this.segments[t-1]??null}getInputForSegment(e){var c;const t=e,n=this.inputCache.find(l=>l.segment===t);if(n)return n.age=this.nextInputCacheAge++,n.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:((c=this.input._formatOptions.isobmff)==null?void 0:c.resolveKeyId)&&(l=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(l);let u=l.psshBoxes;const{psshBox:d}=t.encryption;return(d.keyIds===null||d.keyIds.includes(l.keyId))&&!u.some(f=>Hp(f,d))&&(u=[...u,d]),this.input._formatOptions.isobmff.resolveKeyId({...l,psshBoxes:u})})}},a=new $s({source:new Vg(t.location.path,async l=>{y(l.isRoot);const u={...l,isRoot:!1};let d;const f=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(u),f){const p=d.source.slice(t.location.offset,t.location.length??void 0).ref();d.free(),d=p}}else if(t.encryption.method==="AES-128"){const h=t.encryption;y(h.iv);let p=await this.input._getSourceCached(u);if(f){const w=p.source.slice(t.location.offset,t.location.length??void 0).ref();p.free(),p=w}const m=new _o(p.source),A=yC(m,async()=>{const g={stack:[],error:void 0,hasError:!1};try{const w=Kg(g,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},qI),!1),k=await new _o(w.source).requestSlice(0,vr);if(!k)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:ae(k,vr),iv:h.iv}}catch(w){g.error=w,g.hasError=!0}finally{qg(g)}},()=>{p.free()});d=new Gg(A).ref()}else y(!1);return d}),formats:this.input._formats.filter(l=>!(l instanceof su)),initInput:i??void 0,formatOptions:s});if(a._onFormatDetermined=l=>{var u,d;if((((u=t.encryption)==null?void 0:u.method)==="SAMPLE-AES"||((d=t.encryption)==null?void 0:d.method)==="SAMPLE-AES-CTR")&&!l._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const l=pl(this.inputCache,u=>u.age);y(l!==-1),this.inputCache.splice(l,1)}return a}
200async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}/*!
201 * Copyright (c) 2026-present, Vanilagy and contributors
202 *
203 * This Source Code Form is subject to the terms of the Mozilla Public
204 * License, v. 2.0. If a copy of the MPL was not distributed with this
205 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
206 */class cI extends Vr{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{y(this.input._rootSource instanceof Xn);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();y(t);const n=zA(t,t.length,{ignore:Mg}),i=[],s=[];for(let d=1;d<n.length;d++){const f=n[d];if(f.startsWith(Cg)){const h=d,p=n[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const m=Dt(e,p),A=new Ws(f.slice(Cg.length));if(A.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");i.push({fullPath:m,attributes:A,lineNumber:h,hasOnlyKeyPackets:!1})}else if(f.startsWith(Ig)){const h=new Ws(f.slice(Ig.length)),p=h.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const A=Dt(e,p);i.push({fullPath:A,attributes:h,lineNumber:d,hasOnlyKeyPackets:!0})}else if(f.startsWith(Bg)){const h=new Ws(f.slice(Bg.length));if(h.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(h.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let A=null;const g=h.get("uri");g!==null&&(A=Dt(e,g)),s.push({fullPath:A,attributes:h,lineNumber:d})}else if(f!==ZC){if(f.startsWith(Jl)){const h=new jg(this,e,null,n);this.segmentedInputs=[h],this.hasMasterPlaylist=!1,this.trackBackings=await h.getTrackBackings();return}}}const a=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(s.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(i.map(async(d,f)=>{const h=[],p=d.attributes.get("codecs");let m;if(p)m=p.split(",").map(C=>C.trim());
206else{const v=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),R=await Promise.all(v.map(async M=>({track:M,codec:await M.getCodec()})));m=await Promise.all(R.filter(M=>M.codec!==null).map(M=>M.track.getDecoderConfig().then(z=>z.codec)))}const A=d.attributes.get("video"),g=d.attributes.get("audio"),w=m.some(C=>dt.includes(zr(C))),b=m.some(C=>bt.includes(zr(C)));if(A!==null&&!w){if(!a.includes(A))throw new Error(`Invalid M3U8 file; variant stream references video group "${A}" which is not defined in any #EXT-X-MEDIA tags.`);const C=s.find(v=>{const R=v.attributes.get("group-id"),M=v.attributes.get("type");return R===A&&M.toLowerCase()==="video"});e:if(C){const v=C.attributes.get("uri");if(v===null)break e;const R=Dt(e,v),W=(await this.getSegmentedInputForPath(R).getTrackBackings()).find(U=>U.getType()==="video");if(!W||await W.getCodec()===null)break e;const H=await W.getDecoderConfig().then(U=>(U==null?void 0:U.codec)??null);y(H!==null),m.push(H)}}if(g!==null&&!b){if(!o.includes(g))throw new Error(`Invalid M3U8 file; variant stream references audio group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);const C=s.find(v=>{const R=v.attributes.get("group-id"),M=v.attributes.get("type");return R===g&&M.toLowerCase()==="audio"});e:if(C){const v=C.attributes.get("uri");if(v===null)break e;
206const R=Dt(e,v),W=(await this.getSegmentedInputForPath(R).getTrackBackings()).find(U=>U.getType()==="audio");if(!W||await W.getCodec()===null)break e;const H=await W.getDecoderConfig().then(U=>(U==null?void 0:U.codec)??null);y(H!==null),m.push(H)}}m=[...new Set(m)];let k=null,S=null;const x=d.attributes.getAsNumber("bandwidth");y(x!==null);const B=d.attributes.getAsNumber("average-bandwidth"),I=d.attributes.get("name");for(const C of m){const v=zr(C);if(v!==null){if(dt.includes(v)){if(k!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");k=C;const R=d.attributes.get("video");if(R===null){const M=d.attributes.get("resolution");let z=null,W=null;if(M){const H=M.match(/^(\d+)x(\d+)$/);H&&(z=Number(H[1]),W=Number(H[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Bt,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(f),peakBitrate:x,averageBitrate:B,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:z,height:W}})}else{if(!a.includes(R))throw new Error(`Invalid M3U8 file; variant stream references video group "${R}" which is not defined in any #EXT-X-MEDIA tags.`);for(const M of s){const z=M.attributes.get("group-id"),W=M.attributes.get("type");if(z!==R||W.toLowerCase()!=="video")continue;const H=M.attributes.get("resolution")??d.attributes.get("resolution");let U=null,j=null;if(H){const ce=H.match(/^(\d+)x(\d+)$/);ce&&(U=Number(ce[1]),j=Number(ce[2]))}h.push({id:-1,demuxer:this,backingTrack:null,default:go(M.attributes),autoselect:go(M.attributes)||Zg(M.attributes),languageCode:eA(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:U,height:j}})}}}else if(bt.includes(v)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");S=C;const R=d.attributes.get("audio");if(R===null){const M=d.attributes.get("channels"),z=M!==null?Number(M.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Bt,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(f),peakBitrate:x,averageBitrate:B,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:z!==null&&Number.isInteger(z)&&z>0?z:null}})}else{if(!o.includes(R))throw new Error(`Invalid M3U8 file; variant stream references audio group "${R}" which is not defined in any #EXT-X-MEDIA tags.`);for(const M of s){const z=M.attributes.get("group-id"),W=M.attributes.get("type");if(z!==R||W.toLowerCase()!=="audio")continue;const H=M.attributes.get("channels")??d.attributes.get("channels"),U=H!==null?Number(H.split("/")[0]):null;h.push({id:-1,demuxer:this,backingTrack:null,default:go(M.attributes),autoselect:go(M.attributes)||Zg(M.attributes),languageCode:eA(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(f),peakBitrate:null,averageBitrate:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:U!==null&&Number.isInteger(U)&&U>0?U:null}})}}}}}return h})),l=[],u=d=>{const f=l.find(h=>h.fullPath===d.fullPath&&h.info.type===d.info.type);f?(f.pairingMask|=d.pairingMask,f.default||(f.default=d.default),f.autoselect||(f.autoselect=d.autoselect),f.lineNumber=Math.min(f.lineNumber,d.lineNumber),d.peakBitrate!==null&&(f.peakBitrate=Math.max(f.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(f.averageBitrate=Math.max(f.averageBitrate??-1/0,d.averageBitrate)),f.languageCode===Bt&&(f.languageCode=d.languageCode)):(d.id=l.length+1,l.push(d))};for(const d of c)for(const f of d)u(f);l.sort((d,f)=>d.lineNumber-f.lineNumber),this.trackBackings=[];for(const d of l)d.info.type==="video"?this.trackBackings.push(new Jg(d)):this.trackBackings.push(new $g(d));this.internalTracks=l})())}async getTrackBackings(){return await this.readMetadata(),y(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(i=>i.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),t=new jg(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Vi}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Xg{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(s=>s.getType()===this.getType());if(i.length===1)t=i[0];else if(this instanceof Jg){for(const s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}else{y(this instanceof $g);for(const s of i)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Lr,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){y(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
206async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class Jg extends Xg{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return zr(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}
206async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class $g extends Xg{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return zr(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const go=r=>{const e=r.get("default");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},Zg=r=>{const e=r.get("autoselect");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},eA=r=>{if(r===null)return Bt;const e=r.split("-")[0];return e||Bt};/*!
207 * Copyright (c) 2026-present, Vanilagy and contributors
208 *
209 * This Source Code Form is subject to the terms of the Mozilla Public
210 * License, v. 2.0. If a copy of the MPL was not distributed with this
211 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
212 */class yr{constructor(){this._isIsobmff=!1}}class nu extends yr{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const n=ct(t,4);return n!=="ftyp"&&n!=="styp"?null:ct(t,4)}_createDemuxer(e){return new Ol(e)}}class tA extends nu{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt  ";let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;const i=ct(n,4);return i==="moof"||i==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class rA extends nu{async _canReadInput(e){return await this._getMajorBrand(e)==="qt  "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class iu extends yr{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,Yr);if(n instanceof Promise&&(n=await n),!n)return!1;const i=ag(n);if(i===null||i<1||i>8||Be(n,i)!==_.EBML)return!1;const a=og(n);if(typeof a!="number")return!1;let o=e._reader.requestSlice(n.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;const c=n.filePos;for(;o.filePos<=c+a-dr;){const l=Kr(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case _.EBMLVersion:if(Be(o,d)!==1)return!1;break;case _.EBMLReadVersion:if(Be(o,d)!==1)return!1;break;case _.DocType:if(Qi(o,d)!==t)return!1;break;case _.DocTypeVersion:if(Be(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new vC(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}
212class nA extends iu{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class iA extends yr{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,$r);if(d instanceof Promise&&(d=await d),!d)break;const f=ti(d);if(!f)break;t=d.filePos+f.size}const n=await Kl(e._reader,t,t+4096);if(!n)return!1;const i=n.header,s=Za(i.mpegVersionId,i.channel);let a=e._reader.requestSlice(n.startPos+s,4);if(a instanceof Promise&&(a=await a),!a)return!1;const o=q(a);if(o===$a||o===Tl)return!0;t=n.startPos+n.header.totalSize;const l=await Kl(e._reader,t,t+Vn);if(!l)return!1;const u=l.header;return!(i.channel!==u.channel||i.sampleRate!==u.sampleRate)}_createDemuxer(e){return new RC(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class sA extends yr{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const n=ct(t,4);return n!=="RIFF"&&n!=="RIFX"&&n!=="RF64"?!1:(t.skip(4),ct(t,4)==="WAVE")}_createDemuxer(e){return new QC(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class aA extends yr{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?ct(t,4)==="OggS":!1}_createDemuxer(e){return new OC(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class oA extends yr{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?ct(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new YC(e)}}class cA extends yr{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,$r);if(a instanceof Promise&&(a=await a),!a)break;const o=ti(a);if(!o)break;t=a.filePos+o.size}let n=e._reader.requestSliceRange(t,Ls,Sn);if(n instanceof Promise&&(n=await n),!n)return!1;const i=jr(n);if(!i||(t+=i.frameLength,n=e._reader.requestSliceRange(t,Ls,Sn),n instanceof Promise&&(n=await n),!n))return!1;const s=jr(n);return s?i.objectType===s.objectType&&i.samplingFrequencyIndex===s.samplingFrequencyIndex&&i.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new zC(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class lA extends yr{async _canReadInput(e){const t=Wt+16+1;let n=e._reader.requestSlice(0,t);if(n instanceof Promise&&(n=await n),!n)return!1;const i=ae(n,t);return i[0]===71&&i[Wt]===71||i[0]===71&&i[Wt+16]===71?!0:i[4]===71&&i[4+Wt+4]===71}_createDemuxer(e){return new qC(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class su extends yr{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(ct(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Xn))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new cI(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Vi}}const au=new tA,ou=new rA,uA=new iu,dA=new nA,cu=new iA,fA=new sA,hA=new aA,lu=new cA,mA=new oA,uu=new lA,du=new su,lI=[du,au,ou,uA,dA,fA,hA,mA,cu,lu,uu],uI=[du,au,ou,cu,lu,uu],dI=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}};/*!
213 * Copyright (c) 2026-present, Vanilagy and contributors
214 *
215 * This Source Code Form is subject to the terms of the Mozilla Public
216 * License, v. 2.0. If a copy of the MPL was not distributed with this
217 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
218 */const fu=new Map,hu=new Map,fI=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&zr(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.codedWidth!==void 0&&(!Number.isInteger(e.codedWidth)||e.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(e.codedHeight!==void 0&&(!Number.isInteger(e.codedHeight)||e.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(e.displayAspectWidth!==void 0&&(!Number.isInteger(e.displayAspectWidth)||e.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(e.displayAspectHeight!==void 0&&(!Number.isInteger(e.displayAspectHeight)||e.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(e.description!==void 0&&!Si(e.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");
218if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},hI=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&zr(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(e.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(e.description!==void 0&&!Si(e.description))throw new TypeError("options.description, when provided, must be a buffer source.")},mI=r=>dt.includes(r)?mu(r):bt.includes(r)?pu(r):!1,mu=async(r,e={})=>{if(!dt.includes(r))return!1;fI(r,e);const t={...e,codedWidth:e.codedWidth??1280,codedHeight:e.codedHeight??720,codec:e.codec??Ep(r,1280,720,1e6)};t.description??(t.description=zS());const n=JSON.stringify(t),i=fu.get(n);if(i)return i;const s=(async()=>Ks.some(o=>o.supports(r,t))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(t)).supported===!0)();return fu.set(n,s),s},pu=async(r,e={})=>{if(!bt.includes(r))return!1;hI(r,e);const t={...e,numberOfChannels:e.numberOfChannels??2,sampleRate:e.sampleRate??48e3,codec:e.codec??Tp(r,2,48e3)};if(t.description===void 0){const a=WS(t);if(a===!1)return!1;t.description=a}const n=JSON.stringify(t),i=hu.get(n);if(i)return i;const s=(async()=>qs.some(o=>o.supports(r,t))||yt.includes(r)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0)();return hu.set(n,s),s},pI=async()=>{const[r,e]=await Promise.all([pA(),gA()]);return[...r,...e]},pA=async(r=dt,e)=>{const t=await Promise.all(r.map(n=>mu(n,e)));return r.filter((n,i)=>t[i])},gA=async(r=bt,e)=>{const t=await Promise.all(r.map(n=>pu(n,e)));return r.filter((n,i)=>t[i])};/*!
219 * Copyright (c) 2026-present, Vanilagy and contributors
220 *
221 * This Source Code Form is subject to the terms of the Mozilla Public
222 * License, v. 2.0. If a copy of the MPL was not distributed with this
223 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
224 */var gI=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},AI=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(o){return t(o),s()})}else i|=1}catch(o){t(o)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});ml();let AA=-1/0,wA=-1/0,rr=null;typeof FinalizationRegistry<"u"&&(rr=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-AA>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),AA=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-wA>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),wA=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class Cn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Ao=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],wI=new Set(Ao);class gt{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(pn*this.timestamp)}get microsecondDuration(){return Math.trunc(pn*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var n,i,s,a,o,c,l,u;if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!wI.has(t.format))throw new TypeError("init.format must be one of: "+Ao.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");
224if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const f of t.layout){if(!f||typeof f!="object"||Array.isArray(f))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(f.offset)||f.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(f.stride)||f.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&up(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=je(e).slice(),this._layout=t.layout??EI(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let d=t.colorSpace??null;d===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?d={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:d={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new wo(d),this.visibleRect={left:((n=t.visibleRect)==null?void 0:n.left)??0,top:((i=t.visibleRect)==null?void 0:i.top)??0,width:((s=t.visibleRect)==null?void 0:s.width)??t.codedWidth,height:((a=t.visibleRect)==null?void 0:a.height)??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if((t==null?void 0:t.rotation)!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t==null?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(t==null?void 0:t.visibleRect)!==void 0&&up(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:((o=e.visibleRect)==null?void 0:o.x)??0,top:((c=e.visibleRect)==null?void 0:c.y)??0,width:((l=e.visibleRect)==null?void 0:l.width)??e.codedWidth,height:((u=e.visibleRect)==null?void 0:u.height)??e.codedHeight},this.rotation=(t==null?void 0:t.rotation)??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=(t==null?void 0:t.timestamp)??e.timestamp/1e6,this.duration=(t==null?void 0:t.duration)??(e.duration??0)/1e6,this.colorSpace=new wo(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new gt(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*pn),duration:Math.trunc((t.duration??0)*pn)||void 0}),t);let d=0,f=0;
224if("naturalWidth"in e?(d=e.naturalWidth,f=e.naturalHeight):"videoWidth"in e?(d=e.videoWidth,f=e.videoHeight):"width"in e&&(d=Number(e.width),f=Number(e.height)),!d||!f)throw new TypeError("Could not determine dimensions.");const h=new OffscreenCanvas(d,f),p=h.getContext("2d",{alpha:Ka(),willReadFrequently:!0});y(p),p.drawImage(e,0,0),this._data=h,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:d,height:f},this.squarePixelWidth=d,this.squarePixelHeight=f,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new wo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Cn){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Ao.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.pixelAspectRatio=Ps({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),rr==null||rr.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(this._data!==null),this._data instanceof Cn?new gt(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):Hs(this._data)?new gt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(y(this._layout),new gt(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new gt(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(rr==null||rr.unregister(this),this._data instanceof Cn?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Hs(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(bA(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Hs(this._data)?this._data.allocationSize(e):EA(this,e).allocationSize}async copyTo(e,t={}){if(!Si(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(bA(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(y(this._data!==null),Hs(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Cn){const l={stack:[],error:void 0,hasError:!1};try{const u=gI(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof gt))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{AI(l)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}const n=EA(this,t);y(this.format);const i=je(e);if(i.byteLength<n.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${n.allocationSize}, Available: ${i.byteLength}`);const s=bo(this.format);let a;if(this._data instanceof Cn){let l=this._data.getDataPlanes();if(l instanceof Promise&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)y(this._layout),y(this._layout.length===s.length),a=this._layout.map((l,u)=>{const d=Math.ceil(this.codedHeight/s[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{const u=this._data.getContext("2d");y(u);const d=u.getImageData(0,0,this.codedWidth,this.codedHeight);
224a=[{data:je(d.data),stride:4*this.codedWidth}]}const o=[],c=s.length;for(let l=0;l<c;l++){const u=n.computedLayouts[l],d=a[l].stride,f=a[l].data;let h=u.sourceTop*d;h+=u.sourceLeftBytes;let p=u.destinationOffset;const m=u.sourceWidthBytes,A={offset:p,stride:u.destinationStride};for(let g=0;g<u.sourceHeight;g++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(p+m>i.byteLength)throw new Error("Destination buffer OOB write.");const w=f.subarray(h,h+m);i.set(w,p),h+=d,p+=u.destinationStride}o.push(A)}if(t.format!==void 0){const l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<n.allocationSize;d+=4){if(l){const f=i[d],h=i[d+2];i[d]=h,i[d+2]=f}u&&(i[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Cn){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),n=new Uint8Array(t);let i=0;const s=[];for(const a of e)n.set(a.data,i),s.push(i),i+=a.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((a,o)=>({offset:s[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Hs(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,i,s,a,o,c,l){let u=0,d=0,f=this.displayWidth,h=this.displayHeight,p=0,m=0,A=this.displayWidth,g=this.displayHeight;if(a!==void 0?(u=t,d=n,f=i,h=s,p=a,m=o,c!==void 0?(A=c,g=l):(A=f,g=h)):(p=t,m=n,i!==void 0&&(A=i,g=s)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(A)||A<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:f,sHeight:h}=this._rotateSourceRegion(u,d,f,h,this.rotation));const w=this.toCanvasImageSource();e.save();const b=p+A/2,k=m+g/2;e.translate(b,k),e.rotate(this.rotation*Math.PI/180);const S=this.rotation%180===0?1:A/g;e.scale(1/S,S),e.drawImage(w,u,d,f,h,-A/2,-g/2,A,g),e.restore()}drawWithFit(e,t){var w,b,k,S;if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");
224if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Gs(t.crop,"options.");const n=e.canvas.width,i=e.canvas.height,s=t.rotation??this.rotation,[a,o]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=yo(c,a,o));let l,u,d,f;const{sx:h,sy:p,sWidth:m,sHeight:A}=this._rotateSourceRegion(((w=t.crop)==null?void 0:w.left)??0,((b=t.crop)==null?void 0:b.top)??0,((k=t.crop)==null?void 0:k.width)??a,((S=t.crop)==null?void 0:S.height)??o,s);if(t.fit==="fill")l=0,u=0,d=n,f=i;else{const[x,B]=t.crop?[t.crop.width,t.crop.height]:[a,o],I=t.fit==="contain"?Math.min(n/x,i/B):Math.max(n/x,i/B);d=x*I,f=B*I,l=(n-d)/2,u=(i-f)/2}e.save();const g=s%180===0?1:d/f;e.translate(n/2,i/2),e.rotate(s*Math.PI/180),e.scale(1/g,g),e.translate(-n/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,p,m,A,l,u,d,f),e.restore()}_rotateSourceRegion(e,t,n,i,s){return s===90?[e,t,n,i]=[t,this.squarePixelHeight-e-n,i,n]:s===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-i]:s===270&&([e,t,n,i]=[this.squarePixelWidth-t-i,e,i,n]),{sx:e,sy:t,sWidth:n,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Cn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Gs(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=Ti(this.rotation+(e.rotate??0)),[n,i]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=e.crop;s&&(s=yo(s,n,i));const a=s?s.width:n,o=s?s.height:i,c=a/o;let l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=al(l,e.roundDimensionsTo??1),u=al(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:s??{left:0,top:0,width:n,height:i},alpha:e.alpha??"keep"};for(const m of gu){let A=m(this,d);if(A instanceof Promise&&(A=await A),A!==null)return A}let f=null,h=!1;for(const m of Vs)if(m.canvas.width===d.width&&m.canvas.height===d.height){f=m.canvas,m.age=yA++;break}if(f===null){if(typeof OffscreenCanvas<"u")f=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");f=document.createElement("canvas"),f.width=d.width,f.height=d.height}h=!0,Vs.length>=bI&&Vs.splice(pl(Vs,m=>m.age),1),Vs.push({canvas:f,age:yA++})}const p=f.getContext("2d",{alpha:!0});return y(p),d.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):h||p.
224clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new gt(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const gu=[],yI=r=>{gu.includes(r)||gu.push(r)},bI=3,Vs=[];let yA=0;class wo{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(Nn);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const n=Object.keys(Qn);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(", ")}.`);const i=Object.keys(Ln);if(e.matrix!=null&&!i.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(e==null?void 0:e.primaries)??null,this.transfer=(e==null?void 0:e.transfer)??null,this.matrix=(e==null?void 0:e.matrix)??null,this.fullRange=(e==null?void 0:e.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Hs=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,yo=(r,e,t)=>{const n=Math.min(r.left,e),i=Math.min(r.top,t),s=Math.min(r.width,e-n),a=Math.min(r.height,t-i);return y(s>=0),y(a>=0),{left:n,top:i,width:s,height:a}},Gs=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},bA=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'dis
224play-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},EI=(r,e,t)=>{const n=bo(r),i=[];let s=0;for(const a of n){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;i.push({offset:s,stride:l}),s+=u}return i},bo=r=>{const e=(t,n,i,s,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:n,widthDivisor:i,heightDivisor:s},{sampleBytes:n,widthDivisor:i,heightDivisor:s}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Ut(r),y(!1)}},EA=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},n=e.rect,i=kI(t,n,r.codedWidth,r.codedHeight,r.format),s=e.layout;let a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return SI(i,a,s)},kI=(r,e,t,n,i)=>{const s={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>n)throw new TypeError("visibleRect exceeds codedHeight.");s.x=e.x||0,s.y=e.y||0,s.width=e.width||0,s.height=e.height||0}if(!TI(i,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},TI=(r,e)=>{if(r===null)return!0;const t=bo(r);for(let n=0;n<t.length;n++){const i=t[n],s=i.widthDivisor,a=i.heightDivisor;if((e.x||0)%s!==0||(e.y||0)%a!==0)return!1}return!0},SI=(r,e,t)=>{const n=bo(e),i=n.length;if(t!==void 0&&t.length!==i)throw new TypeError(`Layout must have ${i} planes.`);let s=0;const a=[],o=[];for(let c=0;c<i;c++){const l=n[c],u=l.sampleBytes,d=l.widthDivisor,f=l.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(r.y||0)/f),h.sourceHeight=Math.ceil(Math.trunc(r.height||0)/f),h.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,h.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){const A=t[c];if(A.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=A.offset,h.destinationStride=A.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(m),s=Math.max(s,m);for(let A=0;A<c;A++){const g=a[A];if(!(o[c]<=g.destinationOffset||o[A]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}},Eo=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Hi{constructor(){this._referenceCount=0}}class kt{get microsecondTimestamp(){return Math.trunc(pn*this.timestamp)}get microsecondDuration(){return Math.trunc(pn*this.duration)}constructor(e){if(this._closed=!1,Ys(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Hi){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Eo.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Eo.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Jn(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const i=this.numberOfFrames*this.numberOfChannels*Jn(this.format);if(n.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=n}rr==null||rr.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Eo.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-n;if(i>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const s=Jn(t),a=Gi(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?i:i*this.numberOfChannels)*s}copyTo(e,t){if(!Si(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Eo.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:n,frameCount:i,frameOffset:s}=t;let{planeIndex:a}=t;const o=this.format,c=n??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const f=i!==void 0?i:l-d;if(f>l-d)throw new RangeError("frameCount out of range");const h=Jn(c),p=Gi(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const A=(p?f:f*u)*h;if(e.byteLength<A)throw new RangeError("Destination buffer is too small");const g=Ae(e),w=TA(c);if(Ys(this._data))Bs()&&u>2&&c!==o?CI(this._data,g,o,c,u,a,d,f):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:c});
224else{const b=kA(o),k=Jn(o),S=Gi(o);let x;if(this._data instanceof Hi){const I=C=>{const v=this._data.getDataPlane(C);if(!(v instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const R=l*k*(S?1:u);if(v.byteLength!==R)throw new TypeError(`Data plane ${C} has invalid size. Expected exactly ${R} bytes, got ${v.byteLength} bytes.`);return v};if(S)if(p)x=I(a),a=0;else{x=new Uint8Array(l*k*u);for(let C=0;C<u;C++){const v=I(C);x.set(v,C*l*k)}}else x=I(0)}else x=this._data;const B=Ae(x);for(let I=0;I<f;I++)if(p){const C=I*h;let v;S?v=(a*l+(I+d))*k:v=((I+d)*u+a)*k;const R=b(B,v);w(g,C,R)}else for(let C=0;C<u;C++){const R=(I*u+C)*h;let M;S?M=(C*l+(I+d))*k:M=((I+d)*u+C)*k;const z=b(B,M);w(g,R,z)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Hi){const e=new kt(this._data);return e.setTimestamp(this.timestamp),e}else if(Ys(this._data)){const e=new kt(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new kt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(rr==null||rr.unregister(this),this._data instanceof Hi?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ys(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Hi?this._createAudioDataFromData():Ys(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Gi(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:"f32-planar"}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i);let c=0,l=a;for(;l>0;){const u=Math.min(o,l),d=new Float32Array(i*u);for(let f=0;f<i;f++)e.copyFromChannel(d.subarray(f*u,(f+1)*u),f,c);yield new kt({format:"f32-planar",sampleRate:s,numberOfFrames:u,numberOfChannels:i,timestamp:t+c/s,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const n=48e3*5,i=e.numberOfChannels,s=e.sampleRate,a=e.length,o=Math.floor(n/i);let c=0,l=a;const u=[];for(;l>0;){const d=Math.min(o,l),f=new Float32Array(i*d);for(let p=0;p<i;p++)e.copyFromChannel(f.subarray(p*d,(p+1)*d),p,c);const h=new kt({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:i,timestamp:t+c/s,data:f});u.push(h),c+=d,l-=d}return u}}const Jn=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Gi=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},kA=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},TA=r=>{switch(r){case"u8":case"u8-planar":return(e,t,n)=>e.setUint8(t,It((n+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,n)=>e.setInt16(t,It(Math.round(n*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,n)=>e.setInt32(t,It(Math.round(n*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,n)=>e.setFloat32(t,n,!0)}},Ys=r=>typeof AudioData<"u"&&r instanceof AudioData,SA=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},CI=(r,e,t,n,i,s,a,o)=>{const c=kA(t),l=TA(n),u=Jn(t),d=Jn(n),f=Gi(t);if(Gi(n))if(f){const p=new ArrayBuffer(o*u),m=Ae(p);r.copyTo(p,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let A=0;A<o;A++){const g=A*u,w=A*d,b=c(m,g);l(e,w,b)}}else{const p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let A=0;A<o;A++){const g=(A*i+s)*u,w=A*d,b=c(m,g);l(e,w,b)}}
224else if(f){const p=o*u,m=new ArrayBuffer(p),A=Ae(m);for(let g=0;g<i;g++){r.copyTo(m,{planeIndex:g,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const b=w*u,k=(w*i+g)*d,S=c(A,b);l(e,k,S)}}}else{const p=new ArrayBuffer(o*i*u),m=Ae(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let A=0;A<o;A++)for(let g=0;g<i;g++){const w=A*i+g,b=w*u,k=w*d,S=c(m,b);l(e,k,S)}}},CA=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),n=new ArrayBuffer(t);return r.copyTo(n,{format:e,planeIndex:0}),new kt({data:n,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};/*!
225 * Copyright (c) 2026-present, Vanilagy and contributors
226 *
227 * This Source Code Form is subject to the terms of the Mozilla Public
228 * License, v. 2.0. If a copy of the MPL was not distributed with this
229 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
230 */const Au=new Map,wu=new Map,yu=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!dt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${dt.join(", ")}.`);if(!(r.bitrate instanceof Ht)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Gs(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");IA(r.codec,r)},IA=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&zr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},BA=r=>{const e=r.bitrate instanceof Ht?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??Ep(r.codec,r.width,r.height,e),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:e,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...VS(r.codec)}},bu=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!bt.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${bt.join(", ")}.`);
230if(r.bitrate===void 0&&!(yt.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(r.bitrate!==void 0&&!(r.bitrate instanceof Ht)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");xA(r.codec,r)},xA=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&zr(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},PA=r=>{const e=r.bitrate instanceof Ht?r.bitrate._toAudioBitrate(r.codec):r.bitrate;return{codec:r.fullCodecString??Tp(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:e,bitrateMode:r.bitrateMode,...HS(r.codec)}};class Ht{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){const i=t*n,s={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(i/a,.95),d=o*c*s[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(yt.includes(e)||e==="flac")return;const n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!n)throw new Error(`Unhandled codec: ${e}`);let i=n*this._factor;return e==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a):e==="opus"||e==="vorbis"?i=Math.max(6e3,i):e==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-i)<Math.abs(a-i)?o:a)),Math.round(i/1e3)*1e3}}const II=new Ht(.3),BI=new Ht(.6),xI=new Ht(1),Eu=new Ht(2),PI=new Ht(4),vI=r=>{if(dt.includes(r))return ko(r);if(bt.includes(r))return To(r);if(gr.includes(r))return So(r);throw new TypeError(`Unknown codec '${r}'.`)},ko=async(r,e={})=>{const{width:t=1280,height:n=720,bitrate:i=1e6,...s}=e;if(!dt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("height must be a positive integer.");if(!(i instanceof Ht)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer or a quality.");IA(r,s);const a=BA({codec:r,width:t,height:n,bitrate:i,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(a),c=Au.get(o);if(c)return c;const l=(async()=>Io.some(f=>f.supports(r,a))?!0:typeof VideoEncoder>"u"||(t%2===1||n%2===1)&&(r==="avc"||r==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:Ka()?new Promise(async f=>{try{const h=new VideoEncoder({output:()=>{},error:()=>f(!1)});h.configure(a);const p=new Uint8Array(t*n*4),m=new VideoFrame(p,{format:"RGBA",codedWidth:t,codedHeight:n,timestamp:0});h.encode(m),m.close(),await h.flush(),f(!0)}catch{f(!1)}}):!0)();return Au.set(o,l),l},To=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:n=48e3,bitrate:i=128e3,...s}=e;if(!bt.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(n)||n<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(i instanceof Ht)&&(!Number.isInteger(i)||i<=0))throw new TypeError("bitrate must be a positive integer.");xA(r,s);const a=PA({codec:r,numberOfChannels:t,sampleRate:n,bitrate:i,...s}),o=JSON.stringify(a),c=wu.get(o);if(c)return c;const l=(async()=>Bo.some(d=>d.supports(r,a))||yt.includes(r)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported(a)).supported===!0)();return wu.set(o,l),l},So=async r=>!!gr.includes(r),_I=async()=>{const[r,e,t]=await Promise.all([vA(),Co(),_A()]);return[...r,...e,...t]},vA=async(r=dt,e)=>{const t=await Promise.all(r.map(n=>ko(n,e)));return r.filter((n,i)=>t[i])},Co=async(r=bt,e)=>{const t=await Promise.all(r.map(n=>To(n,e)));return r.filter((n,i)=>t[i])},_A=async(r=gr)=>{const e=await Promise.all(r.map(So));
230return r.filter((t,n)=>e[n])},FA=async(r,e)=>{for(const t of r)if(await ko(t,e))return t;return null},FI=async(r,e)=>{for(const t of r)if(await To(t,e))return t;return null},RI=async r=>{for(const e of r)if(await So(e))return e;return null};/*!
231 * Copyright (c) 2026-present, Vanilagy and contributors
232 *
233 * This Source Code Form is subject to the terms of the Mozilla Public
234 * License, v. 2.0. If a copy of the MPL was not distributed with this
235 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
236 */class RA{static supports(e,t){return!1}}class DA{static supports(e,t){return!1}}class MA{static supports(e,t){return!1}}class UA{static supports(e,t){return!1}}const Ks=[],qs=[],Io=[],Bo=[],DI=r=>{if(r.prototype instanceof RA){const e=r;if(Ks.includes(e)){console.warn("Video decoder already registered.");return}Ks.push(e),fu.clear()}else if(r.prototype instanceof DA){const e=r;if(qs.includes(e)){console.warn("Audio decoder already registered.");return}qs.push(e),hu.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},MI=r=>{if(r.prototype instanceof MA){const e=r;if(Io.includes(e)){console.warn("Video encoder already registered.");return}Io.push(e),Au.clear()}else if(r.prototype instanceof UA){const e=r;if(Bo.includes(e)){console.warn("Audio encoder already registered.");return}Bo.push(e),wu.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
237 * Copyright (c) 2026-present, Vanilagy and contributors
238 *
239 * This Source Code Form is subject to the terms of the Mozilla Public
240 * License, v. 2.0. If a copy of the MPL was not distributed with this
241 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
242 */const UI=r=>{let n=r,i=4096,s=0,a=12,o=0;for(n<0&&(n=-n,s=128),n+=33,n>8191&&(n=8191);(n&i)!==i&&a>=5;)i>>=1,a--;return o=n>>a-4&15,~(s|a-5<<4|o)&255},OI=r=>{let t=0,n=0,i=~r;i&128&&(i&=-129,t=-1),n=((i&240)>>4)+5;const s=(1<<n|(i&15)<<n-4|1<<n-5)-33;return t===0?s:-s},NI=r=>{let t=2048,n=0,i=11,s=0,a=r;for(a<0&&(a=-a,n=128),a>4095&&(a=4095);(a&t)!==t&&i>=5;)t>>=1,i--;return s=a>>(i===4?1:i-4)&15,(n|i-4<<4|s)^85},QI=r=>{let e=0,t=0,n=r^85;n&128&&(n&=-129,e=-1),t=((n&240)>>4)+4;let i=0;return t!==4?i=1<<t|(n&15)<<t-4|1<<t-5:i=n<<1|1,e===0?i:-i};/*!
243 * Copyright (c) 2026-present, Vanilagy and contributors
244 *
245 * This Source Code Form is subject to the terms of the Mozilla Public
246 * License, v. 2.0. If a copy of the MPL was not distributed with this
247 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
248 */const $n=r=>
248{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Xr=r=>{if(!xi(r))throw new TypeError("timestamp must be a number.")},ku=(r,e,t)=>t.verifyKeyPackets?e.then(async n=>{if(!n||n.type==="delta")return n;const i=await r.determinePacketType(n);return i&&(n.type=i),n}):e;class Yi{constructor(e){if(!(e instanceof Ki))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if($n(e),this._track.input._disposed)throw new Gt;return ku(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){$n(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Xr(e),$n(t),this._track.input._disposed)throw new Gt;return ku(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new Gt;return ku(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Xr(e),$n(t),this._track.input._disposed)throw new Gt;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const n=await this._track._backing.getKeyPacket(e,t);
248return n&&(y(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getKeyPacket(n.timestamp-1/await this._track.getTimeResolution(),t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");if($n(t),this._track.input._disposed)throw new Gt;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const n=await this._track._backing.getNextKeyPacket(e,t);return n&&(y(n.type==="key"),await this._track.determinePacketType(n)==="delta"?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof He))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!(n!=null&&n.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof He))throw new TypeError("endPacket must be an EncodedPacket.");if($n(n),this._track.input._disposed)throw new Gt;const i=[];let{promise:s,resolve:a}=rt(),{promise:o,resolve:c}=rt(),l=!1,u=!1,d=null;const f=[],h=()=>Math.max(2,f.length);(async()=>{let m=e??await this.getFirstPacket(n);for(;m&&!u&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=(t==null?void 0:t.sequenceNumber));){if(i.length>h()){({promise:o,resolve:c}=rt()),await o;continue}i.push(m),a(),{promise:s,resolve:a}=rt(),m=await this.getNextPacket(m,n)}l=!0,a()})().catch(m=>{d||(d=m,a())});const p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new Gt;if(u)return{value:void 0,done:!0};if(d)throw d;if(i.length>0){const m=i.shift(),A=performance.now();for(f.push(A);f.length>0&&A-f[0]>=1e3;)f.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await s}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}}class Tu{constructor(e,t){this.onSample=e,this.onError=t}}class Su{mediaSamplesInRange(e=-1/0,t=1/0,n){Xr(e),Xr(t);const i=[];let s=!1,a=null,{promise:o,resolve:c}=rt(),{promise:l,resolve:u}=rt(),d=!1,f=!1,h=!1,p=null;const m={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const w=await this._createDecoder(I=>{if(u(),I.timestamp>=t&&(f=!0),f){I.close();return}a&&(I.timestamp>e?(i.push(a),s=!0):a.close()),I.timestamp>=e&&(i.push(I),s=!0),a=s?null:I,i.length>0&&(c(),{promise:o,resolve:c}=rt())},I=>{p||(p=I,c())}),b=this._createPacketSink(),k=await b.getKeyPacket(e,m)??await b.getFirstKeyPacket(m);let S=k;const B=b.packets(k??void 0,void 0,m);for(await B.next();S&&!f&&!this._track.input._disposed;){const I=OA(i.length);if(i.length+w.getDecodeQueueSize()>I){({promise:l,resolve:u}=rt()),await l;continue}w.decode(S);const C=await B.next();if(C.done)break;S=C.value}await B.return(),!h&&!this._track.input._disposed&&await w.flush(),w.close(),!s&&a&&i.push(a),d=!0,c()})().catch(w=>{p||(p=w,c())});const A=this._track,g=()=>{a==null||a.close();for(const w of i)w.close()};return{async next(){for(;;){if(A.input._disposed)throw g(),new Gt;if(h)return{value:void 0,done:!0};if(p)throw g(),p;if(i.length>0){const w=i.shift();return u(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return h=!0,f=!0,u(),c(),g(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){ES(e);const n=bS(e),i=[],s=[];let{promise:a,resolve:o}=rt(),{promise:c,resolve:l}=rt(),u=!1,d=!1,f=null;const h=g=>{s.push(g),o(),{promise:a,resolve:o}=rt()},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const g=await this._createDecoder(I=>{if(l(),d){I.close();return}let C=0;for(;i.length>0&&I.timestamp-i[0]>-1e-10;)C++,i.shift();if(C>0)for(let v=0;v<C;v++)h(v<C-1?I.clone():I);else I.close()},I=>{f||(f=I,o())}),w=this._createPacketSink();let b=null,k=null,S=-1;const x=async()=>{y(k);let I=k;for(g.decode(I);I.sequenceNumber<S;){const C=OA(s.length);for(;s.length+g.getDecodeQueueSize()>C&&!d;)({promise:c,resolve:l}=rt()),await c;if(d)break;const v=await w.getNextPacket(I,p);y(v),g.decode(v),I=v}S=-1},B=async()=>{await g.flush();for(let I=0;I<i.length;I++)h(null);i.length=0};for await(const I of n){if(Xr(I),d||this._track.input._disposed)break;const C=await w.getPacket(I,p),v=C&&await w.getKeyPacket(I,p);if(!v){S!==-1&&(await x(),await B()),h(null),b=null;continue}b&&(v.sequenceNumber!==k.sequenceNumber||C.timestamp<b.timestamp)&&(await x(),await B()),i.push(C.timestamp),S=Math.max(C.sequenceNumber,S),b=C,k=v}!d&&!this._track.input._disposed&&(S!==-1&&await x(),await B()),g.close(),u=!0,o()})().catch(g=>{f||(f=g,o())});const m=this._track,A=()=>{for(const g of s)g==null||g.close()};return{async next(){for(;;){if(m.input._disposed)throw A(),new Gt;if(d)return{value:void 0,done:!0};if(f)throw A(),f;if(s.length>0){const g=s.shift();return y(g!==void 0),l(),{value:g,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),A(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}const OA=r=>r===0?40:8;class LI extends Tu{constructor(e,t,n,i,s,a){super(e,t),this.codec=n,this.decoderConfig=i,this.rotation=s,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer
248=new Is,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new Is;const o=Ks.find(c=>c.supports(n,i));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=c=>{if(!(c instanceof gt))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const c=u=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();y(d!==void 0),await this.mergeAlpha(u,d)}else this.colorQueue.push(u)}).catch(d=>this.onError(d))};if(n==="avc"&&this.decoderConfig.description&&dl()){const u=xp(je(this.decoderConfig.description));if(u&&u.sequenceParameterSets.length>0){const d=vl(u.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:u=>{try{c(u)}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e;return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,((e=this.alphaDecoder)==null?void 0:e.decodeQueueSize)??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>
2480&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),Bs()||ip(this.inputTimestamps,e.timestamp,t=>t),dl()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];for(const i of Bp(e.data,this.decoderConfig)){const s=Di(e.data[i.offset]);s>=20&&s<=31||t.push(e.data.subarray(i.offset,i.offset+i.length))}const n=eC(t,this.decoderConfig);e=new He(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=dC(e.data,this.decoderConfig);t&&(e=new He(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new xo),!this.alphaDecoder){const n=s=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();y(a!==void 0),await this.mergeAlpha(a,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();y(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},i=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(a){this.onError(a)}},error:s=>{s.stack=i,this.onError(s)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ao(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>
2480&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of io(e,this.decoderConfig)){const n=bn(e[t.offset]);if(n===pt.RASL_N||n===pt.RASL_R)return!0}return!1}sampleHandler(e){if(Bs()){if(this.sampleQueue.length>0&&e.timestamp>=tt(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ip(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();y(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){const s=new gt(e);this.sampleHandler(s);return}y(this.merger);const n=await this.merger.update(e,t),i=new gt(n);this.sampleHandler(i)}async flush(){var e;if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),await Promise.all([this.decoder.flush(),(e=this.alphaDecoder)==null?void 0:e.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t==null?void 0:t.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Bs()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close(),(e=this.alphaDecoder)==null||e.close(),this.colorQueue.forEach(n=>n.close()),this.colorQueue.length=0,this.alphaQueue.forEach(n=>n==null?void 0:n.close()),this.alphaQueue.length=0,(t=this.merger)==null||t.close());for(const n of this.sampleQueue)n.close();this.sampleQueue.length=0}}let NA=!1;class xo{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!xo.forceCpu&&e&&!NA)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}catch(t){this.gl=null,this.canvas=null,NA=!0,console.warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){y(this.gl);const e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
249			in vec2 a_position;
250			in vec2 a_texCoord;
251			out vec2 v_texCoord;
252			
253			void main() {
254				gl_Position = vec4(a_position, 0.0, 1.0);
255				v_texCoord = a_texCoord;
256			}
257		`),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
258			precision highp float;
259			
260			uniform sampler2D u_colorTexture;
261			uniform sampler2D u_alphaTexture;
262			in vec2 v_texCoord;
263			out vec4 fragColor;
264			
265			void main() {
266				vec3 color = texture(u_colorTexture, v_texCoord).rgb;
267				float alpha = texture(u_alphaTexture, v_texCoord).r;
268				fragColor = vec4(color, alpha);
269			}
270		`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){y(this.gl);const n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){y(this.gl),y(this.program);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){y(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}
270updateGpu(e,t){y(this.gl),y(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const n=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),n}updateCpu(e,t){if(!this.worker){const s=new Blob([`(${zI.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(s);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{const c=o.data,l=this.pendingRequests.get(c.id);l&&(this.pendingRequests.delete(c.id),"error"in c?l.reject(new Error(c.error)):l.resolve(c.frame))}),this.worker.addEventListener("error",o=>{const c=new Error(o.message||"Color/alpha merge worker error.");for(const l of this.pendingRequests.values())l.reject(c);this.pendingRequests.clear()})}const n=this.nextRequestId++,i=rt();return this.pendingRequests.set(n,i),this.worker.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),i.promise}close(){var t,n,i;(n=(t=this.gl)==null?void 0:t.getExtension("WEBGL_lose_context"))==null||n.loseContext(),this.gl=null,this.canvas=null,(i=this.worker)==null||i.terminate(),this.worker=null;const e=new Error("Color/alpha merger closed.");for(const s of this.pendingRequests.values())s.reject(e);this.pendingRequests.clear()}}xo.forceCpu=!0;const zI=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:l,color:u,alpha:d}=c.data;t=t.then(async()=>{try{const f=await n(u,d);self.postMessage({id:l,frame:f},{transfer:[f]})}catch(f){self.postMessage({id:l,error:f.message})}finally{u.close(),d.close()}})});const n=async(c,l)=>{const u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const f=u.includes("P10"),h=u.includes("P12"),p=d.includes("P10"),m=d.includes("P12");if(p!==f||m!==h)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);const A=c.codedWidth,g=c.codedHeight;if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await i(c,l,A,g,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await s(c,l,A,g,u);if(u==="NV12")return await a(c,l,A,g);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},i=async(c,l,u,d,f)=>{const h=u*d,p=new Uint8Array(h*4);await c.copyTo(p);const m=await o(l,u,d,1);for(let w=0,b=3;w<h;w++,b+=4)p[b]=m[w];const g={format:f==="RGBX"||f==="RGBA"?"RGBA":"BGRA",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,g)},s=async(c,l,u,d,f)=>{const h=f.includes("P10"),p=f.includes("P12"),m=h||p?2:1;let A,g;f.startsWith("I420")?(A=Math.ceil(u/2),g=Math.ceil(d/2)):f.startsWith("I422")?(A=Math.ceil(u/2),g=d):(A=u,g=d);const w=u*d,b=A*g,k=w*m,S=b*m,x=w*m,B=k+2*S+x,I=new Uint8Array(B);await c.copyTo(I);const C=await o(l,u,d,m),v=k+2*S;I.set(C,v);const M={format:f.slice(0,4)+"A"+f.slice(4),codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[I.buffer]};return new VideoFrame(I,M)},a=async(c,l,u,d)=>{const f=u*d,h=Math.ceil(u/2),p=Math.ceil(d/2),m=h*p,A=c.allocationSize();(!e||e.byteLength!==A)&&(e=new Uint8Array(A)),await c.copyTo(e);const g=new Uint8Array(f+2*m+f);g.set(e.subarray(0,f),0);const w=f,b=f+m,k=f;for(let B=0;B<m;B++)g[w+B]=e[k+B*2],g[b+B]=e[k+B*2+1];const S=await o(l,u,d,1);g.set(S,f+2*m);const x={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,x)},o=async(c,l,u,d)=>{const f=c.allocationSize();(!r||r.byteLength!==f)&&(r=new Uint8Array(f)),await c.copyTo(r);const h=c.format;if(h==="RGBA"||h==="BGRA"||h==="RGBX"||h==="BGRX"){const p=h==="RGBA"||h==="RGBX"?0:2,m=l*u;for(let A=0;A<m;A++)r[A]=r[A*4+p];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}};class Po extends Su{constructor(e){if(!(e instanceof js))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const n=await this._track.getCodec(),i=await this._track.getRotation(),s=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return y(n&&s),new LI(e,t,n,s,i,a)}_createPacketSink(){return new Yi(this._track)}async getSample(e,t={}){Xr(e);for await(const n of this.mediaSamplesAtTimestamps([e],t))return n;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class WI{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof js))throw new TypeError("videoTrack must be an InputVideoTrack.");
270if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Gs(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Po(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),i=await t.getSquarePixelWidth(),s=await t.getSquarePixelHeight(),[a,o]=n%180===0?[i,s]:[s,i];let c=e.crop;c&&(c=yo(c,a,o));let[l,u]=c?[c.width,c.height]:[a,o];const d=l/u;e.width!==void 0&&e.height===void 0?(l=e.width,u=Math.round(l/d)):e.width===void 0&&e.height!==void 0?(u=e.height,l=Math.round(u*d)):e.width!==void 0&&e.height!==void 0&&(l=e.width,u=e.height),this._width=l,this._height=u,this._rotation=n,this._crop=c})())}_videoSampleToWrappedCanvas(e){const t=this._width,n=this._height;let i=this._canvasPool[this._nextCanvasIndex],s=!1;i||(typeof document<"u"?(i=document.createElement("canvas"),i.width=t,i.height=n):i=new OffscreenCanvas(t,n),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=i),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=i.getContext("2d",{alpha:this._alpha||Ka()});y(a),a.resetTransform(),s||(!this._alpha&&Ka()?(a.fillStyle="black",a.fillRect(0,0,t,n)):a.clearRect(0,0,t,n)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:i,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Xr(e),await this._ensureInit();const n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*Ya(this._videoSampleSink.samples(e,t,n),i=>this._videoSampleToWrappedCanvas(i))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Ya(this._videoSampleSink.samplesAtTimestamps(e,t),n=>n&&this._videoSampleToWrappedCanvas(n))}}class VI extends Tu{constructor(e,t,n,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Is,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const s=o=>{let c=o.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-c),c+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(c-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=c);const l=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const u=i.sampleRate;o.setTimestamp(Math.round(l*u)/u),e(o)},a=qs.find(o=>o.supports(n,i));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=i,this.customDecoder.onSample=o=>{if(!(o instanceof kt))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{s(new kt(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(y(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close())}}class HI extends Tu{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,y(yt.includes(n.codec)),this.codec=n.codec;const{dataType:i,sampleSize:s,littleEndian:a}=Ar(this.codec);switch(this.inputSampleSize=s,s){case 1:i==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:i==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):i==="ulaw"?this.readInputValue=(o,c)=>OI(o.getUint8(c)):i==="alaw"?this.readInputValue=(o,c)=>
270QI(o.getUint8(c)):y(!1);break;case 2:i==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:i==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):y(!1);break;case 3:i==="unsigned"?this.readInputValue=(o,c)=>Ha(o,c,a)-2**23:i==="signed"?this.readInputValue=(o,c)=>kS(o,c,a):y(!1);break;case 4:i==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:i==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):i==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):y(!1);break;case 8:i==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):y(!1);break;default:Ut(s),y(!1)}switch(s){case 1:i==="ulaw"||i==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,i==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:Ut(s),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=Ae(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(i),a=new DataView(s);for(let u=0;u<n*this.decoderConfig.numberOfChannels;u++){const d=u*this.inputSampleSize,f=u*this.outputSampleSize,h=this.readInputValue(t,d);this.writeOutputValue(a,f,h)}const o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const l=new kt({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:c});this.onSample(l)}async flush(){}close(){}}class vo extends Su{constructor(e){if(!(e instanceof Xs))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const n=await this._track.getCodec(),i=await this._track.getDecoderConfig();return y(n&&i),yt.includes(i.codec)?new HI(e,t,i):new VI(e,t,n,i)}_createPacketSink(){return new Yi(this._track)}async getSample(e,t={}){Xr(e);for await(const n of this.mediaSamplesAtTimestamps([e],t))return n;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class GI{constructor(e){if(!(e instanceof Xs))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new vo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Xr(e);const n=await this._audioSampleSink.getSample(e,t);return n&&this._audioSampleToWrappedArrayBuffer(n)}buffers(e,t,n){return Ya(this._audioSampleSink.samples(e,t,n),i=>this._audioSampleToWrappedArrayBuffer(i))}buffersAtTimestamps(e,t){return Ya(this._audioSampleSink.samplesAtTimestamps(e,t),n=>n&&this._audioSampleToWrappedArrayBuffer(n))}}/*!
271 * Copyright (c) 2026-present, Vanilagy and contributors
272 *
273 * This Source Code Form is subject to the terms of the Mozilla Public
274 * License, v. 2.0. If a copy of the MPL was not distributed with this
275 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
276 */class Ki{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof js}isAudioTrack(){return this instanceof Xs}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return nt(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return nt(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return nt(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return nt(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return nt(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return(e==null?void 0:e.timestamp)??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}
276),n=((t==null?void 0:t.timestamp)??0)+((t==null?void 0:t.duration)??0);return Ci(n,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const n=new Yi(this);let i=1/0,s=-1/0,a=0,o=0;for await(const c of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=s)break;i=Math.min(i,c.timestamp),s=Math.max(s,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(s-i)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(s-i)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Ki))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Zn({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Zn({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Zn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Zn({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Zn({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=Cu(e));const t=await this.input.getTracks();for(const n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=Cu(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=Cu(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const nt=(r,e,t)=>{if(r instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},Cu=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=i=>{if(typeof i!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return i},n=r(e);return n instanceof Promise?n.then(t):t(n)}:void 0};class js extends Ki{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return nt(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return nt(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return nt(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return nt(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return nt(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return nt(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ps({num:await this.get
276SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ps({num:nt(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*nt(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:nt(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*nt(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){var n,i;const e=await((i=(n=this._backing).getMetadataDisplayWidth)==null?void 0:i.call(n));return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){var i,s;const e=(s=(i=this._backing).getMetadataDisplayWidth)==null?void 0:s.call(i);if(e!==void 0){const a=nt(e,"displayWidth","getDisplayWidth");if(a!==null)return a}const n=nt(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return nt(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){var n,i;const e=await((i=(n=this._backing).getMetadataDisplayHeight)==null?void 0:i.call(n));return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){var i,s;const e=(s=(i=this._backing).getMetadataDisplayHeight)==null?void 0:s.call(i);if(e!==void 0){const a=nt(e,"displayHeight","getDisplayHeight");if(a!==null)return a}const n=nt(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return nt(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}
276async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var n,i;const e=await((i=(n=this._backing).getMetadataCodecParameterString)==null?void 0:i.call(n));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),Ks.some(i=>i.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const n=await this.getDecoderConfig();return y(n),ao(t,n,e.data)}}class Xs extends Ki{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return nt(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return nt(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return nt(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var n,i;const e=await((i=(n=this._backing).getMetadataCodecParameterString)==null?void 0:i.call(n));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),qs.some(n=>n.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const YI=r=>r??1/0,Iu=r=>-(r??-1/0),qi=r=>-r,Js=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{const t=i=>{if(typeof i!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return i},n=r.filter(e);return n instanceof Promise?n.then(t):t(n)}:void 0,sortBy:r.sortBy?e=>{const t=i=>{if(typeof i!="number"&&(!Array.isArray(i)||!i.every(s=>typeof s=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return i},n=r.sortBy(e);return n instanceof Promise?n.then(t):t(n)}:void 0}},Zn=(r,e)=>({filter:r!=null&&r.filter||e!=null&&e.filter?t=>{var s;const n=((s=r==null?void 0:r.filter)==null?void 0:s.call(r,t))??!0,i=a=>{var o;return a===!1?!1:((o=e==null?void 0:e.filter)==null?void 0:o.call(e,t))??!0};return n instanceof Promise?n.then(i):i(n)}:void 0,sortBy:r!=null&&r.sortBy||e!=null&&e.sortBy?t=>{var a,o;const n=((a=r==null?void 0:r.sortBy)==null?void 0:a.call(r,t))??[],i=((o=e==null?void 0:e.sortBy)==null?void 0:o.call(e,t))??[],s=(c,l)=>[...Array.isArray(c)?c:[c],...Array.isArray(l)?l:[l]];return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([c,l])=>s(c,l)):s(n,i)}:void 0}),Bu=async(r,e)=>{let t=r;if(e!=null&&e.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){const c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!(e!=null&&e.sortBy))return t;const n=t.map(a=>e.sortBy(a)),s=n.some(a=>a instanceof Promise)?await Promise.all(n):n;return t.map((a,o)=>({track:a,sortValue:s[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){const f=c[d]??0,h=l[d]??0;if(f!==h)return f-h}return 0}).map(a=>a.track)};/*!
277 * Copyright (c) 2026-present, Vanilagy and contributors
278 *
279 * This Source Code Form is subject to the terms of the Mozilla Public
280 * License, v. 2.0. If a copy of the MPL was not distributed with this
281 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
282 */ml();const KI=1,qI=2;class $s extends _s{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof yr)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof tr||e.source instanceof po))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof tr&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof $s))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&dI(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof tr?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){y(this._rootSource instanceof Xn);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=KI){const n=this._sourceCache.find(a=>a.cacheGroup===t&&Wg(a.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());const i=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Wg(a.request,e));if(i)return i.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(xs(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=pl(this._sourceCache,h=>h.cacheGroup===t&&h.sourceRef.source._refCount===1?h.age:1/0);y(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),sp(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(d=>d.request===e);return y(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{var e;this._reader=new _o(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});
282for(const t of this._formats)if(await t._canReadInput(this))return this._format=t,(e=this._onFormatDetermined)==null||e.call(this,t),t._createDemuxer(this);throw new xu})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),y(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof xu)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(i=>i!==null);if(t.length===0)return 0;const n=await Promise.all(t.map(i=>i.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??(e=await this.getTracks());const n=e.filter(s=>s!==null);if(n.length===0)return 0;const i=await Promise.all(n.map(s=>s.computeDuration(t)));return Math.max(...i)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const n=e.filter(a=>a!==null),s=(await Promise.all(n.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&(e=Js(e));const n=(await this._getTrackBackings()).map(i=>this._wrapBackingAsTrack(i));return Bu(n,e)}async getVideoTracks(e){e&&(e=Js(e));const n=(await this.getTracks()).filter(i=>i.isVideoTrack());return Bu(n,e)}async getAudioTracks(e){e&&(e=Js(e));const n=(await this.getTracks()).filter(i=>i.isAudioTrack());return Bu(n,e)}async getPrimaryVideoTrack(e){e&&(e=Js(e));const t=Zn(e,{sortBy:async i=>[qi((await i.getDisposition()).default),qi(await i.hasPairableAudioTrack()),qi(!await i.hasOnlyKeyPackets()),Iu(await i.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Js(e));const t=await this.getPrimaryVideoTrack(),n=Zn(e,{sortBy:async s=>[qi(!t||s.canBePairedWith(t)),qi((await s.getDisposition()).default),Iu(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i=e.getType()==="video"?new js(this,e):new Xs(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){var e;if(!this._disposed){this._disposed=!0;for(const t of this._sourceRefs)t.free();this._sourceRefs.length=0,(e=this._demuxerPromise)==null||e.then(t=>t.dispose())}}[Symbol.dispose](){this.dispose()}}class xu extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Gt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*!
283 * Copyright (c) 2026-present, Vanilagy and contributors
284 *
285 * This Source Code Form is subject to the terms of the Mozilla Public
286 * License, v. 2.0. If a copy of the MPL was not distributed with this
287 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
288 */class _o{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Gt;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new Nt(s,Ae(s),0,e,e)}const n=e+t,i=this.source._read(e,n,Lg,zg);return i instanceof Promise?i.then(s=>s?new Nt(s.bytes,s.view,s.offset,e,n):null):i?new Nt(i.bytes,i.view,i.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new Gt;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,It(this.fileSizeNonStrict-e,t,n));{const i=this.requestSlice(e,n),s=a=>a||(y(this.fileSizeNonStrict!==null),this.requestSlice(e,It(this.fileSizeNonStrict-e,t,n)));return i instanceof Promise?i.then(s):s(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let n=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const a=t.length*e;let o=this.requestSliceRange(a,0,e);
288if(o instanceof Promise&&(o=await o),!o)break;t.push(ae(o,o.length)),n+=o.length}const i=new Uint8Array(n);let s=0;for(const a of t)i.set(a,s),s+=a.length;return new Nt(i,Ae(i),0,0,n)})()}}class Nt{constructor(e,t,n,i,s){this.bytes=e,this.view=t,this.offset=n,this.start=i,this.end=s,this.bufferPos=i-n}static tempFromBytes(e){return new Nt(e,Ae(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Nt(this.bytes,this.view,this.offset,e,e+t)}}const Yt=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},ae=(r,e)=>{Yt(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},se=r=>(Yt(r,1),r.view.getUint8(r.bufferPos++)),Zs=(r,e)=>{Yt(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},At=r=>{Yt(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},Jr=r=>{Yt(r,3);const e=Ha(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Pu=r=>{Yt(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},In=(r,e)=>{Yt(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},q=r=>{Yt(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},ji=r=>{Yt(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},ei=r=>{Yt(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},jI=r=>{Yt(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},QA=(r,e)=>{let t,n;return e?(t=In(r,!0),n=In(r,!0)):(n=In(r,!1),t=In(r,!1)),n*4294967296+t},fr=r=>{const e=q(r),t=q(r);return e*4294967296+t},XI=r=>{const e=ei(r),t=q(r);return e*4294967296+t},JI=r=>{const e=ji(r);return jI(r)*4294967296+e},$I=r=>{Yt(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},LA=r=>{Yt(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},ct=(r,e)=>{Yt(r,e);let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},zA=(r,e,t)=>Jt.decode(ae(r,e)).split(`
289`).map(s=>s.trim()).filter(s=>{var a;return s.length>0&&!((a=t==null?void 0:t.ignore)!=null&&a.call(t,s))});/*!
290 * Copyright (c) 2026-present, Vanilagy and contributors
291 *
292 * This Source Code Form is subject to the terms of the Mozilla Public
293 * License, v. 2.0. If a copy of the MPL was not distributed with this
294 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
295 */var Xi;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Xi||(Xi={}));var xt;(function(r){r[r.ISO_8859_1=0]="ISO_8859_1",r[r.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",r[r.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",r[r.UTF_8=3]="UTF_8"})(xt||(xt={}));const Fo=128,$r=10,Ji=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Po
295p-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],ZI=(r,e)=>{var d;const t=r.filePos;e.raw??(e.raw={}),(d=e.raw).TAG??(d.TAG=ae(r,Fo-3)),r.filePos=t;const n=$i(r,30);n&&(e.title??(e.title=n));const i=$i(r,30);i&&(e.artist??(e.artist=i));const s=$i(r,30);s&&(e.album??(e.album=s));const a=$i(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??(e.date=new Date(String(o))));const c=ae(r,30);let l;if(c[28]===0&&c[29]!==0){const f=c[29];f>0&&(e.trackNumber??(e.trackNumber=f)),r.skip(-30),l=$i(r,28),r.skip(2)}else r.skip(-30),l=$i(r,30);l&&(e.comment??(e.comment=l));const u=se(r);u<Ji.length&&(e.genre??(e.genre=Ji[u]))},$i=(r,e)=>{const t=ae(r,e),n=Ii(t.indexOf(0),t.length),i=t.subarray(0,n);let s="";for(let a=0;a<i.length;a++)s+=String.fromCharCode(i[a]);return s.trimEnd()},ti=r=>{const e=r.filePos,t=ct(r,3),n=se(r),i=se(r),s=se(r),a=q(r);if(t!=="ID3"||n===255||i===255||(a&2155905152)!==0)return r.filePos=e,null;const o=Cl(a);return{majorVersion:n,revision:i,flags:s,size:o}},vu=(r,e,t)=>{var s,a,o,c,l;if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const n=ae(r,e.size),i=new eB(e,n);if(e.flags&Xi.Footer&&i.removeFooter(),e.flags&Xi.Unsynchronisation&&e.majorVersion===3&&i.ununsynchronizeAll(),e.flags&Xi.ExtendedHeader){const u=i.readU32();e.majorVersion===3?i.pos+=u:i.pos+=u-4}for(;i.pos<=i.bytes.length-i.frameHeaderSize();){const u=i.readId3V2Frame();if(!u)break;const d=i.pos,f=i.pos+u.size;let h=!1,p=!1,m=!1;if(e.majorVersion===3?(h=!!(u.flags&64),p=!!(u.flags&128)):e.majorVersion===4&&(h=!!(u.flags&4),p=!!(u.flags&8),m=!!(u.flags&2)||!!(e.flags&Xi.Unsynchronisation)),h){console.warn(`Skipping encrypted ID3v2 frame ${u.id}`),i.pos=f;continue}if(p){console.warn(`Skipping compressed ID3v2 frame ${u.id}`),i.pos=f;continue}if(m&&i.ununsynchronizeRegion(i.pos,f),t.raw??(t.raw={}),u.id==="TXXX"){const A=(s=t.raw).TXXX??(s.TXXX={}),g=i.readId3V2TextEncoding(),w=i.readId3V2Text(g,f),b=i.readId3V2Text(g,f);A[w]??(A[w]=b)}else u.id[0]==="T"?(a=t.raw)[o=u.id]??(a[o]=i.readId3V2EncodingAndText(f)):(c=t.raw)[l=u.id]??(c[l]=i.readBytes(u.size));switch(i.pos=d,u.id){case"TIT2":case"TT2":t.title??(t.title=i.readId3V2EncodingAndText(f));break;case"TIT3":case"TT3":t.description??(t.description=i.readId3V2EncodingAndText(f));break;case"TPE1":case"TP1":t.artist??(t.artist=i.readId3V2EncodingAndText(f));break;case"TALB":case"TAL":t.album??(t.album=i.readId3V2EncodingAndText(f));break;case"TPE2":case"TP2":t.albumArtist??(t.albumArtist=i.readId3V2EncodingAndText(f));break;case"TRCK":case"TRK":{const g=i.readId3V2EncodingAndText(f).split("/"),w=Number.parseInt(g[0],10),b=g[1]&&Number.parseInt(g[1],10);Number.isInteger(w)&&w>0&&(t.trackNumber??(t.trackNumber=w)),b&&Number.isInteger(b)&&b>0&&(t.tracksTotal??(t.tracksTotal=b))}break;case"TPOS":case"TPA":{const g=i.readId3V2EncodingAndText(f).split("/"),w=Number.parseInt(g[0],10),b=g[1]&&Number.parseInt(g[1],10);Number.isInteger(w)&&w>0&&(t.discNumber??(t.discNumber=w)),b&&Number.isInteger(b)&&b>0&&(t.discsTotal??(t.discsTotal=b))}break;case"TCON":case"TCO":{const A=i.readId3V2EncodingAndText(f);let g=/^\((\d+)\)/.exec(A);if(g){const w=Number.parseInt(g[1]);if(Ji[w]!==void 0){t.genre??(t.genre=Ji[w]);break}}if(g=/^\d+$/.exec(A),g){const w=Number.parseInt(g[0]);if(Ji[w]!==void 0){t.genre??(t.genre=Ji[w]);break}}t.genre??(t.genre=A)}break;case"TDRC":case"TDAT":{const A=i.readId3V2EncodingAndText(f),g=new Date(A);Number.isNaN(g.getTime())||(t.date??(t.date=g))}break;case"TYER":case"TYE":{const A=i.readId3V2EncodingAndText(f),g=Number.parseInt(A,10);Number.isInteger(g)&&(t.date??(t.date=new Date(String(g))))}break;case"USLT":case"ULT":{const A=i.readU8();i.pos+=3,i.readId3V2Text(A,f),t.lyrics??(t.lyrics=i.readId3V2Text(A,f))}break;case"COMM":case"COM":{const A=i.readU8();i.pos+=3,i.readId3V2Text(A,f),t.comment??(t.comment=i.readId3V2Text(A,f))}break;case"APIC":case"PIC":{const A=i.readId3V2TextEncoding();let g;if(e.majorVersion===2){const S=i.readAscii(3);g=S==="PNG"?"image/png":S==="JPG"?"image/jpeg":"image/*"}else g=i.readId3V2Text(A,f);const w=i.readU8(),b=i.readId3V2Text(A,f).trimEnd(),k=f-i.pos;if(k>=0){const S=i.readBytes(k);t.images||(t.images=[]),t.images.push({data:S,mimeType:g,kind:w===3?"coverFront":w===4?"coverBack":"unknown",de
295scription:b})}}break;default:i.pos+=u.size;break}i.pos=f}};class eB{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const n=[];for(let a=e;a<t;a++){const o=this.bytes[a];n.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}const i=this.bytes.subarray(0,e),s=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+n.length+s.length),this.bytes.set(i,0),this.bytes.set(n,i.length),this.bytes.set(s,i.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-$r),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const t=this.readU24();return{id:e,size:t,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const t=this.readU32();let n=this.header.majorVersion===4?Cl(t):t;const i=this.readU16(),s=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const l=this.readAscii(4);if(l!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(l))return!1}return!0};if(!a(n)){const o=this.header.majorVersion===4?t:Cl(t);a(o)&&(n=o)}return this.pos=s,{id:e,size:n,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const n=this.pos,i=this.readBytes(t-this.pos);switch(e){case xt.ISO_8859_1:{let s="";for(let a=0;a<i.length;a++){const o=i[a];if(o===0){this.pos=n+a+1;break}s+=String.fromCharCode(o)}return s}case xt.UTF_16_WITH_BOM:if(i[0]===255&&i[1]===254){const s=new TextDecoder("utf-16le"),a=Ii(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else if(i[0]===254&&i[1]===255){const s=new TextDecoder("utf-16be"),a=Ii(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(2,a))}else{const s=Ii(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),Jt.decode(i.subarray(0,s))}case xt.UTF_16_BE_NO_BOM:{const s=new TextDecoder("utf-16be"),a=Ii(i.findIndex((o,c)=>o===0&&i[c+1]===0&&c%2===0),i.length);return this.pos=n+Math.min(a+2,i.length),s.decode(i.subarray(0,a))}case xt.UTF_8:{const s=Ii(i.findIndex(a=>a===0),i.length);return this.pos=n+Math.min(s+1,i.length),Jt.decode(i.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class _u{constructor(e){this.helper=new Uint8Array(8),this.helperView=Ae(this.helper),this.writer=e}writeId3V2Tag(e){const t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);const n=this.writer.getPos(),i=new Set;for(const{key:o,value:c}of Bi(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),i.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),i.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),i.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),i.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),i.add("TPE2");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),i.add("TRCK")}break;case"discNumber":{const l=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),i.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),i.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),i.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(c),i.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),i.add("COMM");break;case"images":{const l={coverFront:3,coverBack:4,unknown:0};for(const u of c){const d=l[u.kind]??0,f=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,f,u.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;
295default:Ut(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||i.has(o))continue;let l;if(typeof c=="string")if(Qr(c)){l=new Uint8Array(c.length+2),l[0]=xt.ISO_8859_1;for(let d=0;d<c.length;d++)l[d+1]=c.charCodeAt(d)}else{const d=Ve.encode(c);l=new Uint8Array(d.byteLength+2),l[0]=xt.UTF_8,l.set(d,1)}else if(c instanceof Uint8Array)l=c;else if(o==="TXXX"&&mp(c)){for(const u in c){const d=c[u],f=Qr(u)&&Qr(d),h=f?null:Ve.encode(u),p=f?null:Ve.encode(d),m=f?u.length:h.byteLength,A=f?d.length:p.byteLength,g=1+m+1+A+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(g),this.writeU16(0),this.writeU8(f?xt.ISO_8859_1:xt.UTF_8),f?(this.writeIsoString(u),this.writeIsoString(d)):(this.writer.write(h),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}const s=this.writer.getPos(),a=s-n;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(s),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(ZS(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);this.writer.write(t)}writeUtf8String(e){const t=Ve.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const n=Qr(t),s=1+(n?t.length:Ve.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(n?xt.ISO_8859_1:xt.UTF_8),n?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=Qr(e),n="",i=4+n.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(i),this.writeU16(0),this.writeU8(t?xt.ISO_8859_1:xt.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(n),this.writeIsoString(e)):(this.writeUtf8String(n),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=Qr(e),n=t?e.length:Ve.encode(e).byteLength,i="",s=4+i.length+1+n+1;this.writeAscii("COMM"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?xt.ISO_8859_1:xt.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,n,i){const s=Qr(e)&&Qr(n),a=s?n.length:Ve.encode(n).byteLength,o=1+e.length+1+1+a+1+i.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(s?xt.ISO_8859_1:xt.UTF_8),s?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),s?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(i)}}/*!
296 * Copyright (c) 2026-present, Vanilagy and contributors
297 *
298 * This Source Code Form is subject to the terms of the Mozilla Public
299 * License, v. 2.0. If a copy of the MPL was not distributed with this
300 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
301 */class Zr{constructor(e){this.mutex=new zn,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(n&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),i.maxTimestampBeforeLastKeyPacket!==null&&t<i.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,t)}else{if(!n)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}}}/*!
302 * Copyright (c) 2026-present, Vanilagy and contributors
303 *
304 * This Source Code Form is subject to the terms of the Mozilla Public
305 * License, v. 2.0. If a copy of the MPL was not distributed with this
306 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
307 */class tB extends Zr{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),Fs(this.output._metadataTags)||new _u(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,t,n){var s;const i=await this.mutex.acquire();
307try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){yn(n);const a=(s=n==null?void 0:n.decoderConfig)==null?void 0:s.description;if(this.inputIsAdts=!a,!this.inputIsAdts){const o=Rs(je(a)),c=pp(o);this.header=c.header,this.headerBitstream=c.bitstream}}if(this.inputIsAdts){const a=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,a)}else{y(this.header);const a=t.data.byteLength+this.header.byteLength;gp(this.headerBitstream,a);const o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const c=new Uint8Array(a);c.set(this.header,0),c.set(t.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){(await this.mutex.acquire())()}}/*!
308 * Copyright (c) 2026-present, Vanilagy and contributors
309 *
310 * This Source Code Form is subject to the terms of the Mozilla Public
311 * License, v. 2.0. If a copy of the MPL was not distributed with this
312 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
313 */const WA=new Uint8Array([102,76,97,67]),rB=38,nB=34;class iB extends Zr{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(WA),e()}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:a,channels:o,totalSamples:c}){y(this.writer.getPos()===4);const l=!Fs(this.output._metadataTags),u=new Ce(new Uint8Array(4));u.writeBits(1,+!l),u.writeBits(7,Wr.STREAMINFO),u.writeBits(24,nB),this.writer.write(u.bytes);const d=new Ce(new Uint8Array(18));if(d.writeBits(16,t),d.writeBits(16,n),d.writeBits(24,i),d.writeBits(24,s),d.writeBits(20,a),d.writeBits(3,o-1),d.writeBits(5,e-1),c>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){var o,c,l;const t=32+e.mimeType.length+(((o=e.description)==null?void 0:o.length)??0)+e.data.length,n=new Uint8Array(t);let i=0;const s=Ae(n);s.setUint32(i,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),i+=4,s.setUint32(i,e.mimeType.length),i+=4,n.set(Ve.encode(e.mimeType),8),i+=e.mimeType.length,s.setUint32(i,((c=e.description)==null?void 0:c.length)??0),i+=4,n.set(Ve.encode(e.description??""),i),i+=((l=e.description)==null?void 0:l.length)??0,i+=16,s.setUint32(i,e.data.length),i+=4,n.set(e.data,i),i+=e.data.length,y(i===t);const a=new Ce(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,Wr.PICTURE),a.writeBits(24,t),this.writer.write(a.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(rB+WA.byteLength),Fs(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const i of e)this.writePictureBlock(i);const t=Rl(new Uint8Array(0),this.output._metadataTags,!1),n=new Ce(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,Wr.VORBIS_COMMENT),n.writeBits(24,t.length),this.writer.write(n.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null){yn(n),y(n),y(n.decoderConfig),y(n.decoderConfig.description),this.sampleRate=n.decoderConfig.sampleRate,this.channels=n.decoderConfig.numberOfChannels;const d=new Ce(je(n.decoderConfig.description));d.skipBits(167);const f=d.readBits(5)+1;this.bitsPerSample=f,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const s=Nt.tempFromBytes(t.data);s.skip(2);const a=ae(s,2),o=new Ce(a),c=yg(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");bg(s);const l=Eg(s,c);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(t.data.length));const u=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,u),await this.writer.flush()}finally{i()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(!this.format._options.appendOnly){let t=1/0,n=0,i=1/0,s=0,a=0;for(let o=0;o<this.blockSizes.length;o++)i=Math.min(i,this.frameSizes[o]),s=Math.max(s,this.frameSizes[o]),n=Math.max(n,this.blockSizes[o]),a+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));y(this.sampleRate!==null),y(this.channels!==null),y(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:n,minimumFrameSize:i,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}/*!
314 * Copyright (c) 2026-present, Vanilagy and contributors
315 *
316 * This Source Code Form is subject to the terms of the Mozilla Public
317 * License, v. 2.0. If a copy of the MPL was not distributed with this
318 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
319 */const ea=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,sB=/^WEBVTT(.|\n)*?\n{2}/,Ro=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class aB{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
320`,`
321`).replaceAll("\r",`
322`),ea.lastIndex=0;let t;if(!this.preambleText){if(!sB.test(e))throw new Error("WebVTT preamble incorrect.");t=ea.exec(e);const n=e.slice(0,(t==null?void 0:t.index)??e.length).trimEnd();if(!n)throw new Error("No WebVTT preamble provided.");this.preambleText=n,t&&(e=e.slice(t.index),ea.lastIndex=0)}for(;t=ea.exec(e);){const n=e.slice(0,t.index),i=t[1],s=t.index+t[0].length,a=e.indexOf(`
323`,s)+1,o=e.slice(s,a).trim();let c=e.indexOf(`
324
325`,s);c===-1&&(c=e.length);const l=Fu(t[2]),d=Fu(t[3])-l,f=e.slice(a,c).trim();e=e.slice(c).trimStart(),ea.lastIndex=0;const h={timestamp:l/1e3,duration:d/1e3,text:f,identifier:i,settings:o,notes:n},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,p)}}}const oB=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Fu=r=>{const e=oB.exec(r);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},VA=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),n=Math.floor(r%(60*1e3)/1e3),i=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};/*!
326 * Copyright (c) 2026-present, Vanilagy and contributors
327 *
328 * This Source Code Form is subject to the terms of the Mozilla Public
329 * License, v. 2.0. If a copy of the MPL was not distributed with this
330 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
331 */class Do{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const s of e.children)s&&this.writeBox(s);const n=this.writer.getPos(),i=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);y(t!==void 0);const n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const n of e.children)n&&(t+=this.measureBox(n));return t}}}const Se=new Uint8Array(8),hr=new DataView(Se.buffer),ft=r=>[(r%256+256)%256],de=r=>(hr.setUint16(0,r,!1),[Se[0],Se[1]]),Ru=r=>(hr.setInt16(0,r,!1),[Se[0],Se[1]]),HA=r=>(hr.setUint32(0,r,!1),[Se[1],Se[2],Se[3]]),Y=r=>(hr.setUint32(0,r,!1),[Se[0],Se[1],Se[2],Se[3]]),en=r=>(hr.setInt32(0,r,!1),[Se[0],Se[1],Se[2],Se[3]]),_r=r=>(hr.setUint32(0,Math.floor(r/2**32),!1),hr.setUint32(4,r,!1),[Se[0],Se[1],Se[2],Se[3],Se[4],Se[5],Se[6],Se[7]]),cB=r=>(hr.setInt32(0,Math.floor(r/2**32),!1),hr.setUint32(4,r,!1),[Se[0],Se[1],Se[2],Se[3],Se[4],Se[5],Se[6],Se[7]]),GA=r=>(hr.setInt16(0,2**8*r,!1),[Se[0],Se[1]]),br=r=>(hr.setInt32(0,2**16*r,!1),[Se[0],Se[1],Se[2],Se[3]]),Du=r=>(hr.setInt32(0,2**30*r,!1),[Se[0],Se[1],Se[2],Se[3]]),Mu=(r,e)=>{const t=[];let n=r;do{let i=n&127;n>>=7,t.length>0&&(i|=128),t.push(i)}while(n>0||e);return t.reverse()},Ge=(r,e=!1)=>{const t=Array(r.length).fill(null).map((n,i)=>r.charCodeAt(i));return e&&t.push(0),t},YA=r=>{const e=r*(Math.PI/180),t=Math.round(Math.cos(e)),n=Math.round(Math.sin(e));return[t,n,0,-n,t,0,0,0,1]},KA=YA(0),qA=r=>[br(r[0]),br(r[1]),Du(r[2]),br(r[3]),br(r[4]),Du(r[5]),br(r[6]),br(r[7]),Du(r[8])],le=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Ue=(r,e,t,n,i)=>le(r,[ft(e),HA(t),n??[]],i),lB=r=>r.isQuickTime?le("ftyp",[Ge("qt  "),Y(512),Ge("qt  ")]):r.fragmented?r.cmaf?le("ftyp",[Ge("iso5"),Y(512),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]):le("ftyp",[Ge("iso5"),Y(512),Ge("iso5"),Ge("iso6"),Ge("mp41")]):le("ftyp",[Ge("isom"),Y(512),Ge("isom"),r.holdsAvc?Ge("avc1"):[],Ge("mp41")]),jA=()=>le("styp",[Ge("iso5"),Y(0),Ge("iso5"),Ge("iso6"),Ge("mp41"),Ge("cmfc"),Ge("dash")]),XA=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),Ue("sidx",1,0,[Y(1),Y(kr),_r(it(r.minWrittenTimestamp,kr)),_r(0),de(0),de(1),Y(e&2147483647),Y(it(t,kr)),Y(0)])},Mo=r=>({type:"mdat",largeSize:r}),uB=r=>({type:"free",size:r}),ta=r=>le("moov",void 0,[dB(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>fB(e,r.creationTime)),r.isFragmented?qB(r.trackDatas):null,ox(r)]),dB=(r,e)=>{const t=Math.max(0,...e.map(a=>it(Uo(a),kr)+it(a.startTimestampOffset??0,kr))),n=Math.max(0,...e.map(a=>a.track.id))+1,i=!mn(r)||!mn(t),s=i?_r:Y;return Ue("mvhd",+i,0,[s(r),s(r),Y(kr),s(t),br(1),GA(1),Array(10).fill(0),qA(KA),Array(24).fill(0),Y(n)])},Uo=r=>
331{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let n=0;n<r.samples.length;n++){const i=r.samples[n];i.timestamp<e&&(e=i.timestamp),i.timestamp+i.duration>t&&(t=i.timestamp+i.duration)}return e===1/0?0:t-e},fB=(r,e)=>{const t=Ex(r),n=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return le("trak",void 0,[hB(r,e),n?mB(r,r.startTimestampOffset):null,pB(r,e),t.name!==void 0?le("udta",void 0,[le("name",[...Ve.encode(t.name)])]):null])},hB=(r,e)=>{var o;const t=it(Uo(r),kr)+it(r.startTimestampOffset??0,kr),n=!mn(e)||!mn(t),i=n?_r:Y;let s;if(r.type==="video"){const c=r.track.metadata.rotation;s=YA(c??0)}else s=KA;let a=2;return((o=r.track.metadata.disposition)==null?void 0:o.default)!==!1&&(a|=1),Ue("tkhd",+n,a,[i(e),i(e),Y(r.track.id),Y(0),i(t),Array(8).fill(0),de(0),de(r.track.id),GA(r.type==="audio"?1:0),de(0),qA(s),br(r.type==="video"?r.info.width:0),br(r.type==="video"?r.info.height:0)])},mB=(r,e)=>{const t=it(e,kr),n=it(Uo(r),kr),i=!mn(t)||!mn(n),s=i?_r:Y,a=i?cB:en;return le("edts",void 0,[Ue("elst",i?1:0,0,[Y(2),s(t),a(-1),br(1),s(n),a(0),br(1)])])},pB=(r,e)=>le("mdia",void 0,[gB(r,e),Uu(!0,AB[r.type],wB[r.type]),yB(r)]),gB=(r,e)=>{const t=it(Uo(r),r.timescale),n=!mn(e)||!mn(t),i=n?_r:Y;return Ue("mdhd",+n,0,[i(e),i(e),Y(r.timescale),i(t),de(nw(r.track.metadata.languageCode??Bt)),de(0)])},AB={video:"vide",audio:"soun",subtitle:"text"},wB={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Uu=(r,e,t,n="\0\0\0\0")=>Ue("hdlr",0,0,[r?Ge("mhlr"):Y(0),Ge(e),Ge(n),Y(0),Y(0),Ge(t,!0)]),yB=r=>le("minf",void 0,[bB[r.type](),EB(),SB(r)]),bB={video:()=>Ue("vmhd",0,1,[de(0),de(0),de(0),de(0)]),audio:()=>Ue("smhd",0,0,[de(0),de(0)]),subtitle:()=>Ue("nmhd",0,0)},EB=()=>le("dinf",void 0,[kB()]),kB=()=>Ue("dref",0,0,[Y(1)],[TB()]),TB=()=>Ue("url ",0,1),SB=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return le("stbl",void 0,[CB(r),zB(r),e?YB(r):null,e?KB(r):null,VB(r),HB(r),GB(r),WB(r)])},CB=r=>{let e;if(r.type==="video")e=IB(dx(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=rw(r.track.source._codec,r.muxer.isQuickTime);y(t),e=FB(t,r)}else r.type==="subtitle"&&(e=QB(mx[r.track.source._codec],r));return y(e),Ue("stsd",0,0,[Y(1)],[e])},IB=(r,e)=>le(r,[Array(6).fill(0),de(1),de(0),de(0),Array(12).fill(0),de(e.info.width),de(e.info.height),Y(4718592),Y(4718592),Y(0),de(1),Array(32).fill(0),de(24),Ru(65535)],[fx[e.track.source._codec](e),BB(e),rp(e.info.decoderConfig.colorSpace)?xB(e):null]),BB=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:le("pasp",[Y(r.info.pixelAspectRatio.num),Y(r.info.pixelAspectRatio.den)]),xB=r=>le("colr",[Ge("nclx"),de(Nn[r.info.decoderConfig.colorSpace.primaries]),de(Qn[r.info.decoderConfig.colorSpace.transfer]),de(Ln[r.info.decoderConfig.colorSpace.matrix]),ft((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),PB=r=>r.info.decoderConfig&&le("avcC",[...je(r.info.decoderConfig.description)]),vB=r=>r.info.decoderConfig&&le("hvcC",[...je(r.info.decoderConfig.description)]),JA=r=>{var f,h,p,m;if(!r.info.decoderConfig)return null;const e=r.info.decoderConfig,t=e.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(((f=e.colorSpace)==null?void 0:f.fullRange)??0),c=(s<<4)+(a<<1)+o,l=t[5]?Number(t[5]):(h=e.colorSpace)!=null&&h.primaries?Nn[e.colorSpace.primaries]:2,u=t[6]?Number(t[6]):(p=e.colorSpace)!=null&&p.transfer?Qn[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):(m=e.colorSpace)!=null&&m.matrix?Ln[e.colorSpace.matrix]:2;return Ue("vpcC",1,0,[ft(n),ft(i),ft(c),ft(l),ft(u),ft(d),de(0)])},_B=r=>le("av1C",kp(r.info.decoderConfig.codec)),FB=(r,e)=>{var a;let t=0,n,i=16;const s=yt.includes(e.track.source._codec);if(s){const o=e.track.source._codec,{sampleSize:c}=Ar(o);i=8*c,i>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)n=[Array(6).fill(0),de(1),de(t),de(0),Y(0),de(e.info.numberOfChannels),de(i),de(0),de(0),de(e.info.sampleRate<2**16?e.info.sampleRate:0),de(0)];else{const o=s?0:-2;n=[Array(6).fill(0),de(1),de(t),de(0),Y(0),de(e.info.numberOfChannels),de(Math.min(i,16)),Ru(o),de(0),de(e.info.sampleRate<2**16?e.info.sampleRate:0),de(0),s?[Y(1),Y(i/8),Y(e.info.numberOfChannels*i/8)]:[Y(0),Y(0),Y(0)],Y(2)]}return le(r,n,[((a=hx(e.track.source._codec,e.muxer.isQuickTime))==null?void 0:a(e))??null])},Ou=r=>{let e;switch(r.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let t=[...ft(e),...ft(21),...HA(0),...Y(0),...Y(0)];if(r.info.decoderConfig.description){const n=je(r.info.decoderConfig.description);t=[...t,...ft(5),...Mu(n.byteLength),...n]}return t=[...de(1),...ft(0),...ft(4),...Mu(t.length),...t,...ft(6),...ft(1),...ft(2)],t=[...ft(3),...Mu(t.length),...t],Ue("esds",0,0,t)},Bn=r=>le("wave",void 0,[RB(r),DB(r),le("\0\0\0\0")]),RB=r=>le("frma",[Ge(rw(r.track.source._codec,r.muxer.isQuickTime))]),DB=r=>{const{littleEndian:e}=Ar(r.track.source._codec);return le("enda",[de(+e)])},MB=r=>{var c;let e=r.info.numberOfChannels,t=3840,n=r.info.sampleRate,i=0,s=0,a=new Uint8Array(0);const o=(c=r.info.decoderConfig)==null?void 0:c.description;if(o){y(o.byteLength>=18);const l=je(o),u=so(l);e=u.outputChannelCount,t=u.preSkip,n=u.inputSampleRate,i=u.outputGain,s=u.channelMappingFamily,u.channelMappingTable&&(a=u.channelMappingTable)}return le("dOps",[ft(0),ft(e),de(t),Y(n),Ru(i),ft(s),...a])},UB=r=>{var n;const e=(n=r.info.decoderConfig)==null?void 0:n.description;y(e);const t=je(e);return Ue("dfLa",0,0,[...t.subarray(4)])},Fr=r=>{const{littleEndian:e,sampleSize:t}=Ar(r.track.source._codec),n=+e;return Ue("pcmC",0,0,[ft(n),ft(8*t)])},OB=r=>{const e=Op(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),n=new Ce(t);return n.writeBits(2,e.fscod),n.writeBits(5,e.bsid),n.writeBits(3,e.b
331smod),n.writeBits(3,e.acmod),n.writeBits(1,e.lfeon),n.writeBits(5,e.bitRateCode),n.writeBits(5,0),le("dac3",[...t])},NB=r=>{const e=Qp(r.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;const n=Math.ceil(t/8),i=new Uint8Array(n),s=new Ce(i);s.writeBits(13,e.dataRate),s.writeBits(3,e.substreams.length-1);for(const a of e.substreams)s.writeBits(2,a.fscod),s.writeBits(5,a.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,a.bsmod),s.writeBits(3,a.acmod),s.writeBits(1,a.lfeon),s.writeBits(3,0),s.writeBits(4,a.numDepSub),a.numDepSub>0?s.writeBits(9,a.chanLoc):s.writeBits(1,0);return le("dec3",[...i])},QB=(r,e)=>le(r,[Array(6).fill(0),de(1)],[px[e.track.source._codec](e)]),LB=r=>le("vttC",[...Ve.encode(r.info.config.description)]),zB=r=>Ue("stts",0,0,[Y(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[Y(e.sampleCount),Y(e.sampleDelta)])]),WB=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Ue("stss",0,0,[Y(e.length),e.map(([t])=>Y(t+1))])},VB=r=>Ue("stsc",0,0,[Y(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[Y(e.firstChunk),Y(e.samplesPerChunk),Y(1)])]),HB=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=Ar(r.track.source._codec);return Ue("stsz",0,0,[Y(e*r.info.numberOfChannels),Y(r.samples.reduce((t,n)=>t+it(n.duration,r.timescale),0))])}return Ue("stsz",0,0,[Y(0),Y(r.samples.length),r.samples.map(e=>Y(e.size))])},GB=r=>r.finalizedChunks.length>0&&tt(r.finalizedChunks).offset>=2**32?Ue("co64",0,0,[Y(r.finalizedChunks.length),r.finalizedChunks.map(e=>_r(e.offset))]):Ue("stco",0,0,[Y(r.finalizedChunks.length),r.finalizedChunks.map(e=>Y(e.offset))]),YB=r=>Ue("ctts",1,0,[Y(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[Y(e.sampleCount),en(e.sampleCompositionTimeOffset)])]),KB=r=>{let e=1/0,t=-1/0,n=1/0,i=-1/0;y(r.compositionTimeOffsetTable.length>0),y(r.samples.length>0);for(let a=0;a<r.compositionTimeOffsetTable.length;a++){const o=r.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<r.samples.length;a++){const o=r.samples[a];n=Math.min(n,it(o.timestamp,r.timescale)),i=Math.max(i,it(o.timestamp+o.duration,r.timescale))}const s=Math.max(-e,0);return i>=2**31?null:Ue("cslg",0,0,[en(s),en(e),en(t),en(n),en(i)])},qB=r=>le("mvex",void 0,r.map(jB)),jB=r=>Ue("trex",0,0,[Y(r.track.id),Y(1),Y(0),Y(0),Y(0)]),$A=(r,e)=>le("moof",void 0,[XB(r),...e.map(JB)]),XB=r=>Ue("mfhd",0,0,[Y(r)]),ZA=r=>{let e=0,t=0;const n=0,i=0,s=r.type==="delta";return t|=+s,s?e|=1:e|=2,e<<24|t<<16|n<<8|i},JB=r=>le("traf",void 0,[$B(r),ZB(r),ex(r)]),$B=r=>{y(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=r.currentChunk.samples[1]??r.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:ZA(t)};return Ue("tfhd",0,e,[Y(r.track.id),Y(n.duration),Y(n.size),Y(n.flags)])},ZB=r=>(y(r.currentChunk),Ue("tfdt",1,0,[_r(it(r.currentChunk.startTimestamp,r.timescale))])),ex=r=>{y(r.currentChunk);const e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),n=r.currentChunk.samples.map(ZA),i=r.currentChunk.samples.map(m=>it(m.timestamp-m.decodeTimestamp,r.timescale)),s=new Set(e),a=new Set(t),o=new Set(n),c=new Set(i),l=o.size===2&&n[0]!==n[1],u=s.size>1,d=a.size>1,f=!l&&o.size>1,h=c.size>1||[...c].some(m=>m!==0);let p=0;return p|=1,p|=4*+l,p|=256*+u,p|=512*+d,p|=1024*+f,p|=2048*+h,Ue("trun",1,p,[Y(r.currentChunk.samples.length),Y(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?Y(n[0]):[],r.currentChunk.samples.map((m,A)=>[u?Y(e[A]):[],d?Y(t[A]):[],f?Y(n[A]):[],h?en(i[A]):[]])])},tx=r=>le("mfra",void 0,[...r.map(rx),nx()]),rx=(r,e)=>Ue("tfra",1,0,[Y(r.track.id),Y(63),Y(r.finalizedChunks.length),r.finalizedChunks.map(n=>
331[_r(it(n.samples[0].timestamp,r.timescale)),_r(n.moofOffset),Y(e+1),Y(1),Y(1)])]),nx=()=>Ue("mfro",0,0,[Y(0)]),ix=()=>le("vtte"),sx=(r,e,t,n,i)=>le("vttc",void 0,[i!==null?le("vsid",[en(i)]):null,t!==null?le("iden",[...Ve.encode(t)]):null,e!==null?le("ctim",[...Ve.encode(VA(e))]):null,n!==null?le("sttg",[...Ve.encode(n)]):null,le("payl",[...Ve.encode(r)])]),ax=r=>le("vtta",[...Ve.encode(r)]),ox=r=>{const e=[],t=r.format._options.metadataFormat??"auto",n=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const i=lx(n);i&&e.push(i)}else if(t==="mdta"){const i=ux(n);i&&e.push(i)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&cx(e,r.output._metadataTags);return e.length===0?null:le("udta",void 0,e)},cx=(r,e)=>{for(const{key:t,value:n}of Bi(e))switch(t){case"title":r.push(Rr("©nam",n));break;case"description":r.push(Rr("©des",n));break;case"artist":r.push(Rr("©ART",n));break;case"album":r.push(Rr("©alb",n));break;case"albumArtist":r.push(Rr("albr",n));break;case"genre":r.push(Rr("©gen",n));break;case"date":r.push(Rr("©day",n.toISOString().slice(0,10)));break;case"comment":r.push(Rr("©cmt",n));break;case"lyrics":r.push(Rr("©lyr",n));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Ut(t)}if(e.raw)for(const t in e.raw){const n=e.raw[t];n==null||t.length!==4||r.some(i=>i.type===t)||(typeof n=="string"?r.push(Rr(t,n)):n instanceof Uint8Array&&r.push(le(t,Array.from(n))))}},Rr=(r,e)=>{const t=Ve.encode(e);return le(r,[de(t.length),de(nw("und")),Array.from(t)])},ew={"image/jpeg":13,"image/png":14,"image/bmp":27},tw=(r,e)=>{const t=[];for(const{key:n,value:i}of Bi(r))switch(n){case"title":t.push({key:e?"title":"©nam",value:Er(i)});break;case"description":t.push({key:e?"description":"©des",value:Er(i)});break;case"artist":t.push({key:e?"artist":"©ART",value:Er(i)});break;case"album":t.push({key:e?"album":"©alb",value:Er(i)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Er(i)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Er(i)});break;case"genre":t.push({key:e?"genre":"©gen",value:Er(i)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Er(i)});break;case"date":t.push({key:e?"date":"©day",value:Er(i.toISOString().slice(0,10))});break;case"images":for(const s of i)s.kind==="coverFront"&&t.push({key:"covr",value:le("data",[Y(ew[s.mimeType]??0),Y(0),Array.from(s.data)])});break;case"trackNumber":if(e){const s=r.tracksTotal!==void 0?`${i}/${r.tracksTotal}`:i.toString();t.push({key:"track",value:Er(s)})}else t.push({key:"trkn",value:le("data",[Y(0),Y(0),de(0),de(i),de(r.tracksTotal??0),de(0)])});break;case"discNumber":e||t.push({key:"disc",value:le("data",[Y(0),Y(0),de(0),de(i),de(r.discsTotal??0),de(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ut(n)}if(r.raw)for(const n in r.raw){const i=r.raw[n];i==null||!e&&n.length!==4||t.some(s=>s.key===n)||(typeof i=="string"?t.push({key:n,value:Er(i)}):i instanceof Uint8Array?t.push({key:n,value:le("data",[Y(0),Y(0),Array.from(i)])}):i instanceof Wn&&t.push({key:n,value:le("data",[Y(ew[i.mimeType]??0),Y(0),Array.from(i.data)])}))}return t},lx=r=>{const e=tw(r,!1);return e.length===0?null:Ue("meta",0,0,void 0,[Uu(!1,"mdir","","appl"),le("ilst",void 0,e.map(t=>le(t.key,void 0,[t.value])))])},ux=r=>{const e=tw(r,!0);return e.length===0?null:le("meta",void 0,[Uu(!1,"mdta",""),Ue("keys",0,0,[Y(e.length)],e.map(t=>le("mdta",[...Ve.encode(t.key)]))),le("ilst",void 0,e.map((t,n)=>{const i=String.fromCharCode(...Y(n+1));return le(i,void 0,[t.value])}))])},Er=r=>le("data",[Y(1),Y(0),...Ve.encode(r)]),dx=(r,e)=>{switch(r){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},fx={avc:PB,hevc:vB,vp8:JA,vp9:JA,av1:_B},rw=(r,e)=>{switch(r){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(r){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(r){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},hx=(r,e)=>{switch(r){case"aac":return Ou;case"mp3":return Ou;case"opus":return MB;case"vorbis":return Ou;case"flac":return UB;case"ac3":return OB;case"eac3":return NB}if(e)switch(r){case"pcm-s24":return Bn;case"pcm-s24be":return Bn;case"pcm-s32":return Bn;case"pcm-s32be":return Bn;case"pcm-f32":return Bn;case"pcm-f32be":return Bn;case"pcm-f64":return Bn;case"pcm-f64be":return Bn}else switch(r){case"pcm-s16":return Fr;case"pcm-s16be":return Fr;case"pcm-s24":return Fr;case"pcm-s24be":return Fr;case"pcm-s32":return Fr;case"pcm-s32be":return Fr;case"pcm-f32":return Fr;case"pcm-f32be":return Fr;case"pcm-f64":return Fr;case"pcm-f64be":return Fr}return null},mx={webvtt:"wvtt"},px={webvtt:LB},nw=r=>{y(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};/*!
332 * Copyright (c) 2026-present, Vanilagy and contributors
333 *
334 * This Source Code Form is subject to the terms of the Mozilla Public
335 * License, v. 2.0. If a copy of the MPL was not distributed with this
336 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
337 */class ra{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){y(!this.started),this.target._start(),this.started=!0}write(e){y(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return y(this.started&&!this.finalized),this.target._flush()}async finalize(){y(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const n=t+e.byteLength-this.trackedStart;let i=this.trackedWrites.byteLength;for(;i<n;)i*=2;if(i!==this.trackedWrites.byteLength){const s=new Uint8Array(i);
337s.set(this.trackedWrites,0),this.trackedWrites=s}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}/*!
338 * Copyright (c) 2026-present, Vanilagy and contributors
339 *
340 * This Source Code Form is subject to the terms of the Mozilla Public
341 * License, v. 2.0. If a copy of the MPL was not distributed with this
342 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
343 */const iw=typeof mo<"u"?mo:void 0;class Kt extends _s{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){var n;(n=this.onwrite)==null||n.call(this,e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new sw(this,e)}}const Nu=2**16,Qu=2**32;class Oo extends Kt{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Nu,{maxByteLength:Qu})}catch{this._buffer=new ArrayBuffer(Nu),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Nu);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Qu)throw new Error(`ArrayBuffer exceeded maximum size of ${Qu} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const n=new ArrayBuffer(t),i=new Uint8Array(n);i.set(this._bytes,0),this._buffer=n,this._bytes=i}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}const gx=2**24,Ax=2;class Lu extends Kt{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??gx}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){const n=t-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(y(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((n,i)=>n.start-i.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){const i=e[e.length-1],s=t[n];s.start<=i.start+i.size?i.size=Math.max(i.size,s.start+s.data.byteLength-i.start):e.push({start:s.start,size:s.data.byteLength})}for(const n of e){n.data=new Uint8Array(n.size);for(const i of this._sections)n.start<=i.start&&i.start<n.start+n.size&&n.data.set(i.data,i.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(i=>{this._writeError??(this._writeError=i)}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);n===-1&&(n=this._createChunk(t));const i=this._chunks[n],s=t-i.start,a=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));i.data.set(a,s);const o={start:s,end:s+a.byteLength};if(this._insertSectionIntoChunk(i,o),i.written[0].start===0&&i.written[0].end===this._chunkSize&&(i.shouldFlush=!0),this._chunks.length>Ax){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,i=e.written.length-1,s=-1;for(;n<=i;){const a=Math.floor(n+(i-n+1)/2);e.written[a].start<=t.start?(n=a+1,s=a):i=a-1}for(e.written.splice(s+1,0,t),(s===-1||e.written[s].end<t.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){const n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((i,s)=>i.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){y(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const n=this._chunks[t];if(!(!n.shouldFlush&&!e)){for(const i of n.written){const s=n.start+i.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data.subarray(i.start,i.end),position:s}).catch(a=>{this._writeError??(this._writeError=a)}),this._lastFlushEnd=n.start+i.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;y(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){var e;return(e=this._streamWriter)==null?void 0:e.close()}}class wx extends Kt{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new Lu(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>
343{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return y(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,y(this._writer),this._writer.write(t.data)},close:()=>{var t;return(t=this._writer)==null?void 0:t.close()}}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class yx extends Kt{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!iw.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;const n=new WritableStream({start:async()=>{this._fileHandle=await iw.fs.open(e,"w")},write:async i=>{y(this._fileHandle),await this._fileHandle.write(i.data,0,i.data.byteLength,i.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new Lu(n,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class zu extends Kt{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class sw extends Kt{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class tn{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}/*!
344 * Copyright (c) 2026-present, Vanilagy and contributors
345 *
346 * This Source Code Form is subject to the terms of the Mozilla Public
347 * License, v. 2.0. If a copy of the MPL was not distributed with this
348 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
349 */const kr=57600,bx=2082844800,Ex=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},it=(r,e,t=!0)=>{const n=r*e;return t?Math.round(n):n};class kx extends Zr{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Oo,this.auxWriter=new ra(this.auxTarget,!1),this.auxBoxWriter=new Do(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=rt(),this.creationTime=Math.floor(Date.now()/1e3)+bx,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof ed,this.isCmaf=t instanceof Zu,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Zu?1/0:1)}async start(){var n;const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":i instanceof Oo),this.boxWriter=new Do(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Oo?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const i=await this.output._getInitTarget(),s=new ra(i,!0);
349s.start(),this.initWriter=s,this.initBoxWriter=new Do(s)}const t=this.output._tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(y(i),this.format._options.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(lB({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:s,start:a}=i.writer.stopTrackingWrites();this.format._options.onFtyp(s,a)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(y(this.writer),y(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Mo(!0),this.boxWriter.writeBox(this.mdat));await((n=this.writer)==null?void 0:n.flush()),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Wp({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,n){const i=this.trackDatas.find(f=>f.track===e);if(i)return i;Ja(n),y(n),y(n.decoderConfig);const s={...n.decoderConfig};y(s.codedWidth!==void 0),y(s.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!s.description){const f=Pl(t.data);if(!f)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=tC(f),a=!0}else if(e.source._codec==="hevc"&&!s.description){const f=_l(t.data);if(!f)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=lC(f),a=!0}const o=PS(1/(e.metadata.frameRate??kr),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}
349:Ps({num:c*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((f,h)=>f.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,n){const i=this.trackDatas.find(c=>c.track===e);if(i)return i;yn(n),y(n),y(n.decoderConfig);const s={...n.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!s.description){const c=jr(Nt.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const l=gn[c.samplingFrequencyIndex],u=_i[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=yl({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&yt.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const n=this.trackDatas.find(s=>s.track===e);if(n)return n;Cp(t),y(t),y(t.config);const i={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,t,n);let a=t.data;if(s.info.requiresAnnexBTransformation){const c=[...Ri(a)].map(l=>a.subarray(l.offset,l.offset+l.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=xl(c,4)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(s,a,t.timestamp,t.duration,t.type);await this.registerSample(s,o)}finally{i()}}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,t,n);let a=t.data;if(s.info.requiresAdtsStripping){const u=jr(Nt.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const d=u.crcCheck===null?Ls:Sn;a=a.subarray(d)}this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){const d=Ar(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(c=a.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const f=o-s.info.expectedNextPcmPacketTimestamp;if(f<.01)o=s.info.expectedNextPcmPacketTimestamp;else{const h=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);o=s.info.expectedNextPcmPacketTimestamp+h}}s.info.expectedNextPcmPacketTimestamp=o+c}const l=this.createSampleForTrack(s,a,o,c,t.type);await this.registerSample(s,l)}finally{i()}}async padWithSilence(e,t,n){const i=it(n,e.timescale);if(n=i/e.timescale,i>0){const{sampleSize:s,silentValue:a}=Ar(e.info.decoderConfig.codec),o=i*e.info.numberOfChannels,c=new Uint8Array(s*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,t,n){const i=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(t),await this.processWebVTTCues(s,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const n=new Set([]);
349for(const l of e.cueQueue)y(l.timestamp<=t),y(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);const i=[...n].sort((l,u)=>l-u),s=i[0],a=i[1]??s;if(t<a)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const l=ix();this.auxBoxWriter.writeBox(l);const u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){const u=e.cueQueue[l];if(u.timestamp>=a)break;Ro.lastIndex=0;const d=Ro.test(u.text),f=u.timestamp+u.duration;let h=e.cueToSourceId.get(u);if(h===void 0&&a<f&&(h=e.nextSourceId++,e.cueToSourceId.set(u,h)),u.notes){const m=ax(u.notes);this.auxBoxWriter.writeBox(m)}const p=sx(u.text,d?s:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(p),f===a&&e.cueQueue.splice(l--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,a-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,i,s){return{timestamp:n,decodeTimestamp:n,duration:i,data:t,size:t.byteLength,type:s,timescaleUnitsToNextSample:it(i,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=e.timestampProcessingQueue[0].timestamp));let i=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){const a=e.timestampProcessingQueue[s],o=it(a.duration,e.timescale);i+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:i,sampleDelta:1});else{const s=tt(e.timeToSampleTable);s.sampleCount+=i}e.timestampProcessingQueue.length=0;return}const n=e.timestampProcessingQueue.map(i=>i.timestamp).sort((i,s)=>i-s);this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=n[0]));for(let i=0;i<e.timestampProcessingQueue.length;i++){const s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i];const a=it(s.timestamp-s.decodeTimestamp,e.timescale),o=it(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){y(e.lastSample);const c=it(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(y(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=tt(e.timeToSampleTable);
349if(y(u),u.sampleCount===1){u.sampleDelta=l;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==l&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:l}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=tt(e.compositionTimeOffsetTable);y(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=it(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,y(e.lastSample),y(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){y(t.type==="key");const i=it(t.timestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const i=e.track.metadata.maximumPacketCount;if(y(i!==void 0),e.samples.length>i)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${i}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.closed});i>=this.minimumFragmentDuration&&s&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=i>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),y(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(y(!this.isFragmented),y(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((n,i)=>n+it(i.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||tt(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const n of e.currentChunk.samples)y(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(y(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,n=1/0;for(const s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(t=s,n=s.sampleQueue[0].timestamp)}if(!t)break;const i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!this.isCmaf){y(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){const h=this.initBoxWriter??this.boxWriter;y(h),this.format._options.onMoov&&h.writer.startTrackingWrites();const p=ta(this);if(h.writeBox(p),this.format._options.onMoov){const{data:m,start:A}=h.writer.stopTrackingWrites();this.format._options.onMoov(m,A)}if(this.isCmaf){y(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Do(this.writer);const m=this.boxWriter.measureBox(jA()),A=this.boxWriter.measureBox(XA(this,0));this.segmentHeaderSize=m+A,this.writer.seek(this.segmentHeaderSize)}}y(this.writer),y(this.boxWriter);const n=this.trackDatas.filter(h=>h.currentChunk),i=$A(t,n),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(i);let o=a+Hr,c=1/0;for(const h of n){h.currentChunk.offset=o,h.currentChunk.moofOff
349set=s;for(const p of h.currentChunk.samples)o+=p.size;c=Math.min(c,h.currentChunk.startTimestamp)}const l=o-a,u=l>=2**32;if(u)for(const h of n)h.currentChunk.offset+=Gn-Hr;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=$A(t,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:h,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,p,c)}y(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const f=Mo(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?Gn:Hr));for(const h of n)for(const p of h.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){const{data:h,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,p)}for(const h of n)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(y(this.writer),y(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){const n=ta(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;y(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Mo(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){y(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const n=t.track.metadata.maximumPacketCount;y(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){const t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const t of this.trackDatas){await this.finalizeCurrentChunk(t),y(t.startTimestampOffset!==null);for(let n=0;n<t.samples.length;n++){const i=t.samples[n];i.timestamp-=t.startTimestampOffset,i.decodeTimestamp-=t.startTimestampOffset}}if(y(this.writer),y(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Mo(!1);let t;for(let i=0;i<2;i++){const s=ta(this),a=this.boxWriter.measureBox(s);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:l}of c.samples)y(l),o+=l.byteLength,t+=l.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const n=ta(this);if(this.boxWriter.writeBox(n),this.format._options.onMoov){const{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(i,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const s of i.samples)y(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){const{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(i,s)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(jA()),this.boxWriter.writeBox(XA(this,t))}else{const t=this.writer.getPos(),n=tx(this.trackDatas);this.boxWriter.writeBox(n);const i=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{y(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);y(t!==void 0);const n=this.writer.getPos()-t;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,a)}const i=ta(this);if(this.fastStart==="reserve"){y(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(uB(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,a)}}e()}}/*!
350 * Copyright (c) 2026-present, Vanilagy and contributors
351 *
352 * This Source Code Form is subject to the terms of the Mozilla Public
353 * License, v. 2.0. If a copy of the MPL was not distributed with this
354 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
355 */const Tx=-32768,Sx=2**15-1,aw="Mediabunny",ow=6,cw=5,Cx={video:1,audio:2,subtitle:17};class Ix extends Zr{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=rt(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMa
355xMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new xC(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:_.EBML,data:[{id:_.EBMLVersion,data:1},{id:_.EBMLReadVersion,data:1},{id:_.EBMLMaxIDLength,data:4},{id:_.EBMLMaxSizeLength,data:8},{id:_.DocType,data:this.format instanceof rd?"webm":"matroska"},{id:_.DocTypeVersion,data:2},{id:_.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:_.SeekHead,data:[{id:_.Seek,data:[{id:_.SeekID,data:t},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:_.Seek,data:[{id:_.SeekID,data:n},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:_.Seek,data:[{id:_.SeekID,data:i},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:_.Seek,data:[{id:_.SeekID,data:s},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:_.Seek,data:[{id:_.SeekID,data:a},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:_.Duration,data:new zl(0)};this.segmentDuration=e;const t={id:_.Info,data:[{id:_.TimestampScale,data:1e6},{id:_.MuxingApp,data:aw},{id:_.WritingApp,data:aw},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){var t,n,i,s,a,o;const e={id:_.Tracks,data:[]};this.tracksElement=e;for(const c of this.trackDatas){const l=Zt[c.track.source._codec];y(l);let u=0;if(c.type==="audio"&&c.track.source._codec==="opus"){u=1e6*80;const d=c.info.decoderConfig.description;if(d){const f=je(d),h=so(f);u=Math.round(1e9*(h.preSkip/Fi))}}e.data.push({id:_.TrackEntry,data:[{id:_.TrackNumber,data:c.track.id},{id:_.TrackUID,data:c.track.id},{id:_.TrackType,data:Cx[c.type]},((t=c.track.metadata.disposition)==null?void 0:t.default)===!1?{id:_.FlagDefault,data:0}:null,(n=c.track.metadata.disposition)!=null&&n.forced?{id:_.FlagForced,data:1}:null,(i=c.track.metadata.disposition)!=null&&i.hearingImpaired?{id:_.FlagHearingImpaired,data:1}:null,(s=c.track.metadata.disposition)!=null&&s.visuallyImpaired?{id:_.FlagVisualImpaired,data:1}:null,(a=c.track.metadata.disposition)!=null&&a.original?{id:_.FlagOriginal,data:1}:null,(o=c.track.metadata.disposition)!=null&&o.commentary?{id:_.FlagCommentary,data:1}:null,{id:_.FlagLacing,data:0},{id:_.Language,data:c.track.metadata.languageCode??Bt},{id:_.CodecID,data:l},{id:_.CodecDelay,data:0},{id:_.SeekPreRoll,data:u},c.track.metadata.name!==void 0?{id:_.Name,data:new kn(c.track.metadata.name)}:null,c.type==="video"?this.videoSpecificTrackInfo(c):null,c.type==="audio"?this.audioSpecificTrackInfo(c):null,c.type==="subtitle"?this.subtitleSpecificTrackInfo(c):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:n}=e.track.metadata,i=[e.info.decoderConfig.description?{id:_.CodecPrivate,data:je(e.info.decoderConfig.description)}:null,t?{id:_.DefaultDuration,data:1e9/t}:null],s=n?Ti(-n):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace,c={id:_.Video,data:[{id:_.PixelWidth,data:e.info.width},{id:_.PixelHeight,data:e.info.height},a?{id:_.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:_.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:_.DisplayUnit,data:3}:null,e.info.alphaMode?{id:_.AlphaMode,data:1}:null,rp(o)?{id:_.Colour,data:[{id:_.MatrixCoefficients,data:Ln[o.matrix]},{id:_.TransferCharacteristics,data:Qn[o.transfer]},{id:_.Primaries,data:Nn[o.primaries]},{id:_.Range,data:o.fullRange?2:1}]}:null,s?{id:_.Projection,data:[{id:_.ProjectionType,data:0},{id:_.ProjectionPoseRoll,data:new Ll((s+180)%360-180)}]}:null]};return i.push(c),i}audioSpecificTrackInfo(e){const t=yt.includes(e.track.source._codec)?Ar(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:_.CodecPrivate,data:je(e.info.decoderConfig.description)}:null,{id:_.Audio,data:[{id:_.SamplingFrequency,data:new Ll(e.info.sampleRate)},{id:_.Channels,data:e.info.numberOfChannels},t?{id:_.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:_.CodecPrivate,data:Ve.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(s,a)=>{e.push({id:_.SimpleTag,data:[{id:_.TagName,data:new kn(s)}
355,typeof a=="string"?{id:_.TagString,data:new kn(a)}:{id:_.TagBinary,data:a}]})},n=this.output._metadataTags,i=new Set;for(const{key:s,value:a}of Bi(n))switch(s){case"title":t("TITLE",a),i.add("TITLE");break;case"description":t("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":t("ARTIST",a),i.add("ARTIST");break;case"album":t("ALBUM",a),i.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),i.add("GENRE");break;case"comment":t("COMMENT",a),i.add("COMMENT");break;case"lyrics":t("LYRICS",a),i.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":{const o=n.tracksTotal!==void 0?`${a}/${n.tracksTotal}`:a.toString();t("PART_NUMBER",o),i.add("PART_NUMBER")}break;case"discNumber":{const o=n.discsTotal!==void 0?`${a}/${n.discsTotal}`:a.toString();t("DISC",o),i.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:Ut(s)}if(n.raw)for(const s in n.raw){const a=n.raw[s];a==null||i.has(s)||(typeof a=="string"||a instanceof Uint8Array)&&t(s,a)}e.length!==0&&(this.tagsElement={id:_.Tags,data:[{id:_.Tag,data:[{id:_.Targets,data:[{id:_.TargetTypeValue,data:50},{id:_.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],n=new Set,i=e.images??[];for(const s of i){let a=s.name;a===void 0&&(a=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(_S(s.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!n.has(o))break}n.add(o),t.push({id:_.AttachedFile,data:[s.description!==void 0?{id:_.FileDescription,data:new kn(s.description)}:null,{id:_.FileName,data:new kn(a)},{id:_.FileMediaType,data:s.mimeType},{id:_.FileData,data:s.data},{id:_.FileUID,data:o}]})}for(const[s,a]of Object.entries(e.raw??{}))!(a instanceof ja)||!/^\d+$/.test(s)||i.find(c=>
355c.mimeType===a.mimeType&&lp(c.data,a.data))||t.push({id:_.AttachedFile,data:[a.description!==void 0?{id:_.FileDescription,data:new kn(a.description)}:null,{id:_.FileName,data:new kn(a.name??"")},{id:_.FileMediaType,data:a.mimeType??""},{id:_.FileData,data:a.data},{id:_.FileUID,data:BigInt(s)}]});t.length!==0&&(this.attachmentsElement={id:_.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:_.Segment,size:this.format._options.appendOnly?-1:ow,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,n)}}createCues(){this.cues={id:_.Cues,data:[]}}get segmentDataOffset(){return y(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return lg({isWebM:this.format instanceof rd,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,n){const i=this.trackDatas.find(l=>l.track===e);if(i)return i;Ja(n),y(n),y(n.decoderConfig),y(n.decoderConfig.codedWidth!==void 0),y(n.decoderConfig.codedHeight!==void 0);const s=n.decoderConfig.displayAspectWidth,a=n.decoderConfig.displayAspectHeight,o=s===void 0||a===void 0?null:Ps({num:s,den:a}),c={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:n.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec==="vp9"?c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(LS(c.info.decoderConfig.codec))}:e.source._codec==="av1"&&(c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(kp(c.info.decoderConfig.codec))}),this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,n){const i=this.trackDatas.find(c=>c.track===e);if(i)return i;yn(n),y(n),y(n.decoderConfig);const s={...n.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!s.description){const c=jr(Nt.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const l=gn[c.samplingFrequencyIndex],u=_i[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=yl({objectType:c.objectType,sampleRate:l,numberOfChannels:u}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const n=this.trackDatas.find(s=>s.track===e);if(n)return n;Cp(t),y(t),y(t.config);const i={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(i),this.trackDatas.sort((s,a)=>s.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,t,n),a=t.type==="key";this.validateTimestamp(s.track,t.timestamp,a);let o=t.timestamp,c=t.duration;e.metadata.frameRate!==void 0&&(o=Ci(o,e.metadata.frameRate),c=Ci(c,e.metadata.frameRate));const l=s.info.alphaMode?t.sideData.alpha??null:null,u=this.createInternalChunk(t.data,o,c,t.type,l);
355e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,u),s.chunkQueue.push(u),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,t,n);let a=t.data;if(s.info.requiresAdtsStripping){const l=jr(Nt.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const u=l.crcCheck===null?Ls:Sn;a=a.subarray(u)}const o=t.type==="key";this.validateTimestamp(s.track,t.timestamp,o);const c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);s.chunkQueue.push(c),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,t,n){const i=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,!0);let a=t.text;const o=Math.round(t.timestamp*1e3);Ro.lastIndex=0,a=a.replace(Ro,d=>{const h=Fu(d.slice(1,-1))-o;return`<${VA(h)}>`});const c=Ve.encode(a),l=`${t.settings??""}
356${t.identifier??""}
357${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?Ve.encode(l):null);s.chunkQueue.push(u),await this.interleaveChunks()}finally{i()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,n=1/0;for(const s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<n&&(t=s,n=s.chunkQueue[0].timestamp)}if(!t)break;const i=t.chunkQueue.shift();this.writeBlock(t,i)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const n=new Ce(t.data);n.skipBits(2);const i=n.readBits(1),a=(n.readBits(1)<<1)+i;if(a===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;a>=2&&n.skipBits(1);const u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];AS(t.data,n.pos,n.pos+3,u)}createInternalChunk(e,t,n,i,s=null){return{data:e,type:i,timestamp:t,duration:n,additions:s}}writeBlock(e,t){this.segment||this.createSegment();const n=Math.round(1e3*t.timestamp),i=this.trackDatas.every(u=>{if(e===u)return t.type==="key";const d=u.chunkQueue[0];return d?d.type==="key":u.closed});let s=!1;if(!this.currentCluster)s=!0;else{y(this.currentClusterStartMsTimestamp!==null),y(this.currentClusterMaxMsTimestamp!==null);const u=n-this.currentClusterStartMsTimestamp;s=i&&n>this.currentClusterMaxMsTimestamp&&u>=1e3*(this.format._options.minimumClusterDuration??1)||u>Sx}s&&this.createNewCluster(n);const a=n-this.currentClusterStartMsTimestamp;if(a<Tx)return;const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,a,!1);const l=Math.round(1e3*t.duration);if(t.additions){const u={id:_.BlockGroup,data:[{id:_.Block,data:[o,t.data]},t.type==="delta"?{id:_.ReferenceBlock,data:new rg(e.lastWrittenMsTimestamp-n)}:null,t.additions?{id:_.BlockAdditions,data:[{id:_.BlockMore,data:[{id:_.BlockAddID,data:1},{id:_.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:_.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(u)}else{c.setUint8(3,+(t.type==="key")<<7);const u={id:_.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(u)}this.startTimestamp=Math.min(this.startTimestamp,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:_.Cluster,size:this.format._options.appendOnly?-1:cw,data:[{id:_.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(y(this.currentCluster),!this.format._options.appendOnly){const i=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(i,cw),this.writer.seek(s)}if(this.format._options.onCluster){y(this.currentClusterStartMsTimestamp!==null);const{data:i,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(i,s,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[i,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)t.has(s)||t.set(s,[]),t.get(s).push(i);const n=[...t.entries()].sort((i,s)=>i[0]-s[0]);for(const[i,s]of n)y(this.cues),this.cues.data.push({id:_.CuePoint,data:[{id:_.CueTime,data:i},...s.map(a=>({id:_.CueTrackPositions,data:[{id:_.CueTrack,data:a.track.id},{id:_.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){const t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),y(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,ow);const n=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new zl(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),y(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}/*!
358 * Copyright (c) 2026-present, Vanilagy and contributors
359 *
360 * This Source Code Form is subject to the terms of the Mozilla Public
361 * License, v. 2.0. If a copy of the MPL was not distributed with this
362 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
363 */class Bx{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos(),n=255,i=224|e.mpegVersionId<<3|e.layer<<1;let s;e.mpegVersionId&2?s=e.mpegVersionId&1?0:1:s=1;const a=0,o=155;let c=-1;const l=s*16*4+e.layer*16;for(let A=0;A<16;A++){const g=kl[l+A];if(Sl(s,e.layer,1e3*g,e.sampleRate,a)>=o){c=A;break}}if(c===-1)throw new Error("No suitable bitrate found.");const u=c<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=n,this.helper[1]=i,this.helper[2]=u,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));const f=Za(e.mpegVersionId,e.channel);this.writer.seek(t+f),this.writeU32($a);let h=0;e.frameCount!==null&&(h|=Hn.FrameCount),e.fileSize!==null&&(h|=Hn.FileSize),e.toc!==null&&(h|=Hn.Toc),this.writeU32(h),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const p=kl[l+c],m=Sl(s,e.layer,1e3*p,e.sampleRate,a);this.writer.seek(t+m)}}/*!
364 * Copyright (c) 2026-present, Vanilagy and contributors
365 *
366 * This Source Code Form is subject to the terms of the Mozilla Public
367 * License, v. 2.0. If a copy of the MPL was not distributed with this
368 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
369 */class xx extends Zr{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new Bx(this.writer),Fs(this.output._metadataTags)||new _u(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const n=await this.mutex.acquire();try{const i=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&i){const s=Ae(t.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=s.getUint32(0,!1),o=eo(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");const c=Za(o.mpegVersionId,o.channel);if(s.byteLength>=c+4){const l=s.getUint32(c,!1);if(l===$a||l===Tl)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}
369this.validateTimestamp(e,t.timestamp,t.type==="key"),i&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;const e=await this.mutex.acquire(),n=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);const i=new Uint8Array(100);for(let s=0;s<100;s++){const a=Math.floor(this.framePositions.length*(s/100)),o=this.framePositions[a]-this.xingFramePos;i[s]=256*(o/n)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=n,this.xingFrameData.toc=i,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:s,start:a}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,a)}e()}}/*!
370 * Copyright (c) 2026-present, Vanilagy and contributors
371 *
372 * This Source Code Form is subject to the terms of the Mozilla Public
373 * License, v. 2.0. If a copy of the MPL was not distributed with this
374 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
375 */const Px=8192;class vx extends Zr{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=rt(),this.pageBytes=new Uint8Array(gg),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,pg({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const n=this.trackDatas.find(a=>a.track===e);if(n)return n;let i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===i));y(e.source._codec==="vorbis"||e.source._codec==="opus"),yn(t),y(t),y(t.decoderConfig);const s={track:e,serialNumber:i,internalSampleRate:e.source._codec==="opus"?Fi:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,
375currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,t),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,t){if(y(t.decoderConfig),e.track.source._codec==="vorbis"){y(t.decoderConfig.description);const n=je(t.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let i=1;const s=()=>{let m=0;for(;;){const A=n[i++];if(A===void 0)throw new TypeError("Vorbis decoder description is too short.");if(m+=A,A<255)return m}},a=s(),o=s();if(n.length-i<=0)throw new TypeError("Vorbis decoder description is too short.");const l=n.subarray(i,i+=a);i+=o;const u=n.subarray(i),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;const f=Rl(d,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});const p=Ae(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(p&15),1<<(p>>4)],modeBlockflags:Up(u).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const n=je(t.decoderConfig.description),i=new Uint8Array(8),s=Ae(i);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);const a=Rl(i,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:so(n).preSkip}}}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=s.currentTimestampInSamples,{durationInSamples:o,vorbisBlockSize:c}=mg(t.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=o,s.vorbisLastBlocksize=c,s.packetQueue.push({data:t.data,timestampInSamples:a,durationInSamples:o,forcePageFlush:!1}),await this.interleavePages()}finally{i()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(const t of this.trackDatas)for(;t.packetQueue.length>0;){const n=t.packetQueue.shift();if(this.writePacket(t,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,n=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!a.closed)break e;a.packetQueue.length>0&&a.packetQueue[0].timestampInSamples<n&&(t=a,n=a.packetQueue[0].timestampInSamples)}if(!t)break;const i=t.packetQueue.shift(),s=t.packetQueue.length===0;this.writePacket(t,i,s)}e||await this.writer.flush()}writePacket(e,t,n){const i=t.timestampInSamples+t.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){const l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&i-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,o+=l;const u=s<255;if(e.currentLacingValues.length===255){const d=t.data.subarray(a,o);if(a=o,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,n&&u),u)return}if(u)break;s-=255}const c=t.data.subarray(a);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=i,(e.currentPageSize>=Px||t.forcePageFlush)&&this.writePage(e,n)}writePage(e,t){this.pageView.setUint32(0,ql,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),t&&(n|=4),this.pageView.setUint8(5,n);const i=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;SS(this.pageView,6,i),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,s),s+=c.length;const a=this.pageBytes.subarray(0,s),o=hg(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){const{data:c,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(c,l,e.track.source)}}async onTrackClose(e){const t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;await this.interleavePages(!0);for(const t of this.trackDatas)t.currentLacingValues.length>0&&this.writePage(t,!0);e()}}/*!
376 * Copyright (c) 2026-present, Vanilagy and contributors
377 *
378 * This Source Code Form is subject to the terms of the Mozilla Public
379 * License, v. 2.0. If a copy of the MPL was not distributed with this
380 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
381 */const _x=0,lw=4096,uw=256,Fx=224,dw=192,fw=new Uint8Array([9,240]),hw=new Uint8Array([70,1]);class Rx extends Zr{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(Wt),this.packetView=Ae(this.packetBuffer),this.allTracksKnown=rt(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,kg(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const n=this.trackDatas.find(l=>l.track===e);if(n)return n;Ja(t),y(t==null?void 0:t.decoderConfig);const i=e.source._codec;y(i==="avc"||i==="hevc");const s=i==="avc"?27:36,a=uw+this.trackDatas.length,o=Fx+this.videoTrackIndex++,c={track:e,pid:a,streamType:s,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1}
381;return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const n=this.trackDatas.find(l=>l.track===e);if(n)return n;yn(t),y(t==null?void 0:t.decoderConfig);const i=e.source._codec;y(i==="aac"||i==="mp3"||i==="ac3"||i==="eac3");let s,a;switch(i){case"aac":s=15,a=dw+this.audioTrackIndex++;break;case"mp3":s=3,a=dw+this.audioTrackIndex++;break;case"ac3":s=129,a=189;break;case"eac3":s=135,a=189;break}const o=uw+this.trackDatas.length,c={track:e,pid:o,streamType:s,streamId:a,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}async addEncodedVideoPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=this.prepareVideoPacket(s,t,n);t.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{i()}}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=this.prepareAudioPacket(s,t,n);t.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{i()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,n){var s;const i=e.track.source._codec;if(e.inputIsAnnexB===null){const a=(s=n==null?void 0:n.decoderConfig)==null?void 0:s.description;if(e.inputIsAnnexB=!a,!e.inputIsAnnexB){const o=je(a);i==="avc"?e.avcDecoderConfig=xp(o):e.hevcDecoderConfig=uC(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,i):this.prepareLengthPrefixedVideoPacket(e,t,i)}prepareAnnexBVideoPacket(e,t){const n=[];for(const s of Ri(e)){const a=e.subarray(s.offset,s.offset+s.length);(t==="avc"?Di(a[0])===ur.AUD:bn(a[0])===pt.AUD_NUT)||n.push(a)}const i=t==="avc"?fw:hw;return n.unshift(i),no(n)}prepareLengthPrefixedVideoPacket(e,t,n){const i=t.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(const c of Il(i,s)){const l=i.subarray(c.offset,c.offset+c.length);(n==="avc"?Di(l[0])===ur.AUD:bn(l[0])===pt.AUD_NUT)||a.push(l)}if(t.type==="key")if(n==="avc"){const c=e.avcDecoderConfig;for(const l of c.pictureParameterSets)a.unshift(l);for(const l of c.sequenceParameterSets)a.unshift(l)}else{const c=e.hevcDecoderConfig;for(const l of c.arrays)if(l.nalUnitType===pt.PPS_NUT)for(const u of l.nalUnits)a.unshift(u);for(const l of c.arrays)if(l.nalUnitType===pt.SPS_NUT)for(const u of l.nalUnits)a.unshift(u);for(const l of c.arrays)if(l.nalUnitType===pt.VPS_NUT)for(const u of l.nalUnits)a.unshift(u)}const o=n==="avc"?fw:hw;return a.unshift(o),no(a)}prepareAudioPacket(e,t,n){var c;const i=e.track.source._codec;if(i==="mp3"||i==="ac3"||i==="eac3")return t.data;if(e.inputIsAdts===null){const l=(c=n==null?void 0:n.decoderConfig)==null?void 0:c.description;if(e.inputIsAdts=!l,!e.inputIsAdts){const u=Rs(je(l)),d=pp(u);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return t.data;y(e.adtsHeader),y(e.adtsHeaderBitstream);const s=e.adtsHeader,a=t.data.byteLength+s.byteLength;gp(e.adtsHeaderBitstream,a);const o=new Uint8Array(a);return o.set(s,0),o.set(t.data,s.byteLength),o}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;const n=e.timestampProcessingQueue.map(i=>i.presentationTimestamp).sort((i,s)=>i-s);for(let i=0;i<e.timestampProcessingQueue.length;i++){const s=e.timestampProcessingQueue[i];s.decodeTimestamp=n[i],e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}
381async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,n=1/0;for(const s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!s.closed)break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<n&&(t=s,n=s.packetQueue[0].presentationTimestamp)}if(!t)break;const i=t.packetQueue.shift();this.writePesPacket(t,i)}e||await this.writer.flush()}writeTables(){y(!this.tablesWritten),this.writePsiSection(_x,ri),this.writePsiSection(lw,Mx(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let n=0,i=!0;for(;n<t.length;){const a=184-(i?1:0),o=t.length-n,c=Math.min(a,o);let l;i?(l=this.payloadBuffer.subarray(0,1+c),l[0]=0,l.set(t.subarray(n,n+c),1)):l=t.subarray(n,n+c),this.writeTsPacket(e,i,null,l),n+=c,i=!1}}writePesPacket(e,t){const n=e.track.type==="video",i=n?10:5,s=new Uint8Array(9+i),a=Ae(s),o=new Ce(s.subarray(9));Ga(a,0,1,!1),s[3]=e.streamId;const c=e.track.type==="video"?0:Math.min(8+t.data.length,65535);a.setUint16(4,c,!1),a.setUint8(6,132),a.setUint8(7,n?192:128),a.setUint8(8,i);const l=Math.round(t.presentationTimestamp*wr);if(o.pos=0,o.writeBits(4,n?3:2),o.writeBits(3,l>>>30&7),o.writeBits(1,1),o.writeBits(15,l>>>15&32767),o.writeBits(1,1),o.writeBits(15,l&32767),o.writeBits(1,1),n){y(t.decodeTimestamp!==null);const h=Math.round(t.decodeTimestamp*wr);o.writeBits(4,1),o.writeBits(3,h>>>30&7),o.writeBits(1,1),o.writeBits(15,h>>>15&32767),o.writeBits(1,1),o.writeBits(15,h&32767),o.writeBits(1,1)}const u=s.length+t.data.length;let d=0,f=!0;for(;d<u;){const h=f,p=u-d,m=f&&t.isKeyframe,A=f&&!e.firstPacketWritten,g=Math.max(0,184-p);let w;m||A?w=Math.max(2,g):w=g;let b=null;if(w>0){const C=this.adaptationFieldBuffer;w===1?C[0]=0:(C[0]=w-1,C[1]=Number(A)<<7|Number(m)<<6,C.fill(255,2,w)),b=C.subarray(0,w)}const k=Math.min(184-w,p),S=this.payloadBuffer.subarray(0,k);let x=0;if(d<s.length){const C=Math.min(s.length-d,k);S.set(s.subarray(d,d+C),0),x=C}const B=Math.max(0,d-s.length),I=B+(k-x);x<k&&S.set(t.data.subarray(B,I),x),this.writeTsPacket(e.pid,h,b,S),d+=k,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,n,i){const s=this.continuityCounters.get(e)??0,a=i.length>0,o=n?a?3:2:a?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|s&15,a&&this.continuityCounters.set(e,s+1&15);let c=4;n&&(this.packetBuffer.set(n,c),c+=n.length),this.packetBuffer.set(i,c),c+=i.length,c<Wt&&this.packetBuffer.fill(255,c);const l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){const t=await this.mutex.acquire(),n=this.trackDatas.find(i=>i.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0,await this.flushTimestampQueue(t,!1);await this.interleavePackets(!0),e()}}const Dx=79764919,mw=new Uint32Array(256);for(let r=0;r<256;r++){let e=r<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^Dx:e<<1;mw[r]=e>>>0&4294967295}const pw=r=>{let e=4294967295;for(let t=0;t<r.length;t++){const n=r[t];e=(e<<8^mw[e>>>24^n])>>>0}return e},ri=new Uint8Array(16);{const r=Ae(ri);ri[0]=0,r.setUint16(1,45069,!1),r.setUint16(3,1,!1),ri[5]=193,ri[6]=0,ri[7]=0,r.setUint16(8,1,!1),r.setUint16(10,57344|lw&8191,!1),r.setUint32(12,pw(ri.subarray(0,12)),!1)}const Mx=r=>{let e=0;for(const c of r)e+=5,c.streamType===129?e+=oo.length:c.streamType===135&&(e+=co.length);const t=9+e+4,n=new Uint8Array(3+t-4),i=Ae(n);n[0]=2,i.setUint16(1,45056|t&4095,!1),i.setUint16(3,1,!1),n[5]=193,n[6]=0,n[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let s=12;for(const c of r)n[s++]=c.streamType,i.setUint16(s,57344|c.pid&8191,!1),s+=2,c.streamType===129?(i.setUint16(s,61440|oo.length,!1),s+=2,n.set(oo,s),s+=oo.length):c.streamType===135?(i.setUint16(s,61440|co.length,!1),s+=2,n.set(co,s),s+=co.length):(i.setUint16(s,61440,!1),s+=2);const a=pw(n),o=new Uint8Array(n.length+4);return o.set(n,0),Ae(o).setUint32(n.length,a,!1),o};/*!
382 * Copyright (c) 2026-present, Vanilagy and contributors
383 *
384 * This Source Code Form is subject to the terms of the Mozilla Public
385 * License, v. 2.0. If a copy of the MPL was not distributed with this
386 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
387 */class Ux{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}}/*!
388 * Copyright (c) 2026-present, Vanilagy and contributors
389 *
390 * This Source Code Form is subject to the terms of the Mozilla Public
391 * License, v. 2.0. If a copy of the MPL was not distributed with this
392 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
393 */class Ox extends Zr{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new 
393Ux(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,n){const i=await this.mutex.acquire();try{if(this.headerWritten||(yn(n),y(n),y(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let n;const i=e.source._codec,s=Ar(i);s.dataType==="ulaw"?n=er.MULAW:s.dataType==="alaw"?n=er.ALAW:s.dataType==="float"?n=er.IEEE_FLOAT:n=er.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=s.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*s.sampleSize),!Fs(this.output._metadataTags)){const l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):Ut(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){const{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,u)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const n=new Set,i=(o,c)=>{if(!Qr(c)){console.warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const l=c.length+1,u=new Uint8Array(l);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(l),this.writer.write(u),l&1&&this.writer.write(new Uint8Array(1)),n.add(o)};for(const{key:o,value:c}of Bi(e))switch(o){case"title":i("INAM",c),n.add("INAM");break;case"artist":i("IART",c),n.add("IART");break;case"album":i("IPRD",c),n.add("IPRD");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();i("ITRK",l),n.add("ITRK")}break;case"genre":i("IGNR",c),n.add("IGNR");break;case"date":i("ICRD",c.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":i("ICMT",c),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:Ut(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];c==null||o.length!==4||n.has(o)||typeof c=="string"&&i(o,c)}const s=this.writer.getPos(),a=s-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const i=new _u(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(i),this.writer.seek(s),i&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire(),t=this.writer.getPos();this.isRf64?(y(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),y(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),y(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(y(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),y(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}/*!
394 * Copyright (c) 2026-present, Vanilagy and contributors
395 *
396 * This Source Code Form is subject to the terms of the Mozilla Public
397 * License, v. 2.0. If a copy of the MPL was not distributed with this
398 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
399 */class gw{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(e.startTime*this.targetSampleRate),this.timestampOffset=e.startTime-this.bufferStartFrame/this.targetSampleRate}doChannelMixerSetup(){y(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(n,i)=>n[i*e]:e===1&&t===4?this.channelMixer=(n,i,s)=>n[i*e]*+(s<2):e===1&&t===6?this.channelMixer=(n,i,s)=>n[i*e]*+(s===2):e===2&&t===1?this.channelMixer=(n,i)=>{const s=i*e;return .5*(n[s]+n[s+1])}:e===2&&t===4?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===2&&t===6?this.channelMixer=(n,i,s)=>n[i*e+s]*+(s<2):e===4&&t===1?this.channelMixer=(n,i)=>{const s=i*e;return .25*(n[s]+n[s+1]+n[s+2]+n[s+3])}:e===4&&t===2?this.channelMixer=(n,i,s)=>{const a=i*e;return .5*(n[a+s]+n[a+s+2])}:e===4&&t===6?this.channelMixer=(n,i,s)=>{const a=i*e;return s<2?n[a+s]:s===2||s===3?0:n[a+s-2]}:e===6&&t===1?this.channelMixer=(n,i)=>{const s=i*e;return Math.SQRT1_2*(n[s]+n[s+1])+n[s+2]+.5*(n[s+4]+n[s+5])}:e===6&&t===2?this.channelMixer=(n,i,s)=>{const a=i*e;return n[a+s]+Math.SQRT1_2*(n[a+2]+n[a+s+4])}:e===6&&t===4?this.channelMixer=(n,i,s)=>{const a=i*e;return s<2?n[a+s]+Math.SQRT1_2*n[a+2]:n[a+s+2]}:this.channelMixer=(n,i,s)=>s<e?n[i*e+s]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const n=new Float32Array(t);n.set(this.tempSourceBuffer),this.tempSourceBuffer=n}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const n=e.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(i,{planeIndex:0,format:"f32"});const s=e.timestamp,a=Math.min(e.timestamp+e.duration,this.endTime),o=Math.floor(s*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const u=l-this.bufferStartFrame;y(u<this.bufferSizeInFrames);const h=(l/this.targetSampleRate-s)*this.sourceSampleRate,p=Math.floor(h),m=Math.ceil(h),A=h-p;for(let g=0;g<this.targetNumberOfChannels;g++){let w=0,b=0;p>=0&&p<e.numberOfFrames&&(w=this.channelMixer(i,p,g)),m>=0&&m<e.numberOfFrames&&(b=this.channelMixer(i,m,g));const k=w+A*(b-w),S=u*this.targetNumberOfChannels+g;this.outputBuffer[S]+=k}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const n=this.bufferStartFrame/this.targetSampleRate,i=new kt({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n+this.timestampOffset,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}/*!
400 * Copyright (c) 2026-present, Vanilagy and contributors
401 *
402 * This Source Code Form is subject to the terms of the Mozilla Public
403 * License, v. 2.0. If a copy of the MPL was not distributed with this
404 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
405 */class No{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}
405_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(e),this._closed=!0})())}}class Zi extends No{constructor(e){if(super(),this._connectedTrack=null,!dt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${dt.join(", ")}.`);this._codec=e}}const Wu=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Vu extends Zi{constructor(e){super(e)}add(e,t){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Wu(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Hu{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.co
405dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Is,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){var s,a,o,c,l,u,d,f,h,p,m,A;const i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const g=this.encodingConfig,w=g.sizeChangeBehavior??"deny";let b=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(b=!0,w==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(((s=g.transform)==null?void 0:s.width)!==void 0||((a=g.transform)==null?void 0:a.height)!==void 0||((o=g.transform)==null?void 0:o.rotate)!==void 0||((c=g.transform)==null?void 0:c.crop)!==void 0||((l=g.transform)==null?void 0:l.force)===!0||b&&w!=="passThrough"){let B=(u=g.transform)==null?void 0:u.width,I=(d=g.transform)==null?void 0:d.height,C=((f=g.transform)==null?void 0:f.fit)??"fill";b&&w!=="passThrough"&&(y(this.outputWidth),y(this.outputHeight),y(w!=="deny"),B=this.outputWidth,I=this.outputHeight,C=w);const v=await e.transform({width:B,height:I,roundDimensionsTo:2,crop:(h=g.transform)==null?void 0:h.crop,rotate:(p=g.transform)==null?void 0:p.rotate,fit:C,alpha:g.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=v.displayWidth,this.outputHeight=v.displayHeight),t&&e.close(),e=v,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const x=(m=g.transform)==null?void 0:m.frameRate;if(x!==void 0){const B=e.timestamp+e.duration,I=op(e.timestamp,x);if(this.frameRateLastSample!==null)if(I<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=B;return}else await this.padFrameRate(I,n);e===i&&(e=e.clone(),t=!0),e.setTimestamp(I),e.setDuration(1/x),(A=this.frameRateLastSample)==null||A.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=I,this.frameRateLastEndTimestamp=B}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){var s;const n=this.encodingConfig;let i;if((s=n.transform)!=null&&s.process){let a=n.transform.process(e);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]),i=a.map(o=>o instanceof gt?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new gt(o):new gt(o,{timestamp:e.timestamp,duration:e.duration}))}else i=[e];try{for(const a of i){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized);const o=this.encodingConfig.keyFrameInterval??2,c=Math.floor(a.timestamp/o),l={...t,keyFrame:(t==null?void 0:t.keyFrame)||o===0||c!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=c,this.customEncoder){this.customEncoderQueueSize++;const u=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).then(()=>this.customEncoderQueueSize--).catch(f=>this.error??(this.error=f)).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await d}else{y(this.encoder);const u=a.toVideoFrame(),d=Me(this.preciseTimings,u.timestamp,h=>h.microsecondTimestamp),f=d!==-1?this.preciseTimings[d]:null;if(f&&f.microsecondTimestamp===u.timestamp?(f.timestamp!==a.timestamp&&(f.timestampIsValid=!1),f.duration!==a.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,l),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,l),u.close();else{const p=u.displayWidth,m=u.displayHeight;this.splitter||(this.splitter=new Qo(p,m));const{colorFrame:A,alphaFrame:g}=await this.splitter.update(u);this.alphaFrameQueue.push(g),this.encoder.encode(A,l),A.close()}this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const a of i)a!==e&&a.close()}}async padFrameRate(e,t){const n=this.encodingConfig.transform.frameRate;y(this.frameRateLastSample);const i=Math.round((e-this.frameRateLastTimestamp)*n);for(let s=1;s<i;s++){const a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+s/n),a.setDuration(1/n),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var i,s,a;const t=BA({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:(i=this.source._connectedTrack)==null?void 0:i.metadata.frameRate});(a=(s=this.encodingConfig).onEncoderConfig)==null||a.call(s,t);const n=Io.find(o=>o.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(o,c)=>{var l,u;if(!(o instanceof He))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Wu(this.source._connectedTrack,o),(u=(l=this.encodingConfig).onEncodedPacket)==null||u.call(l,o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(d=>{this.error??(this.error=d)})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const l=[],u=[];let d=0,f=0;const h=(m,A,g)=>{var B,I;const w={};if(A){const C=new Uint8Array(A.byteLength);A.copyTo(C),w.alpha=C}let b=He.fromEncodedChunk(m,w);const k=Me(this.preciseTimings,m.timestamp,C=>C.microsecondTimestamp),S=k!==-1?this.preciseTimings[k]:null;let x=null;this.emittedEncoderPackets===0&&b.type==="delta"&&(g!=null&&g.decoderConfig)&&(x=ao(this.encodingConfig.codec,g.decoderConfig,b.data)),(S&&S.microsecondTimestamp===m.timestamp||x!==null)&&(b=b.clone({t
405imestamp:S!=null&&S.timestampIsValid?S.timestamp:void 0,duration:S!=null&&S.durationIsValid?S.duration:void 0,type:x??void 0})),Wu(this.source._connectedTrack,b),(I=(B=this.encodingConfig).onEncodedPacket)==null||I.call(B,b,g),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,b,g).catch(C=>{this.error??(this.error=C)}),this.emittedEncoderPackets++},p=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(m,A)=>{if(!this.alphaEncoder){h(m,null,A);return}const g=this.alphaFrameQueue.shift();y(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:m.type==="key"}),f++,g.close(),l.push({chunk:m,meta:A})):f===0?h(m,null,A):(u.push(d+f),l.push({chunk:m,meta:A}))},error:m=>{m.stack=p,this.error??(this.error=m)}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){const m=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(A,g)=>{f--;const w=l.shift();for(y(w!==void 0),h(w.chunk,A,w.meta),d++;u.length>0&&u[0]===d;){u.shift();const b=l.shift();y(b!==void 0),h(b.chunk,null,b.meta)}},error:A=>{A.stack=m,this.error??(this.error=A)}}),this.alphaEncoder.configure(t)}}y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){var t,n,i;if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){const s=this.encodingConfig.transform.frameRate,a=op(this.frameRateLastEndTimestamp,s);await this.padFrameRate(a)}(t=this.frameRateLastSample)==null||t.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await((n=this.alphaEncoder)==null?void 0:n.flush())),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(s=>s==null?void 0:s.close()),(i=this.splitter)==null||i.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}let Aw=!1;class Qo{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const n=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!Qo.forceCpu&&n&&!Aw)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(i){this.gl=null,this.canvas=null,Aw=!0,console.warn("Falling back to CPU for color/alpha splitting.",i)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){y(this.gl),y(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);const t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return y(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
406			in vec2 a_position;
407			in vec2 a_texCoord;
408			out vec2 v_texCoord;
409			
410			void main() {
411				gl_Position = vec4(a_position, 0.0, 1.0);
412				v_texCoord = a_texCoord;
413			}
414		`)}createColorProgram(){y(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
415			precision highp float;
416			
417			uniform sampler2D u_sourceTexture;
418			in vec2 v_texCoord;
419			out vec4 fragColor;
420			
421			void main() {
422				vec4 source = texture(u_sourceTexture, v_texCoord);
423				fragColor = vec4(source.rgb, 1.0);
424			}
425		`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createAlphaProgram(){y(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
426			precision highp float;
427			
428			uniform sampler2D u_sourceTexture;
429			uniform vec2 u_resolution; // The width and height of the canvas
430			in vec2 v_texCoord;
431			out vec4 fragColor;
432
433			// This function determines the value for a single byte in the YUV stream
434			float getByteValue(float byteOffset) {
435				float width = u_resolution.x;
436				float height = u_resolution.y;
437
438				float yPlaneSize = width * height;
439
440				if (byteOffset < yPlaneSize) {
441					// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
442					float y = floor(byteOffset / width);
443					float x = mod(byteOffset, width);
444					
445					// Add 0.5 to sample the center of the texel
446					vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
447					
448					// The luma value is the alpha from the source texture
449					return texture(u_sourceTexture, sampleCoord).a;
450				} else {
451					// Write a fixed value for chroma and beyond
452					return 128.0 / 255.0;
453				}
454			}
455			
456			void main() {
457				// Each fragment writes 4 bytes (R, G, B, A)
458				float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
459				float baseByteOffset = pixelIndex * 4.0;
460
461				vec4 result;
462				for (int i = 0; i < 4; i++) {
463					float currentByteOffset = baseByteOffset + float(i);
464					result[i] = getByteValue(currentByteOffset);
465				}
466				
467				fragColor = result;
468			}
469		`),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){y(this.gl);const n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(n)),n}createVAO(){y(this.gl),y(this.colorProgram);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){y(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return y(this.gl),y(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){y(this.gl),y(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:n}=this.canvas,i=Math.ceil(t/2)*Math.ceil(n/2),s=t*n+i*2,a=Math.ceil(s/(t*4));let o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,s),y(o[t*n]===128),y(o[o.length-1]===128);const c={format:"I420",codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){const i=new Blob([`(${Nx.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(i);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",a=>{const o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{const o=new Error(a.message||"Color/alpha splitter worker error.");for(const c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}const t=this.nextRequestId++,n=rt();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){var t,n,i;(n=(t=this.gl)==null?void 0:t.getExtension("WEBGL_lose_context"))==null||n.loseContext(),this.gl=null,this.canvas=null,(i=this.worker)==null||i.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const s of this.pendingRequests.values())s.reject(e);this.pendingRequests.clear()}}Qo.forceCpu=!0;const Nx=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",s=>{const{id:a,sourceFrame:o}=s.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async s=>{const a=s.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");
469const o=s.codedWidth,c=s.codedHeight,l=s.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await s.copyTo(r),a==="RGBA"||a==="BGRA")return n(r,o,c,a,s);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return i(r,o,c,a,s);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},n=(s,a,o,c,l)=>{const u=a*o,d=Math.ceil(a/2),f=Math.ceil(o/2),h=u+d*f*2,p=new Uint8Array(h);for(let w=0,b=3;w<u;w++,b+=4)p[w]=s[b];p.fill(128,u);const m=new VideoFrame(s,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),A={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[p.buffer]},g=new VideoFrame(p,A);return{colorFrame:m,alphaFrame:g}},i=(s,a,o,c,l)=>{const u=c.includes("P10"),d=c.includes("P12"),f=u||d?2:1;let h,p;c.startsWith("I420")?(h=Math.ceil(a/2),p=Math.ceil(o/2)):c.startsWith("I422")?(h=Math.ceil(a/2),p=o):(h=a,p=o);const m=a*o,A=h*p,g=m*f,w=A*f,b=m*f,k=g+w*2,S=c.replace("A",""),x=Math.ceil(a/2),B=Math.ceil(o/2),I=x*B,C=I*f,v=b+2*C,R=new Uint8Array(v),M=k;R.set(s.subarray(M,M+b),0);const z=b,W=u?512:d?2048:128;f===1?R.fill(W,z):new Uint16Array(R.buffer,z,2*I).fill(W);const H=u?"I420P10":d?"I420P12":"I420",U=new VideoFrame(s.subarray(0,k),{format:S,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),j={format:H,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[R.buffer]},ce=new VideoFrame(R,j);return{colorFrame:U,alphaFrame:ce}}};class Gu extends Zi{constructor(e){yu(e),super(e.codec),this._encoder=new Hu(this,e)}add(e,t){if(!(e instanceof gt))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Qx extends Zi{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");yu(t),super(t.codec),this._encoder=new Hu(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const i=new gt(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Lx extends Zi{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(yu(t),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=rt(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=n,this._encoder=new Hu(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");const e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,n=null,i=0,s=!1,a=null,o=0;const c=()=>{if(y(e!==null),!this._lastVideoFrame)return;y(n!==null),y(t!==null);const d=performance.now();for(;d-n>1e3/e;){n+=1e3/e;const f=t+i/e,h=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});u(h,d)}};e!==null&&(this._timerHandle=US(c,4));const l=d=>{var f;if(e===null)u(d);else{const h=performance.now();this._lastVideoFrame?(c(),(f=this._lastVideoFrame)==null||f.close(),this._lastVideoFrame=d):(u(d.clone(),h),n=h,this._lastVideoFrame=d)}},u=(d,f=performance.now())=>{if(s){d.close();return}i++;const h=d.timestamp/1e6;if(this._paused){if(t!==null){if(a!==null&&this._options.timestampBase!=="unix"){const A=h-a;o-=A}a=h}d.close();return}if(t===null){t=h;let m;const A=this._options.timestampBase??"synced-zero";if(A==="unix")m=Date.now()/1e3;else if(A==="zero")m=0;else{const g=this._connectedTrack.output;g._firstMediaStreamTimestamp===null?(g._firstMediaStreamTimestamp=f/1e3,m=0):m=f/1e3-g._firstMediaStreamTimestamp}o=m-t}if(a=h,this._encoder.getQueueSize()>=8){d.close();return}const p=new gt(d,{timestamp:h+o});this._encoder.add(p,!0).catch(m=>{var A;s=!0,(A=this._abortController)==null||A.abort(),this._promiseWithResolvers.reject(m),this._workerTrackId!==null&&Xu({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const d=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});d.readable.pipeTo(f,{signal:this._abortController.signal}).catch(h=>{h instanceof DOMException&&h.name==="AbortError"||this._promiseWithResolvers.reject(h)})}else if(await Yx())this._workerTrackId=Hx++,Xu({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{const h=f.data;h.type==="videoFrame"&&h.trackId===this._workerTrackId?l(h.videoFrame):h.type==="error"&&h.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(h.error)},Tr.addEventListener("message",this._workerListener);else if(e!==null){const f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=ne
469w MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;const h=new VideoFrame(f,{timestamp:1e3*performance.now()});l(h),h.close()},{once:!0}),f.play().catch(h=>{s=!0,this._promiseWithResolvers.reject(h)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){var t;this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&OS(this._timerHandle),(t=this._lastVideoFrame)==null||t.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(y(this._workerListener),Xu({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(n=>{const i=s=>{const a=s.data;a.type==="trackStopped"&&a.trackId===this._workerTrackId&&(y(this._workerListener),Tr.removeEventListener("message",this._workerListener),Tr.removeEventListener("message",i),n())};Tr.addEventListener("message",i)})),await this._encoder.flushAndClose(e)}}class es extends No{constructor(e){if(super(),this._connectedTrack=null,!bt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${bt.join(", ")}.`);this._codec=e}}class Yu extends es{constructor(e){super(e)}add(e,t){if(!(e instanceof He))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class Ku{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Is,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t){var n,i;try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const s=this.encodingConfig;((n=s.transform)==null?void 0:n.numberOfChannels)!==void 0||((i=s.transform)==null?void 0:i.sampleRate)!==void 0?(this.resampler||(this.resampler=new gw({targetNumberOfChannels:s.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:s.transform.sampleRate??e.sampleRate,startTime:e.timestamp,endTime:1/0,onSample:async o=>{await this.processAndEncode(o,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){var i,s;const n=this.encodingConfig;if(((i=n.transform)==null?void 0:i.sampleFormat)!==void 0&&SA(e.format)!==n.transform.sampleFormat){const a=CA(e,n.transform.sampleFormat);t&&e.close(),e=a,t=!0}if((s=n.transform)!=null&&s.process){let a=n.transform.process(e);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);for(const o of a){if(!(o instanceof kt))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(o,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized);
469{const n=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=i;else{const s=n-this.lastEndSampleIndex;if(s>=64){const a=new kt({data:new Float32Array(s*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:s,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const n=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(n)).then(()=>this.customEncoderQueueSize--).catch(s=>this.error??(this.error=s)).finally(()=>{n.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{y(this.encoder);const n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(i=>this.encoder.addEventListener("dequeue",i,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){var f,h;y(this.outputSampleSize),y(this.writeOutputValue);const{numberOfChannels:n,numberOfFrames:i,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let p=0;p<i;p+=o){const m=Math.min(o,e.numberOfFrames-p),A=m*n*this.outputSampleSize,g=new ArrayBuffer(A),w=new DataView(g);c.push({frameCount:m,view:w})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let p=0;p<n;p++){e.copyTo(u,{planeIndex:p,format:"f32-planar"});for(let m=0;m<c.length;m++){const{frameCount:A,view:g}=c[m];for(let w=0;w<A;w++)this.writeOutputValue(g,(w*n+p)*this.outputSampleSize,u[m*o+w])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:s}};for(let p=0;p<c.length;p++){const{frameCount:m,view:A}=c[p],g=A.buffer,w=p*o,b=new He(new Uint8Array(g),"key",a+w/s,m/s);(h=(f=this.encodingConfig).onEncodedPacket)==null||h.call(f,b,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,b,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var a,o;const{numberOfChannels:t,sampleRate:n}=e,i=PA({numberOfChannels:t,sampleRate:n,...this.encodingConfig});(o=(a=this.encodingConfig).onEncoderConfig)==null||o.call(a,i);const s=Bo.find(c=>c.supports(this.encodingConfig.codec,i));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(c,l)=>{var u,d;if(!(c instanceof He))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");(d=(u=this.encodingConfig).onEncodedPacket)==null||d.call(u,c,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,c,l).catch(f=>{this.error??(this.error=f)})},await this.customEncoder.init();else if(yt.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);const l=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,d)=>{var h,p;if(this.encodingConfig.codec==="aac"&&(d!=null&&d.decoderConfig)){let m=!1;if(!d.decoderConfig.description||d.decoderConfig.description.byteLength<2?m=!0:m=
469Rs(je(d.decoderConfig.description)).objectType===0,m){const A=Number(tt(i.codec.split(".")));d.decoderConfig.description=yl({objectType:A,numberOfChannels:d.decoderConfig.numberOfChannels,sampleRate:d.decoderConfig.sampleRate})}}let f=He.fromEncodedChunk(u);f=f.clone({timestamp:Ci(f.timestamp,i.sampleRate),duration:u.duration!=null?Ci(f.duration,i.sampleRate):void 0}),(p=(h=this.encodingConfig).onEncodedPacket)==null||p.call(h,f,d),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,f,d).catch(m=>{this.error??(this.error=m)})},error:u=>{u.stack=l,this.error??(this.error=u)}}),this.encoder.configure(i)}y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:i}=Ar(e);switch(this.outputSampleSize=n,n){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,It((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,It(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=It(Math.floor(o*32767),-32768,32767);s.setUint8(a,UI(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=It(Math.floor(o*32767),-32768,32767);s.setUint8(a,NI(c))}:y(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,It((o+1)*32767.5,0,65535),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,It(Math.round(o*32767),-32768,32767),i):y(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>Ga(s,a,It((o+1)*83886075e-1,0,16777215),i):t==="signed"?this.writeOutputValue=(s,a,o)=>TS(s,a,It(Math.round(o*8388607),-8388608,8388607),i):y(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,It((o+1)*21474836475e-1,0,4294967295),i):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,It(Math.round(o*2147483647),-2147483648,2147483647),i):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,i):y(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,i):y(!1);break;default:Ut(n),y(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}class qu extends es{constructor(e){bu(e),super(e.codec),this._encoder=new Ku(this,e)}add(e){if(!(e instanceof kt))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class zx extends es{constructor(e){bu(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Ku(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=kt._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const n of t)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Wx extends es{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(bu(t),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=rt(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=n,this._encoder=new Ku(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,n=null,i=0;const s=a=>
469{if(t){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){const l=o-n;i-=l}n=o}a.close();return}if(e===null){e=a.timestamp;let c;const l=this._options.timestampBase??"synced-zero";if(l==="unix")c=Date.now()/1e3;else if(l==="zero")c=0;else{const u=this._connectedTrack.output;u._firstMediaStreamTimestamp===null?(u._firstMediaStreamTimestamp=performance.now()/1e3,c=0):c=performance.now()/1e3-u._firstMediaStreamTimestamp}i=c-e}if(n=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+i),this._encoder.add(a,!0).catch(c=>{var l,u;t=!0,(l=this._abortController)==null||l.abort(),this._promiseWithResolvers.reject(c),(u=this._audioContext)==null||u.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>s(new kt(c))});a.readable.pipeTo(o,{signal:this._abortController.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||this._promiseWithResolvers.reject(c)})}else{const a=window.AudioContext||window.webkitAudioContext;this._audioContext=new a({sampleRate:this._track.getSettings().sampleRate});const o=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),o.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let c=0;this._scriptProcessorNode.onaudioprocess=l=>{const u=kt._fromAudioBuffer(l.inputBuffer,c);c+=l.inputBuffer.duration;for(const d of u)s(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(y(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}const Vx=()=>{const r=(n,i)=>{i?self.postMessage(n,{transfer:i}):self.postMessage(n)};r({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",n=>{const i=n.data;switch(i.type){case"videoTrack":{t.set(i.trackId,i.track);const s=new MediaStreamTrackProcessor({track:i.track}),a=new WritableStream({write:c=>{if(!t.has(i.trackId)){c.close();return}r({type:"videoFrame",trackId:i.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(i.trackId,o),s.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||r({type:"error",trackId:i.trackId,error:c})})}break;case"stopTrack":{const s=e.get(i.trackId);s&&(s.abort(),e.delete(i.trackId));const a=t.get(i.trackId);a==null||a.stop(),t.delete(i.trackId),r({type:"trackStopped",trackId:i.trackId})}break;default:Ut(i)}})};let Hx=0,Tr=null;const Gx=()=>{const r=new Blob([`(${Vx.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(r);Tr=new Worker(e)};let ju=null;const Yx=async()=>ju!==null?ju:(Tr||Gx(),new Promise(r=>{y(Tr);const e=t=>{const n=t.data;n.type==="support"&&(ju=n.supported,Tr.removeEventListener("message",e),r(n.supported))};Tr.addEventListener("message",e)})),Xu=(r,e)=>{y(Tr),Tr.postMessage(r)};class Ju extends No{constructor(e){if(super(),this._connectedTrack=null,!gr.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${gr.join(", ")}.`);this._codec=e}}class Kx extends Ju{constructor(e){super(e),this._error=null,this._lastMuxerPromise=Promise.resolve(),this._parser=new aB({codec:e,output:(t,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,n).catch(i=>{this._error??(this._error=i)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose(e){e||this._checkForError()}}/*!
470 * Copyright (c) 2026-present, Vanilagy and contributors
471 *
472 * This Source Code Form is subject to the terms of the Mozilla Public
473 * License, v. 2.0. If a copy of the MPL was not distributed with this
474 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
475 */class qx extends Zr{constructor(e,t){if(!(e._target instanceof tn))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n})=>`playlist-${n}
475.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(A=>A.metadata.isRelativeToUnixEpoch),n=this.output._tracks.some(A=>!A.metadata.isRelativeToUnixEpoch);if(t&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;const i=new Map,s=[];let a=!1,o=!1,c=!1;for(const A of this.output._tracks){A.type==="video"&&(a=!0);const g=new Map;for(const w of this.output._tracks){if(A===w||!A.canBePairedWith(w))continue;if(A.type===w.type){o||(console.warn(`Illegal pairing of two ${A.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(A.isVideoTrack()&&A.metadata.hasOnlyKeyPackets||w.isVideoTrack()&&w.metadata.hasOnlyKeyPackets){c||(console.warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),c=!0);continue}let b=g.get(w.source._codec);b||g.set(w.source._codec,b=[]),b.push(w)}for(const[,w]of g){const b=w.map(x=>x.id).join("-");s.find(x=>x.key===b)||s.push({name:w[0].type+"-"+(s.length+1),key:b,tracks:w,needsEmit:!1,firstNoUri:!1});let S=i.get(A);S||i.set(A,S=[]),S.push(b)}}const l=a?"video":"audio",u=[],d=[],f=[];for(const A of this.output._tracks){const g=i.get(A);if(g){if(y(g.length>0),A.type!==l)continue;for(const w of g){const b=s.find(k=>k.key===w);if(y(b),g.length===1&&b.tracks.length===1){const k=i.get(b.tracks[0]);if(y(k!==void 0),k.length===1){const S=s.find(x=>x.key===k[0]);if(S.tracks.length===1){y(S.tracks[0]===A),u.push({tracks:[A,b.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[A],linkedGroup:b}),b.needsEmit=!0}}else A.type==="video"?d.push(A):A.type==="audio"&&f.push(A)}const h=({metadata:A})=>{var w,b,k;let g="";return g+=`${A.languageCode??Bt}-`,g+=`${A.name??""}-`,g+=`${((w=A.disposition)==null?void 0:w.default)??!0}-`,g+=`${((b=A.disposition)==null?void 0:b.primary)??!1}-`,g+=`${((k=A.disposition)==null?void 0:k.forced)??!1}-`,g};if(d.length>0)if(new Set(d.map(h)).size>1){const g={key:d.map(w=>w.id).join("-"),name:"video-"+(s.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};s.push(g),u.push({tracks:[d[0]],linkedGroup:g})}else for(const g of d)u.push({tracks:[g],linkedGroup:null});if(f.length>0)if(new Set(f.map(h)).size>1){const g={key:f.map(w=>w.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(g),u.push({tracks:[f[0]],linkedGroup:g})}else for(const g of f)u.push({tracks:[g],linkedGroup:null});const p=A=>{const g=[];let w=0,b=0,k=!1,S=null,x=-1/0;for(const B of A)B.isVideoTrack()?(w++,k||(k=(B.metadata.rotation??0)!==0)):B.isAudioTrack()&&b++,g.push(B.source._codec);for(const B of Pi(this.format._options.segmentFormat)){const I=B.getSupportedCodecs(),C=B.getSupportedTrackCounts();if(g.some(R=>!I.includes(R))||w<C.video.min||w>C.video.max||b<C.audio.min||b>C.audio.max)continue;let v=0;k&&B.supportsVideoRotationMetadata&&v++,v>x&&(S=B,x=v)}return y(S),S},m=async A=>{if(A.some(S=>this.playlists.some(x=>x.tracks.includes(S))))throw new Error("Internal error: track is already registered in a playlist.");const g=p(A),w=this.playlists.length+1,b=await this.getPlaylistPath({n:w,tracks:A,segmentFormat:g});jx(b);const k={id:this.playlists.length+1,path:b,tracks:A,segmentFormat:g,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new zn};return this.playlists.push(k),k};for(const A of s)if(A.needsEmit)for(let g=0;g<A.tracks.length;g++){const w=A.tracks[g];let b=this.playlists.find(k=>k.tracks[0].id===w.id);b??(b=await m([w])),this.playlistDeclarations.push({playlist:b,groupId:A.name,noUri:A.firstNoUri&&g===0,references:[]})}for(const A of u){let g=this.playlists.find(w=>w.tracks[0].id===A.tracks[0].id);g??(g=await m(A.tracks)),this.playlistDeclarations.push({playlist:g,groupId:null,noUri:!1,references:A.linkedGroup?this.playlistDeclarations.filter(w=>w.groupId===A.linkedGroup.name):[]})}e()}async getMimeType(){return Vi}allTracksAreKnown(e){for(const t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(n=>n.track===t))return!1;return!0}async onTrackClose(e){const t=this.trackDatas.find(s=>s.track===e);t&&(t.closed=!0);const n=this.playlists.find(s=>s.tracks.includes(e));
475y(n);const i=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{i()}}getVideoTrackData(e,t){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ja(t),y(t),y(t==null?void 0:t.decoderConfig);const i=this.playlists.filter(s=>s.tracks.includes(e));return y(i.length===1),n={track:e,packets:[],playlist:i[0],closed:!1,info:{type:"video",decoderConfig:t.decoderConfig}},this.trackDatas.push(n),n}getAudioTrackData(e,t){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;yn(t),y(t),y(t==null?void 0:t.decoderConfig);const i=this.playlists.filter(s=>s.tracks.includes(e));return y(i.length===1),n={track:e,packets:[],playlist:i[0],closed:!1,info:{type:"audio",decoderConfig:t.decoderConfig}},this.trackDatas.push(n),n}async addEncodedVideoPacket(e,t,n){const i=this.getVideoTrackData(e,n),s=i.playlist,a=await s.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),i.packets.push(t),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=t.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(s)}finally{a()}}async addEncodedAudioPacket(e,t,n){const i=this.getAudioTrackData(e,n),s=i.playlist,a=await s.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),i.packets.push(t),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=t.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(s)}finally{a()}}async addSubtitleCue(e,t,n){throw new Error("Unreachable.")}async advancePlaylist(e){var s,a,o,c;if(y(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}const t=this.trackDatas.filter(l=>e.tracks.includes(l.track)),n=t.find(l=>l.info.type==="video"),i=t.find(l=>l.info.type==="audio");for(;;){const l=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let u=0,d=0;if(n&&(!n.closed||n.packets.length>0)){const B=n.packets.every(v=>v.timestamp<l);let I=null,C=null;if(B){if(!n.closed)return}else for(let v=0;v<n.packets.length;v++){const R=n.packets[v];if(I!==null&&R.timestamp>l)break;v>0&&R.type==="key"&&(I=R,C=v)}if(C!==null){if(u=C,i){const v=i.packets.findIndex(R=>R.timestamp>=I.timestamp);if(v!==-1)d=v;else if(i.closed)d=i.packets.length;else return}}else{if(!n.closed)return;u=n.packets.length;const v=RS(n.packets,M=>M.timestamp),R=n.packets[v];if(y(R),i)if(R.timestamp<l){const M=i.packets.findIndex(z=>z.timestamp>=l);if(M!==-1)d=M;else if(i.closed)d=i.packets.length;else return}else{const M=i.packets.findIndex(z=>z.timestamp>R.timestamp);if(M!==-1)d=M;else if(i.closed)d=i.packets.length;else return}}}else if(i&&(!i.closed||i.packets.length>0))if(i.packets.every(I=>I.timestamp<l))if(i.closed)d=i.packets.length;else return;else{const I=Va(i.packets,C=>C.timestamp<=l);d=Math.max(I,1)}if(u===0&&d===0){t.every(I=>I.closed)&&await this.onPlaylistDone(e);return}let f=null,h,p;y(this.output._target instanceof tn);const m=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const B={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Lo(e)};
475h=await this.getSegmentPath(B),ww(h),p=Dt(Dt(m.rootPath,e.path),h);const I=await this.output._getTarget({path:p,isRoot:!1,mimeType:e.segmentFormat.mimeType});I._start(),e.singleFile={target:I,path:h,nextOffset:0,info:B}}else h=e.singleFile.path,p=Dt(Dt(m.rootPath,e.path),h);else f={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Lo(e)},h=await this.getSegmentPath(f),ww(h),p=Dt(Dt(m.rootPath,e.path),h),e.nextSegmentId++;let A=0,g=null;const w=new Wo({format:e.segmentFormat,target:new tn(p,async B=>{const I={...B,isRoot:!1};if(B.isRoot)if(e.singleFile){const C=e.singleFile.target.slice(e.singleFile.nextOffset);return C.on("write",({end:v})=>A=Math.max(A,v)),C}else{const C=await this.output._getTarget(I);return g=C,C.on("write",({end:v})=>A=Math.max(A,v)),C}return this.output._getTarget(I)}),initTarget:async()=>{if(e.initSegment)return new zu;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const B=e.singleFile.target.slice(e.singleFile.nextOffset);return B.on("write",({end:I})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,I)}),B.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),B}else{const B=Lo(e),I=await this.getInitPath(B);Xx(I),e.initSegment={path:I,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const C=Dt(Dt(m.rootPath,e.path),I),v=await this.output._getTarget({path:C,isRoot:!1,mimeType:e.segmentFormat.mimeType});return v.on("write",({end:R})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,R)}),v.on("finalized",()=>{var R,M;(M=(R=this.format._options).onInit)==null||M.call(R,v,B)}),v}}});let b=-1/0;try{let B=null,I=null;if(n&&(B=new Vu(n.track.source._codec),w.addVideoTrack(B,n.track.metadata)),i&&(I=new Yu(i.track.source._codec),w.addAudioTrack(I,i.track.metadata)),await w.start(),n){y(B);const C={decoderConfig:n.info.decoderConfig};for(let v=0;v<u;v++){const R=n.packets[v];await B.add(R,C),b=Math.max(b,R.timestamp+R.duration)}}if(i){y(I);const C={decoderConfig:i.info.decoderConfig};for(let v=0;v<d;v++){const R=i.packets[v];await I.add(R,C),b=Math.max(b,R.timestamp+R.duration)}}await w.finalize()}catch(B){throw await w.cancel(),B}f&&(y(g),(a=(s=this.format._options).onSegment)==null||a.call(s,g,f)),u>0&&(y(n),n.packets.splice(0,u)),d>0&&(y(i),i.packets.splice(0,d));let k=1/0;n&&n.packets.length>0&&(k=n.packets[0].timestamp),i&&i.packets.length>0&&(k=Math.min(k,i.packets[0].timestamp));const S=k<1/0?k:b;y(Number.isFinite(S));const x=S-e.currentSegmentStartTimestamp;if(y(x>=0),e.writtenSegments.push({path:h,duration:x,timestamp:e.currentSegmentStartTimestamp,byteSize:A,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:f??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,x),e.currentSegmentStartTimestamp=S,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=A),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const B=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(y(B.info),(c=(o=this.format._options).onSegmentPopped)==null||c.call(o,B.path,B.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){var t,n;y(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),(n=(t=this.format._options).onSegment)==null||n.call(t,e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){const t=e.writtenSegments;let n=0,i=0,s=0;for(let a=0;a<t.length;
475a++){s+=t[a].duration;let o=0,c=0;for(let l=a;l<t.length&&(o+=t[l].byteSize,c+=t[l].duration,c>=.5*this.globalTargetDuration&&c<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*o/c)),!(c>1.5*this.globalTargetDuration));l++);}if(n===0)for(const a of t){const o=a.duration||1;n=Math.max(n,8*a.byteSize/o)}for(const a of t)i+=8*a.byteSize;e.peakBitrate=n,e.averageBitrate=i/(s||1)}async writePlaylist(e){var d,f;y(this.output._target instanceof tn);const t=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(const h of e.writtenSegments)n||(n=h.byteOffset!==null);const i=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let s=3;(i||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!i&&(s=6);const a=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=Dt(t.rootPath,e.path),c=`#EXTM3U
476#EXT-X-VERSION:${s}
477`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
478`)+`#EXT-X-TARGETDURATION:${Math.ceil(a)}
479`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
480`:"")+`#EXT-X-INDEPENDENT-SEGMENTS
481`+(i?`#EXT-X-I-FRAMES-ONLY
482`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
483`:"")+`
484`+e.writtenSegments.map(h=>`#EXTINF:${+h.duration.toFixed(12)},
485`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*h.timestamp).toISOString()}
486`:"")+(h.byteOffset!==null?`#EXT-X-BYTERANGE:${h.byteSize}@${h.byteOffset}
487`:"")+`${h.path}
488`).join("")+(e.done?(e.writtenSegments.length>0?`
489`:"")+`#EXT-X-ENDLIST
490`:"");(f=(d=this.format._options).onPlaylist)==null||f.call(d,c,Lo(e));const l=await this.output._getTarget({path:o,isRoot:!1,mimeType:Vi}),u=new ra(l,!0);u.start(),u.write(Ve.encode(c)),await u.flush(),await u.finalize()}async writeMasterPlaylist(){var c,l;y(this.output._target instanceof tn);const e=this.output._target;let t=`#EXTM3U
491`,n=!1,i=null,s=0,a=!1;for(const u of this.playlistDeclarations)if(u.groupId===null){const d=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,f=[];for(const w of u.playlist.tracks){const b=this.trackDatas.find(S=>S.track===w),k=(b==null?void 0:b.info.decoderConfig.codec)??w.source._codec;f.push(k)}let h=0,p=0;if(u.references.length>0){const b=u.references[0].playlist.tracks[0],k=this.trackDatas.find(x=>x.track===b),S=(k==null?void 0:k.info.decoderConfig.codec)??b.source._codec;f.push(S);for(const x of u.references)y(x.playlist.peakBitrate!==null),h=Math.max(h,x.playlist.peakBitrate),p=Math.max(p,x.playlist.averageBitrate??0)}y(u.playlist.peakBitrate!==null);const m=u.playlist.peakBitrate+h,A=(u.playlist.averageBitrate??0)+p;n||(t+=`
492`,n=!0),d?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(m)}`,A>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(A)}`),t+=`,CODECS="${f.join(",")}"`;const g=u.playlist.tracks.find(w=>w.isVideoTrack());if(g!=null&&g.isVideoTrack()){const w=this.trackDatas.find(k=>k.track===g),b=w==null?void 0:w.info.decoderConfig;if(b){let k=b.displayAspectWidth??b.codedWidth,S=b.displayAspectHeight??b.codedHeight;k!==void 0&&S!==void 0&&(g.metadata.rotation!==void 0&&g.metadata.rotation%180===90&&([k,S]=[S,k]),t+=`,RESOLUTION=${k}x${S}`)}!d&&g.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+g.metadata.frameRate.toFixed(3)}`)}if(!d){const w=new Map;for(const b of u.references){y(b.groupId!==null);const k=b.playlist.tracks[0].type;w.set(k,b.groupId)}for(const[b,k]of w)t+=`,${b.toUpperCase()}="${k}"`}d?(t+=`,URI="${u.playlist.path}"`,t+=`
493`):(t+=`
494`,t+=`${u.playlist.path}
495`)}else{y(u.playlist.tracks.length===1);const d=u.playlist.tracks[0],f=d.type;let h=d.metadata.name??null;const p=d.metadata.languageCode,m=d.metadata.disposition;(i===null||u.groupId!==i)&&(s=0,t+=`
496`,a=!1),i=u.groupId,s++,t+=`#EXT-X-MEDIA:TYPE=${f.toUpperCase()},GROUP-ID="${u.groupId}"`,h!==null&&/[\n\r"]/.test(h)&&(console.warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),h=null),h??(h=`${p??u.groupId}-${s}`),t+=`,NAME="${h}"`,p!==void 0&&(t+=`,LANGUAGE="${p}"`);const A=(m==null?void 0:m.primary)??!1,g=(m==null?void 0:m.default)??!0,w=(m==null?void 0:m.forced)??!1;if(A&&!a&&(t+=",DEFAULT=YES",a=!0),(A||g)&&(t+=",AUTOSELECT=YES"),w&&(t+=",FORCED=YES"),f==="audio"){const b=this.trackDatas.find(S=>S.track===d),k=b==null?void 0:b.info.decoderConfig;k&&(t+=`,CHANNELS="${k.numberOfChannels}"`)}u.noUri||(t+=`,URI="${u.playlist.path}"`),t+=`
497`}(l=(c=this.format._options).onMaster)==null||l.call(c,t);const o=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{const d=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Vi});
497u=new ra(d,!0),u.start()}u.write(Ve.encode(t)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){y(this.isLive);for(const e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(t=>t.mutex.acquire()))).forEach(t=>t());for(const t of this.trackDatas)t.closed=!0;await Promise.all(this.playlists.map(t=>t.done?Promise.resolve():this.advancePlaylist(t))),this.isLive||await this.writeMasterPlaylist()}}const jx=r=>{if(typeof r!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},ww=r=>{if(typeof r!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},Xx=r=>{if(typeof r!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Lo=r=>({n:r.id,tracks:r.tracks,segmentFormat:r.segmentFormat});/*!
498 * Copyright (c) 2026-present, Vanilagy and contributors
499 *
500 * This Source Code Form is subject to the terms of the Mozilla Public
501 * License, v. 2.0. If a copy of the MPL was not distributed with this
502 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
503 */class nr{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>dt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>bt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>gr.includes(e))}_codecUnsupportedHint(e){return""}}class zo extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new kx(e,this)}}class $u extends zo{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...dt,...An,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...gr]}_codecUnsupportedHint(e){return new ed().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Zu extends zo{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...dt,...An,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...gr]}}class ed extends zo{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...dt,...bt]}_codecUnsupportedHint(e){return new $u().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class td extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");
503if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Ix(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...dt,...An,...yt.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...gr]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class rd extends td{constructor(e){super(e)}getSupportedCodecs(){return[...dt.filter(e=>["vp8","vp9","av1"].includes(e)),...bt.filter(e=>["opus","vorbis"].includes(e)),...gr]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new td().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class Jx extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new xx(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class $x extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Ox(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...yt.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class Zx extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Number.isFinite(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new vx(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...bt.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class e1 extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new tB(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class t1 extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new iB(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class r1 extends nr{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Rx(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:1,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...dt.filter(e=>["avc","hevc"].includes(e)),...bt.filter(e=>["aac","mp3","ac3","eac3"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class n1 extends nr{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof nr)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof nr)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(typeof e.targetDuration!="number"||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!="number"||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");
503if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new qx(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Vi}getSupportedCodecs(){return[...new Set(Pi(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,n=!1;for(const i of Pi(this._options.segmentFormat)){const s=i.getSupportedTrackCounts();e||(e=s.video.max>0),t||(t=s.audio.max>0),n||(n=s.subtitle.max>0)}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:1,max:1/0}}}get supportsVideoRotationMetadata(){return Pi(this._options.segmentFormat).some(e=>e.supportsVideoRotationMetadata)}get supportsTimestampedMediaData(){return!0}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}/*!
504 * Copyright (c) 2026-present, Vanilagy and contributors
505 *
506 * This Source Code Form is subject to the terms of the Mozilla Public
507 * License, v. 2.0. If a copy of the MPL was not distributed with this
508 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
509 */const yw=["video","audio","subtitle"];class ts{constructor(e,t,n,i,s){this.id=e,this.output=t,this.type=n,this.source=i,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof ts))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Pi(this.metadata.group),n=Pi(e.metadata.group);for(const i of t)if(this.type!==e.type&&n.some(o=>i===o)||n.some(o=>i._pairedGroups.has(o)))return!0;return!1}}class bw extends ts{constructor(e,t,n,i){super(e,t,"video",n,i)}}class Ew extends ts{constructor(e,t,n,i){super(e,t,"audio",n,i)}}class kw extends ts{constructor(e,t,n,i){super(e,t,"subtitle",n,i)}}class mr{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof mr))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const nd=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!Cs(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&QS(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof mr)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof mr))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Wo extends _s{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new mr,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new zn,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof nr))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Kt||e.target instanceof tn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Kt&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Kt)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Kt&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){y(this._target instanceof tn);const t=this._target.getTarget(e),n=i=>{if(!(i instanceof Kt))throw new TypeError("getTarget must return a Target.");return i};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){y(this._target instanceof tn);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}
509async _getInitTarget(){if(y(this._initTarget!==null),this._initTarget instanceof Kt)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Kt)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=i=>(this.state==="canceled"?i._close():this._rememberTarget(i),this._emit("target",{target:i,request:e,isRoot:!0}),this._rootTarget=i,i);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const t=await this._getRootTarget(),n=new ra(t,typeof e=="boolean"?e:e(t));return n.start(),n})())}addVideoTrack(e,t={}){if(!(e instanceof Zi))throw new TypeError("source must be a VideoSource.");if(nd(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);const n={...t};return n.group??(n.group=this.defaultTrackGroup),this._addTrack(new bw(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof es))throw new TypeError("source must be an AudioSource.");nd(t);const n={...t};return n.group??(n.group=this.defaultTrackGroup),this._addTrack(new Ew(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Ju))throw new TypeError("source must be a SubtitleSource.");nd(t);const n={...t};return n.group??(n.group=this.defaultTrackGroup),this._addTrack(new kw(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(wl(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),i=t[e.type].max;if(n===i)throw new Error(i===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${i} ${e.type} track${i===1?"":"s"}.`);const s=t.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}
509async start(){const e=this.format.getSupportedTrackCounts();for(const n of yw){const i=this._tracks.reduce((a,o)=>a+(o.type===n?1:0),0),s=e[n].min;if(i<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const n=await this._mutex.acquire();try{await this._muxer.start();const i=this._tracks.map(s=>s.source._start());await Promise.all(i)}finally{n()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this._tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}}/*!
510 * Copyright (c) 2026-present, Vanilagy and contributors
511 *
512 * This Source Code Form is subject to the terms of the Mozilla Public
513 * License, v. 2.0. If a copy of the MPL was not distributed with this
514 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
515 */const Vo=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if((r==null?void 0:r.discard)!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if((r==null?void 0:r.forceTranscode)!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if((r==null?void 0:r.codec)!==void 0&&!dt.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${dt.join(", ")}.`);if((r==null?void 0:r.bitrate)!==void 0&&!(r.bitrate instanceof Ht)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if((r==null?void 0:r.width)!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if((r==null?void 0:r.height)!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if((r==null?void 0:r.fit)!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");
515if((r==null?void 0:r.width)!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if((r==null?void 0:r.rotate)!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if((r==null?void 0:r.allowRotationMetadata)!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if((r==null?void 0:r.crop)!==void 0&&Gs(r.crop,"options.video."),(r==null?void 0:r.frameRate)!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if((r==null?void 0:r.alpha)!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if((r==null?void 0:r.keyFrameInterval)!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if((r==null?void 0:r.process)!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if((r==null?void 0:r.processedWidth)!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if((r==null?void 0:r.processedHeight)!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if((r==null?void 0:r.hardwareAcceleration)!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if((r==null?void 0:r.group)!==void 0&&!(r.group instanceof mr||Array.isArray(r.group)&&r.group.every(e=>e instanceof mr)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Ho=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if((r==null?void 0:r.discard)!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if((r==null?void 0:r.forceTranscode)!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if((r==null?void 0:r.codec)!==void 0&&!bt.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${bt.join(", ")}.`);if((r==null?void 0:r.bitrate)!==void 0&&!(r.bitrate instanceof Ht)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if((r==null?void 0:r.numberOfChannels)!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if((r==null?void 0:r.sampleRate)!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if((r==null?void 0:r.sampleFormat)!==void 0&&!["u8","s16","s32","f32"].includes(r.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if((r==null?void 0:r.process)!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if((r==null?void 0:r.processedNumberOfChannels)!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if((r==null?void 0:r.processedSampleRate)!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if((r==null?void 0:r.group)!==void 0&&!(r.group instanceof mr||Array.isArray(r.group)&&r.group.every(e=>e instanceof mr)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},id=2,sd=48e3;class ad{static async init(e){const t=new ad(e);return await t._init(),t}constructor(e){var i,s,a;if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPromises=[],this._executed=!1,this._synchronizer=new i1,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof $s))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Wo))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");
515if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const o of e.video)Vo(o);else Vo(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const o of e.audio)Ho(o);else Ho(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(((i=e.trim)==null?void 0:i.start)!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(((s=e.trim)==null?void 0:s.end)!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(((a=e.trim)==null?void 0:a.start)!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&wl(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output;const{promise:t,resolve:n}=rt();this._started=t,this._start=n}async _init(){var h,p;const e=await this.input.getFormat();let t,n=this._options.tracks;if(n===void 0&&(n=e.name.includes("(HLS)")?"primary":"all"),n==="all")t=await this.input.getTracks();else if(n==="primary"){const m=await this.input.getPrimaryVideoTrack(),A=await this.input.getPrimaryAudioTrack();t=[m,A].filter(g=>g!==null)}else Ut(n),y(!1);const i=this.output.format.getSupportedTrackCounts();let s=1,a=1;const o=[],c=[];for(const m of t){let A;if(m.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const b=await this._options.video(m,s)??{};if(Array.isArray(b))for(const k of b)Vo(k);else Vo(b);A=Array.isArray(b)?b:[b],s++}else A=Array.isArray(this._options.video)?this._options.video:[this._options.video];else A=[{}];else if(m.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const b=await this._options.audio(m,a)??{};if(Array.isArray(b))for(const k of b)Ho(k);else Ho(b);A=Array.isArray(b)?b:[b],a++}else A=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else A=[{}];else y(!1);const g=A.filter(b=>b.discard);for(const b of g)this.discardedTracks.push({track:m,reason:"discarded_by_user",trackOptions:b});if(A.length===g.length){A.length===0&&this.discardedTracks.push({track:m,reason:"discarded_by_user",trackOptions:{}});continue}const w=A.filter(b=>!b.discard);o.push(m),c.push(w)}((h=this._options.trim)==null?void 0:h.start)!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(((p=this._options.trim)==null?void 0:p.end)??1/0,this._startTimestamp);for(let m=0;m<o.length;m++){const A=o[m],g=c[m];for(const w of g){if(this._totalTrackCount===i.total.max){this.discardedTracks.push({track:A,reason:"max_track_count_reached",trackOptions:w});continue}if(this._addedCounts[A.type]===i[A.type].max){this.discardedTracks.push({track:A,reason:"max_track_count_of_type_reached",trackOptions:w});continue}const b=this._nextOutputTrackId++;A.isVideoTrack()?await this._processVideoTrack(A,w,b):A.isAudioTrack()?await this._processAudioTrack(A,w,b):y(!1)}}for(let m=0;m<this.utilizedTracks.length-1;m++)for(let A=m+1;A<this.utilizedTracks.length;A++){const g=this.utilizedTracks[m],w=this.utilizedTracks[A],b=this._outputOwnTrackGroups[m],k=this._outputOwnTrackGroups[A];y(b!==void 0),y(k!==void 0),b&&k&&g.canBePairedWith(w)&&b.pairWith(k)}const l=await this.input.getMetadataTags();let u;if(this._options.tags){const m=typeof this._options.tags=="function"?await this._options.tags(l):this._options.tags;wl(m),u=m}else u=l;const d=e.mimeType===this.output.format.mimeType,f=l.raw===u.raw;if(l.raw&&f&&!d&&delete u.raw,this.output.setMetadataTags(u),this.isValid=this._totalTrackCount>=i.total.min&&this._addedCounts.video>=i.video.min&&this._addedCounts.audio>=i.audio.min&&this._addedCounts.subtitle>=i.subtitle.min,this._options.showWarnings??!0){const m=[],A=this.discardedTracks.filter(g=>g.reason!=="discarded_by_user");A.length>0&&m.push("Some tracks had to be discarded from the conversion:",A),this.isValid||(m.length>0&&m.push(`
516
517`),m.push(this._getInvalidityExplanation().join(""))),m.length>0&&console.warn(...m)}}_getInvalidityExplanation(){const e=[];
517if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(n=>n.reason==="discarded_by_user"||n.reason==="no_encodable_target_codec")&&this.discardedTracks.some(n=>n.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const n=this.discardedTracks.flatMap(s=>s.reason==="discarded_by_user"?[]:s.track.type==="video"?this.output.format.getSupportedVideoCodecs():s.track.type==="audio"?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()),i=[...new Set(n)];i.length===1?e.push(`
518Tracks were discarded because your environment is not able to encode '${i[0]}'.`):e.push(`
519Tracks were discarded because your environment is not able to encode any of the following codecs: ${i.map(s=>`'${s}'`).join(", ")}.`),i.includes("mp3")&&e.push(`
520The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),i.includes("aac")&&e.push(`
521The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(i.includes("ac3")||i.includes("eac3"))&&e.push(`
522The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),i.includes("flac")&&e.push(`
523The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
524Check the discardedTracks field for more info.`)}return e}async execute(){var e,t;if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
525`+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0;for(const n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){const i=[...new Set(this.utilizedTracks)].map(async a=>await a.isLive()?1/0:await a.getDurationFromMetadata()??await a.computeDuration()),s=Math.max(0,...await Promise.all(i));this._computeProgress=!0,this._totalDuration=Math.min(s-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const a of this._outputTrackIds)this._maxTimestamps.set(a,0);(e=this.onProgress)==null||e.call(this,0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(n){throw this._canceled||this.cancel(),n}if(this._canceled)throw new Tw;if(await this.output.finalize(),this._computeProgress){const n=Math.min(...this._maxTimestamps.values());(t=this.onProgress)==null||t.call(this,1,n)}}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t,n){const i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getRotation(),o=Ti(a+(t.rotate??0));let c=o;const l=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),u=await e.getSquarePixelWidth(),d=await e.getSquarePixelHeight(),[f,h]=o%180===0?[u,d]:[d,u];let p=t.crop;p&&(p=yo(p,f,h));const[m,A]=p?[p.width,p.height]:[f,h];let g=m,w=A;const b=g/w;t.width!==void 0&&t.height===void 0?(g=vi(t.width),w=vi(Math.round(g/b))):t.width===void 0&&t.height!==void 0?(w=vi(t.height),g=vi(Math.round(w*b))):t.width!==void 0&&t.height!==void 0&&(g=vi(t.width),w=vi(t.height));const k=await e.getFirstTimestamp();let S=this.output.format.getSupportedVideoCodecs();const x=!!t.forceTranscode||k<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!S.includes(i)||t.codec&&t.codec!==i||g!==m||w!==A||o!==0&&!l||!!p,B=t.alpha??"discard";if(x){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(S=S.filter(U=>U===t.codec));const R=t.bitrate??Eu,M=await FA(S,{width:t.process&&t.processedWidth?t.processedWidth:g,height:t.process&&t.processedHeight?t.processedHeight:w,bitrate:R});if(!M){this.discardedTracks.push({track:e,reason:"no_encodable_target_co
525dec",trackOptions:t});return}const z={codec:M,bitrate:R,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:B,hardwareAcceleration:t.hardwareAcceleration,transform:{}};y(z.transform);let W=g!==m||w!==A||o!==0&&(!l||t.process!==void 0)||!!p||u!==await e.getCodedWidth()||d!==await e.getCodedHeight();if(!W){const U=new Wo({format:new $u,target:new zu}),j=new Gu(z);U.addVideoTrack(j),await U.start();const ee=await new Po(e).getSample(k);if(ee)try{await j.add(ee),ee.close(),await U.finalize()}catch(fe){console.info("Error when probing encoder support. Falling back to rerender path.",fe),W=!0,U.cancel()}else await U.cancel()}t.frameRate&&(z.transform.frameRate=t.frameRate),W&&(c=0,z.transform.width=g,z.transform.height=w,z.transform.fit=t.fit??"fill",z.transform.rotate=Ti(o-a),z.transform.crop=p,z.transform.alpha=B);const H=new Gu(z);s=H,this._trackPromises.push((async()=>{await this._started;const U=new Po(e);for await(const j of U.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){j.close();return}const ce=Math.max(j.timestamp-this._startTimestamp,0);j.setTimestamp(ce),await this._registerVideoSample(t,n,H,j),j.close()}H.close(),this._synchronizer.closeTrack(n)})())}else{const v=new Vu(i);s=v,this._trackPromises.push((async()=>{await this._started;const R=new Yi(e),z={decoderConfig:await e.getDecoderConfig()??void 0};for await(const W of R.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(W.timestamp>=this._endTimestamp)break;const H=W.clone({timestamp:W.timestamp-this._startTimestamp,sideData:B==="discard"?{}:W.sideData});y(H.timestamp>=0),this._reportProgress(n,H.timestamp+H.duration),await v.add(H,z),this._synchronizer.shouldWait(n,H.timestamp)&&await this._synchronizer.wait(H.timestamp)}v.close(),this._synchronizer.closeTrack(n)})())}let I=null;t.group||(I=new mr);const C=await e.getLanguageCode();this.output.addVideoTrack(s,{frameRate:t.frameRate,languageCode:Cs(C)?C:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:c,group:I??t.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(I)}async _registerVideoSample(e,t,n,i){if(this._canceled)return;this._reportProgress(t,i.timestamp+i.duration);let s;if(!e.process)s=[i];else{let a=e.process(i);a instanceof Promise&&(a=await a),Array.isArray(a)||(a=a===null?[]:[a]),s=a.map(o=>o instanceof gt?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new gt(o):new gt(o,{timestamp:i.timestamp,duration:i.duration}))}try{for(const a of s){if(this._canceled)break;await n.add(a),this._synchronizer.shouldWait(t,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}}finally{for(const a of s)a!==i&&a.close()}}async _processAudioTrack(e,t,n){const i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getNumberOfChannels(),o=await e.getSampleRate(),c=await e.getFirstTimestamp();let l=t.numberOfChannels??a,u=t.sampleRate??o,d=l!==a||u!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,f=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!d&&f.includes(i)&&(!t.codec||t.codec===i)&&!t.process&&t.sampleFormat===void 0){const m=new Yu(i);s=m,this._trackPromises.push((async()=>{await this._started;const A=new Yi(e),w={decoderConfig:await e.getDecoderConfig()??void 0};for await(const b of A.packets()){if(this._canceled)return;if(b.timestamp>=this._endTimestamp)break;const k=b.clone({timestamp:b.timestamp-this._startTimestamp});y(k.timestamp>=0),this._reportProgress(n,k.timestamp+k.duration),await m.add(k,w),this._synchronizer.shouldWait(n,k.timestamp)&&await this._synchronizer.wait(k.timestamp)}m.close(),this._synchronizer.closeTrack(n)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let A=null;t.codec&&(f=f.filter(b=>b===t.codec));const g=t.bitrate??Eu,w=await Co(f,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:l,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:u,bitrate:g});if(!w.some(b=>An.includes(b))&&f.some(b=>An.includes(b))&&(l!==id||u!==sd)){const k=(await Co(f,{numberOfChannels:id,sampleRate:sd,bitrate:g})).find(S=>An.includes(S));k&&(d=!0,A=k,l=id,u=sd)}else A=w[0]??null;if(A===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_co
525dec",trackOptions:t});return}if(d)s=this._resampleAudio(e,t,n,A,l,u,g);else{const b=new qu({codec:A,bitrate:g});s=b,this._trackPromises.push((async()=>{await this._started;const k=new vo(e);for await(const S of k.samples(void 0,this._endTimestamp)){if(this._canceled){S.close();return}S.setTimestamp(S.timestamp-this._startTimestamp),await this._registerAudioSample(t,n,b,S),S.close()}b.close(),this._synchronizer.closeTrack(n)})())}}let h=null;t.group||(h=new mr);const p=await e.getLanguageCode();this.output.addAudioTrack(s,{languageCode:Cs(p)?p:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:h??t.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(n),this._outputOwnTrackGroups.push(h)}async _registerAudioSample(e,t,n,i){if(this._canceled)return;let s=i;e.sampleFormat!==void 0&&SA(s.format)!==e.sampleFormat&&(s=CA(s,e.sampleFormat)),this._reportProgress(t,s.timestamp+s.duration);let a;if(!e.process)a=[s];else{let o=e.process(s);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(c=>c instanceof kt))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");a=o}try{for(const o of a){if(this._canceled)break;await n.add(o),this._synchronizer.shouldWait(t,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}}finally{s!==i&&s.close();for(const o of a)o!==i&&o.close()}}_resampleAudio(e,t,n,i,s,a,o){const c=new qu({codec:i,bitrate:o});return this._trackPromises.push((async()=>{await this._started;const l=new gw({targetNumberOfChannels:s,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async f=>{y(f.timestamp>=this._startTimestamp),f.setTimestamp(f.timestamp-this._startTimestamp),await this._registerAudioSample(t,n,c,f),f.close()}}),d=new vo(e).samples(this._startTimestamp,this._endTimestamp);for await(const f of d){if(this._canceled){f.close();return}await l.add(f),f.close()}await l.finalize(),c.close(),this._synchronizer.closeTrack(n)})()),c}_reportProgress(e,t){var s;if(!this._computeProgress)return;y(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));
525const n=Math.min(...this._maxTimestamps.values()),i=It(n/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,(s=this.onProgress)==null||s.call(this,i,n))}}class Tw extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const Sw=1;class i1{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const n=this.maxTimestamps.get(e);y(n!==void 0),this.maxTimestamps.set(e,Math.max(t,n));const i=this.computeMinAndMaybeResolve();return t-i>Sw}wait(e){const{promise:t,resolve:n}=rt();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const n=this.resolvers[t];n.timestamp-e<Sw&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}}/*!
526 * Copyright (c) 2026-present, Vanilagy and contributors
527 *
528 * This Source Code Form is subject to the terms of the Mozilla Public
529 * License, v. 2.0. If a copy of the MPL was not distributed with this
530 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
531 */const Cw=Symbol.for("mediabunny loaded");globalThis[Cw]&&console.error(`[WARNING]
532Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`),globalThis[Cw]=!0;var s1=Object.freeze({__proto__:null,ADTS:lu,ALL_FORMATS:lI,ALL_TRACK_TYPES:yw,AUDIO_CODECS:bt,AdtsInputFormat:cA,AdtsOutputFormat:e1,AppendOnlyStreamTarget:wx,AttachedFile:ja,AudioBufferSink:GI,AudioBufferSource:zx,AudioSample:kt,AudioSampleResource:Hi,AudioSampleSink:vo,AudioSampleSource:qu,AudioSource:es,BaseMediaSampleSink:Su,BlobSource:rI,BufferSource:tI,BufferTarget:Oo,CanvasSink:WI,CanvasSource:Qx,CmafOutputFormat:Zu,ConcurrentRunner:NS,Conversion:ad,ConversionCanceledError:Tw,CustomAudioDecoder:DA,CustomAudioEncoder:UA,CustomPathedSource:Vg,CustomSource:eu,CustomVideoDecoder:RA,CustomVideoEncoder:MA,EncodedAudioPacketSource:Yu,EncodedPacket:He,EncodedPacketSink:Yi,EncodedVideoPacketSource:Vu,EventEmitter:_s,FLAC:mA,FilePathSource:Zl,FilePathTarget:yx,FlacInputFormat:oA,FlacOutputFormat:t1,HLS:du,HLS_FORMATS:uI,HlsInputFormat:su,HlsOutputFormat:n1,Input:$s,InputAudioTrack:Xs,InputDisposedError:Gt,InputFormat:yr,InputTrack:Ki,InputVideoTrack:js,IsobmffInputFormat:nu,IsobmffOutputFormat:zo,MATROSKA:uA,MP3:cu,MP4:au,MPEG_TS:uu,MatroskaInputFormat:iu,MediaSource:No,MediaStreamAudioTrackSource:Wx,MediaStreamVideoTrackSource:Lx,MkvOutputFormat:td,MovOutputFormat:ed,Mp3InputFormat:iA,Mp3OutputFormat:Jx,Mp4InputFormat:tA,Mp4OutputFormat:$u,MpegTsInputFormat:lA,MpegTsOutputFormat:r1,NON_PCM_AUDIO_CODECS:An,NullTarget:zu,OGG:hA,OggInputFormat:aA,OggOutputFormat:Zx,Output:Wo,OutputAudioTrack:Ew,OutputFormat:nr,OutputSubtitleTrack:kw,OutputTrack:ts,OutputTrackGroup:mr,OutputVideoTrack:bw,PCM_AUDIO_CODECS:yt,PathedSource:Xn,PathedTarget:tn,QTFF:ou,QUALITY_HIGH:Eu,QUALITY_LOW:BI,QUALITY_MEDIUM:xI,QUALITY_VERY_HIGH:PI,QUALITY_VERY_LOW:II,Quality:Ht,QuickTimeInputFormat:rA,RangedSource:Yg,RangedTarget:sw,ReadableStreamSource:Gg,RichImageData:Wn,SUBTITLE_CODECS:gr,Source:tr,SourceRef:po,StreamSource:sI,StreamTarget:Lu,SubtitleSource:Ju,Target:Kt,TextSubtitleSource:Kx,UnsupportedInputFormatError:xu,UrlSource:$l,VIDEO_CODECS:dt,VIDEO_SAMPLE_PIXEL_FORMATS:Ao,VideoSample:gt,VideoSampleColorSpace:wo,VideoSampleResource:Cn,VideoSampleSink:Po,VideoSampleSource:Gu,VideoSource:Zi,WAVE:fA,WEBM:dA,WavOutputFormat:$x,WaveInputFormat:sA,WebMInputFormat:nA,WebMOutputFormat:rd,asc:YI,canDecode:mI,canDecodeAudio:pu,canDecodeVideo:mu,canEncode:vI,canEncodeAudio:To,canEncodeSubtitles:So,canEncodeVideo:ko,desc:Iu,getDecodableAudioCodecs:gA,getDecodableCodecs:pI,getDecodableVideoCodecs:pA,getEncodableAudioCodecs:Co,getEncodableCodecs:_I,getEncodableSubtitleCodecs:_A,getEncodableVideoCodecs:vA,getFirstEncodableAudioCodec:FI,getFirstEncodableSubtitleCodec:RI,getFirstEncodableVideoCodec:FA,prefer:qi,registerDecoder:DI,registerEncoder:MI,registerVideoSampleTransformer:yI});/*!
533 * ONNX Runtime Web v1.23.0
534 * Copyright (c) Microsoft Corporation. All rights reserved.
535 * Licensed under the MIT License.
536 */var od=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,o1=Object.getOwnPropertyNames,c1=Object.prototype.hasOwnProperty,l1=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),Oe=(r,e)=>()=>(r&&(e=r(r=0)),e),Go=(r,e)=>{for(var t in e)od(r,t,{get:e[t],enumerable:!0})},u1=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of o1(e))!c1.call(r,i)&&i!==t&&od(r,i,{get:()=>e[i],enumerable:!(n=a1(e,i))||n.enumerable});return r},cd=r=>u1(od({},"__esModule",{value:!0}),r),na,xn,ia,Iw,Bw,xw=Oe(()=>{na=new Map,xn=[],ia=(r,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let n=na.get(r);if(n===void 0)na.set(r,{backend:e,priority:t});else{if(n.priority>t)return;if(n.priority===t&&n.backend!==e)throw new Error(`cannot register backend "${r}" using priority ${t}`)}if(t>=0){let i=xn.indexOf(r);i!==-1&&xn.splice(i,1);for(let s=0;s<xn.length;s++)if(na.get(xn[s]).priority<=t){xn.splice(s,0,r);return}xn.push(r)}return}throw new TypeError("not a valid backend")},Iw=async r=>{let e=na.get(r);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(r)),await e.initPromise,e.initialized=!0,e.backend}catch(n){return t||(e.error=`${n}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Bw=async r=>{let e=r.executionProviders||[],t=e.map(c=>typeof c=="string"?c:c.name),n=t.length===0?xn:t,i,s=[],a=new Set;for(let c of n){let l=await Iw(c);typeof l=="string"?s.push({name:c,err:l}):(i||(i=l),i===l&&a.add(c))}if(!i)throw new Error(`no available backend found. ERR: ${s.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:l}of s)t.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${l}`);let o=e.filter(c=>a.has(typeof c=="string"?c:c.name));return[i,new Proxy(r,{get:(c,l)=>l==="executionProviders"?o:Reflect.get(c,l)})]}}),d1=Oe(()=>{xw()}),Pw,f1=Oe(()=>{Pw="1.23.0"}),ld,Pt,vw=Oe(()=>{f1(),ld="warning",Pt={wasm:{},webgl:{},webgpu:{},versions:{common:Pw},set logLevel(r){if(r!==void 0){if(typeof r!="string"||["verbose","info","warning","error","fatal"].indexOf(r)===-1)throw new Error(`Unsupported logging level: ${r}`);ld=r}},get logLevel(){return ld}},Object.defineProperty(Pt,"logLevel",{enumerable:!0})}),st,h1=Oe(()=>{vw(),st=Pt}),_w,Fw,m1=Oe(()=>{_w=(r,e)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=r.dims[3],t.height=r.dims[2];let n=t.getContext("2d");if(n!=null){let i,s;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(i=r.dims[2],s=r.dims[3]):(i=r.dims[3],s=r.dims[2]);let a=(e==null?void 0:e.format)!==void 0?e.format:"RGB",o=e==null?void 0:e.norm,c,l;o===void 0||o.mean===void 0?c=[255,255,255,255]:typeof o.mean=="number"?c=[o.mean,o.mean,o.mean,o.mean]:(c=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(c[3]=o.mean[3])),o===void 0||o.bias===void 0?l=[0,0,0,0]:typeof o.bias=="number"?l=[o.bias,o.bias,o.bias,o.bias]:(l=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(l[3]=o.bias[3]));let u=s*i,d=0,f=u,h=u*2,p=-1;a==="RGBA"?(d=0,f=u,h=u*2,p=u*3):a==="RGB"?(d=0,f=u,h=u*2):a==="RBG"&&(d=0,h=u,f=u*2);for(let m=0;m<s;m++)for(let A=0;A<i;A++){let g=(r.data[d++]-l[0])*c[0],w=(r.data[f++]-l[1])*c[1],b=(r.data[h++]-l[2])
vendor: 13,206 bytes, line 536
536*c[2],k=p===-1?255:(r.data[p++]-l[3])*c[3];n.fillStyle="rgba("+g+","+w+","+b+","+k+")",n.fillRect(A,m,1,1)}if("toDataURL"in t)return t.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Fw=(r,e)=>{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(t!=null){let i,s,a;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(i=r.dims[2],s=r.dims[1],a=r.dims[3]):(i=r.dims[3],s=r.dims[2],a=r.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",c=e==null?void 0:e.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean=="number"?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias=="number"?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=s*i;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,h=0,p=1,m=2,A=3,g=0,w=d,b=d*2,k=-1;o==="RGBA"?(g=0,w=d,b=d*2,k=d*3):o==="RGB"?(g=0,w=d,b=d*2):o==="RBG"&&(g=0,b=d,w=d*2),n=t.createImageData(i,s);for(let S=0;S<s*i;h+=f,p+=f,m+=f,A+=f,S++)n.data[h]=(r.data[g++]-u[0])*l[0],n.data[p]=(r.data[w++]-u[1])*l[1],n.data[m]=(r.data[b++]-u[2])*l[2],n.data[A]=k===-1?255:(r.data[k++]-u[3])*l[3]}else throw new Error("Can not access image data");return n}}),Yo,Rw,Dw,Mw,Uw,Ow,p1=Oe(()=>{dd(),Yo=(r,e)=>{if(r===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:n}=e,i=e.norm??{mean:255,bias:0},s,a;typeof i.mean=="number"?s=[i.mean,i.mean,i.mean,i.mean]:s=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",c=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",l=t*n,u=c==="RGBA"?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,h=1,p=2,m=3,A=0,g=l,w=l*2,b=-1;o==="RGB"&&(d=3,f=0,h=1,p=2,m=-1),c==="RGBA"?b=l*3:c==="RBG"?(A=0,w=l,g=l*2):c==="BGR"&&(w=0,g=l,A=l*2);for(let k=0;k<l;k++,f+=d,p+=d,h+=d,m+=d)u[A++]=(r[f]+a[0])/s[0],u[g++]=(r[h]+a[1])/s[1],u[w++]=(r[p]+a[2])/s[2],b!==-1&&m!==-1&&(u[b++]=(r[m]+a[3])/s[3]);return c==="RGBA"?new ir("float32",u,[1,4,t,n]):new ir("float32",u,[1,3,t,n])},Rw=async(r,e)=>{let t=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,n=typeof ImageData<"u"&&r instanceof ImageData,i=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,s=typeof r=="string",a,o=e??{},c=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(t){let u=c();u.width=r.width,u.height=r.height;let d=l(u);if(d!=null){let f=r.height,h=r.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(f=e.resizedHeight,h=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=f,o.width=h}else o.tensorFormat="RGBA",o.height=f,o.width=h;d.drawImage(r,0,0),a=d.getImageData(0,0,h,f).data}else throw new Error("Can not access image data")}else if(n){let u,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,d=e.resizedWidth):(u=r.height,d=r.width),e!==void 0&&(o=e),o.format="RGBA",o.height=u,o.width=d,e!==void 0){let f=c();f.width=d,f.height=u;let h=l(f);if(h!=null)h.putImageData(r,0,0),a=h.getImageData(0,0,d,u).data;else throw new Error("Can not access image data")}else a=r.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=c();u.width=r.width,u.height=r.height;let d=l(u);if(d!=null){let f=r.height,h=r.width;return d.drawImage(r,0,0,h,f),a=d.getImageData(0,0,h,f).data,o.height=f,o.width=h,Yo(a,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((u,d)=>{let f=c(),h=l(f);if(!r||!h)return d();let p=new Image;p.crossOrigin="Anonymous",p.src=r,p.onload=()=>{f.width=p.width,f.height=p.height,h.drawImage(p,0,0,f.width,f.height);let m=h.getImageData(0,0,f.width,f.height);o.height=f.height,o.width=f.width,u(Yo(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Yo(a,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Dw=(r,e)=>{let{width:t,height:n,download:i,dispose:s}=e,a=[1,n,t,4];return new ir({location:"texture",type:"float32",texture:r,dims:a,download:i,dispose:s})},Mw=(r,e)=>{let{dataType:t,dims:n,download:i,dispose:s}=e;return new ir({location:"gpu-buffer",type:t??"float32",gpuBuffer:r,dims:n,download:i,dispose:s})},Uw=(r,e)=>{let{dataType:t,dims:n,download:i,dispose:s}=e;return new ir({location:"ml-tensor",type:t??"float32",mlTensor:r,dims:n,download:i,dispose:s})},Ow=(r,e,t)=>new ir({location:"cpu-pinned",type:r,data:e,dims:t??[e.length]})}),ni,sa,ud,Nw,g1=Oe(()=>{ni=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),sa=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ud=!1,Nw=()=>{if(!ud){ud=!0;let r=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,n=typeof t<"u"&&t.from;r&&(ni.set("int64",BigInt64Array),sa.set(BigInt64Array,"int64")),e&&(ni.set("uint64",BigUint64Array),sa.set(BigUint64Array,"uint64")),n?(ni.set("float16",t),sa.set(t,"float16")):ni.set("float16",Uint16Array)}}}),Qw,Lw,A1=Oe(()=>{dd(),Qw=r=>{let e=1;for(let t=0;t<r.length;t++){let n=r[t];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${t}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${t}] must be a non-negative integer, got: ${n}`);e*=n}return e},Lw=(r,e)=>{switch(r.location){case"cpu":return new ir(r.type,r.data,e);case"cpu-pinned":return new ir({location:"cpu-pinned",data:r.data,type:r.type,dims:e});case"texture":return new ir({location:"texture",texture:r.texture,type:r.type,dims:e});case"gpu-buffer":return new ir({location:"gpu-buffer",gpuBuffer:r.gpuBuffer,type:r.type,dims:e});case"ml-tensor":return new ir({location:"ml-tensor",mlTensor:r.mlTensor,type:r.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${r.location} is not supported`)}}}),ir,dd=Oe(()=>{m1(),p1(),g1(),A1(),ir=class{constructor(r,e,t){Nw();let n,i;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,n=r.type,i=r.dims,r.location){case"cpu-pinned":{let a=ni.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof r=="string")if(n=r,o=t,r==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let c=ni.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(e)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(e,BigInt):a=c.from(e)}else if(e instanceof c)a=e;else if(e instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&e instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(o=e,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof r[0];if(c==="string")n="string",a=r;else if(c==="boolean")n="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(r);else{let c=sa.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,a=r}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");i=o,this.cpuData=a,this.dataLocation="cpu"}let s=Qw(i);if(this.cpuData&&s!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=s}static async fromImage(r,e){return Rw(r,e)}static fromTexture(r,e){return Dw(r,e)}static fromGpuBuffer(r,e){return Mw(r,e)}static fromMLTensor(r,e){return Uw(r,e)}static fromPinnedBuffer(r,e,t){return Ow(r,e,t)}toDataURL(r){return _w(this,r)}toImageData(r){return Fw(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,r&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Lw(this,r)}}}),Sr,zw=Oe(()=>{dd(),Sr=ir}),Ko,fd,ii,si,ai,oi,Ww=Oe(()=>{vw(),Ko=(r,e)=>{(typeof Pt.trace>"u"?!Pt.wasm.trace:!Pt.trace)||console.timeStamp(`${r}::ORT::${e}`)},fd=(r,e)=>{var i;let t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let s=0;s<t.length;s++){if(n&&!t[s].includes("TRACE_FUNC")){let a=`FUNC_${r}::${t[s].trim().split(" ")[1]}`;e&&(a+=`::${e}`),Ko("CPU",a);return}t[s].includes("TRACE_FUNC")&&(n=!0)}},ii=r=>{(typeof Pt.trace>"u"?!Pt.wasm.trace:!Pt.trace)||fd("BEGIN",r)},si=r=>{(typeof Pt.trace>"u"?!Pt.wasm.trace:!Pt.trace)||fd("END",r)},ai=r=>{(typeof Pt.trace>"u"?!Pt.wasm.trace:!Pt.trace)||console.time(`ORT::${r}`)},oi=r=>{(typeof Pt.trace>"u"?!Pt.wasm.trace:!Pt.trace)||console.timeEnd(`ORT::${r}`)}}),Vw,w1=Oe(()=>{xw(),zw(),Ww(),Vw=class k0{constructor(e){this.handler=e}
536async run(e,t,n){ii(),ai("InferenceSession.run");let i={},s={};if(typeof e!="object"||e===null||e instanceof Sr||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Sr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let l of t){if(typeof l!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(l)===-1)throw new RangeError(`'fetches' contains invalid output name: ${l}.`);i[l]=null}if(typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let l=!1,u=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(u.indexOf(d)!==-1){let f=t[d];(f===null||f instanceof Sr)&&(l=!0,a=!1,i[d]=f)}if(l){if(typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else s=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let l of this.inputNames)if(typeof e[l]>"u")throw new Error(`input '${l}' is missing in 'feeds'.`);if(a)for(let l of this.outputNames)i[l]=null;let o=await this.handler.run(e,i,s),c={};for(let l in o)if(Object.hasOwnProperty.call(o,l)){let u=o[l];u instanceof Sr?c[l]=u:c[l]=new Sr(u.type,u.data,u.dims)}return oi("InferenceSession.run"),si(),c}async release(){return this.handler.dispose()}static async create(e,t,n,i){ii(),ai("InferenceSession.create");let s,a={};if(typeof e=="string"){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,d=0,f=e.byteLength;if(typeof t=="object"&&t!==null)a=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(f=e.byteLength-d,typeof n=="number"){if(f=n,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||d+f>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-d}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(u,d,f)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,c]=await Bw(a),l=await o.createInferenceSessionHandler(s,c);return oi("InferenceSession.create"),si(),new k0(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),hd,y1=Oe(()=>{w1(),hd=Vw}),b1=Oe(()=>{}),E1=Oe(()=>{}),k1=Oe(()=>{}),T1=Oe(()=>{}),Hw={};Go(Hw,{InferenceSession:()=>hd,TRACE:()=>Ko,TRACE_EVENT_BEGIN:()=>ai,TRACE_EVENT_END:()=>oi,TRACE_FUNC_BEGIN:()=>ii,TRACE_FUNC_END:()=>si,Tensor:()=>Sr,env:()=>st,registerBackend:()=>ia});var ci=Oe(()=>{d1(),h1(),y1(),zw(),b1(),E1(),Ww(),k1(),T1()}),md=Oe(()=>{}),Gw={};Go(Gw,{default:()=>Yw});var pd,gd,Yw,S1=Oe(()=>{var r;yy(),rs(),Td(),pd="ort-wasm-proxy-worker",gd=((r=globalThis.self)==null?void 0:r.name)===pd,gd&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Id(n.wasm).then(()=>{_d(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:s}=n;Fd(s,i).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:i}=n,s=$o(i);postMessage({type:t,out:s});break}case"create":{let{model:i,options:s}=n;Dd(i,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":Md(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:s,inputs:a,outputIndices:o,options:c}=n;Od(i,s,a,o,new Array(o.length).fill(null),c).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},Qd([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":Nd(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),Yw=gd?null:e=>new Worker(e??sr,{type:"module",name:pd})}),Kw={};Go(Kw,{default:()=>qw});var Ad,qw,jw,C1=Oe(()=>{var r,e;Ad=async function(t={}){var y0;var n,i,s=t,a=new Promise((E,P)=>{n=E,i=P}),o=typeof window=="object",c=typeof WorkerGlobalScope<"u",l=c&&((y0=self.name)==null?void 0:y0.startsWith("em-pthread"));s.mountExternalData=(E,P)=>{E.startsWith("./")&&(E=E.substring(2)),(s.Sa||(s.Sa=new Map)).set(E,P)},s.unmountExternalData=()=>{delete s.Sa};var u,d,f=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,kb:!0}).buffer.constructor,h=(E,P)=>{throw P},p=self.location.href,m="";if(o||c){try{m=new URL(".",p).href}catch{}c&&(d=E=>{var P=new XMLHttpRequest;return P.open("GET",E,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),u=async E=>{if(ce(E))return new Promise((D,Q)=>{var L=new XMLHttpRequest;L.open("GET",E,!0),L.responseType="arraybuffer",L.onload=()=>{L.status==200||L.status==0&&L.response?D(L.response):Q(L.status)},L.onerror=Q,L.send(null)});var P=await fetch(E,{credentials:"same-origin"});if(P.ok)return P.arrayBuffer();throw Error(P.status+" : "+P.url)}}var A,g,w,b,k,S,x,B,I,C,v,R,M,z=console.log.bind(console),W=console.error.bind(console),H=z,U=W,j=!1,ce=E=>E.startsWith("file://");function ee(){return g.buffer!=k.buffer&&xe(),k}function fe(){return g.buffer!=k.buffer&&xe(),S}function he(){return g.buffer!=k.buffer&&xe(),x}function G(){return g.buffer!=k.buffer&&xe(),B}function ue(){return g.buffer!=k.buffer&&xe(),I}function we(){return g.buffer!=k.buffer&&xe(),C}function _e(){return g.buffer!=k.buffer&&xe(),R}if(l){let E=function(P){try{var D=P.data,Q=D.Ra;if(Q==="load"){let L=[];self.onmessage=$=>L.push($),self.startWorker=()=>{postMessage({Ra:"loaded"});for(let $ of L)E($);self.onmessage=E};for(let $ of D.Za)s[$]&&!s[$].proxy||(s[$]=(...ge)=>{postMessage({Ra:"callHandler",Ya:$,args:ge})},$=="print"&&(H=s[$]),$=="printErr"&&(U=s[$]));g=D.fb,xe(),M(D.gb)}else if(Q==="run"){ua(D.Qa),$d(D.Qa,0,0,1,0,0),ht(),Yd(D.Qa),Ye||(Ye=!0);try{Hd(D.bb,D.Va)}catch(L){if(L!="unwind")throw L}}else D.target!=="setimmediate"&&(Q==="checkMailbox"?Ye&&ic():Q&&(U(`worker: received unknown command ${Q}`),U(D)))}catch(L){throw h0(),L}};var Ye=!1;self.onunhandledrejection=P=>{throw P.reason||P},self.onmessage=E}function xe(){var E=g.buffer;s.HEAP8=k=new Int8Array(E),x=new Int16Array(E),s.HEAPU8=S=new Uint8Array(E),s.HEAP32=B=new Int32Array(E),s.HEAPU32=I=new Uint32Array(E),C=new Float32Array(E),R=new Float64Array(E),v=new BigInt64Array(E),new BigUint64Array(E)}function ne(){l?startWorker(s):ye.$()}var Pe,Ee=0,me=null;function Fe(){if(--Ee==0&&me){var E=me;me=null,E()}}function Qe(E){throw U(E="Aborted("+E+")"),j=!0,E=new WebAssembly.RuntimeError(E+". Build with -sASSERTIONS for more info."),i(E),E}function ze(){return{a:{j:aP,b:R1,E:Dy,f:Oy,U:Ny,A:Qy,C:Ly,V:zy,S:Wy,L:Vy,R:Hy,n:Gy,B:Yy,y:Ky,T:qy,z:jy,_:D1,O:M1,w:U1,F:O1,t:N1,i:Q1,N:Yd,X:L1,I:z1,J:W1,K:V1,G:e0,H:t0,u:r0,q:G1,Z:K1,o:q1,k:j1,Y:Y1,d:X1,W:J1,x:$1,c:H1,e:Z1,h:eP,v:tP,s:rP,r:nP,P:s0,Q:o0,D:oe,g:c0,m:l0,M:u0,l:d0,a:g,p:X}}}class T{constructor(P){Lt(this,"name","ExitStatus");this.message=`Program terminated with exit(${P})`,this.status=P}}var V=E=>{E.terminate(),E.onmessage=()=>{}},F=[],O=E=>{ie.length==0&&(vt(),at(ie[0]));var P=ie.pop();if(!P)return 6;ke.push(P),te[E.Qa]=P,P.Qa=E.Qa;var D={Ra:"run",bb:E.ab,Va:E.Va,Qa:E.Qa};return P.postMessage(D,E.Xa),0},K=0,N=(E,P,...D)=>{for(var Q=2*D.length,L=tf(),$=ef(8*Q),ge=$>>>3,lt=0;lt<D.length;lt++){var _t=D[lt];typeof _t=="bigint"?(v[ge+2*lt]=1n,v[ge+2*lt+1]=_t):(v[ge+2*lt]=0n,_e()[ge+2*lt+1>>>0]=_t)}return E=m0(E,0,Q,$,P),ac(L),E};function X(E){if(l)return N(0,1,E);if(b=E,!(0<K)){for(var P of ke)V(P);for(P of ie)V(P);ie=[],ke=[],te={},j=!0}h(0,new T(E))}function re(E){if(l)return N(1,0,E);oe(E)}var oe=E=>{if(b=E,l)throw re(E),"unwind";X(E)},ie=[],ke=[],Ne=[],te={},be=E=>{var P=E.Qa;
536delete te[P],ie.push(E),ke.splice(ke.indexOf(E),1),E.Qa=0,p0(P)};function ht(){Ne.forEach(E=>E())}var at=E=>new Promise(P=>{E.onmessage=L=>{var $=(L=L.data).Ra;if(L.Ta&&L.Ta!=Jd()){var ge=te[L.Ta];ge?ge.postMessage(L,L.Xa):U(`Internal error! Worker sent a message "${$}" to target pthread ${L.Ta}, but that thread no longer exists!`)}else $==="checkMailbox"?ic():$==="spawnThread"?O(L):$==="cleanupThread"?be(te[L.cb]):$==="loaded"?(E.loaded=!0,P(E)):L.target==="setimmediate"?E.postMessage(L):$==="callHandler"?s[L.Ya](...L.args):$&&U(`worker sent an unknown command ${$}`)},E.onerror=L=>{throw U(`worker sent an error! ${L.filename}:${L.lineno}: ${L.message}`),L};var D,Q=[];for(D of[])s.propertyIsEnumerable(D)&&Q.push(D);E.postMessage({Ra:"load",Za:Q,fb:g,gb:w})});function vt(){var E=new Worker((()=>{let P=URL;return self.location.href>"file:"&&self.location.href<"file;"?new P("ort.wasm.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ie.push(E)}var _n,ua=E=>{xe();var P=ue()[E+52>>>2>>>0];E=ue()[E+56>>>2>>>0],w0(P,P-E),ac(P)},nc=[],Hd=(E,P)=>{K=0;var D=nc[E];D||(nc[E]=D=_n.get(E)),E=D(P),0<K?b=E:Zd(E)};class nn{constructor(P){this.Ua=P-24}}function R1(E,P,D){var Q=new nn(E>>>=0);throw P>>>=0,D>>>=0,ue()[Q.Ua+16>>>2>>>0]=0,ue()[Q.Ua+4>>>2>>>0]=P,ue()[Q.Ua+8>>>2>>>0]=D,E}function Ry(E,P,D,Q){return l?N(2,1,E,P,D,Q):Dy(E,P,D,Q)}function Dy(E,P,D,Q){if(E>>>=0,D>>>=0,Q>>>=0,f===void 0)return 6;var L=[];return l&&L.length===0?Ry(E,P>>>=0,D,Q):(E={ab:D,Qa:E,Va:Q,Xa:L},l?(E.Ra="spawnThread",postMessage(E,L),0):O(E))}var My=typeof TextDecoder<"u"?new TextDecoder:void 0,Uy=(E,P=0,D=NaN)=>{var Q=(P>>>=0)+D;for(D=P;E[D]&&!(D>=Q);)++D;if(16<D-P&&E.buffer&&My)return My.decode(E.buffer instanceof ArrayBuffer?E.subarray(P,D):E.slice(P,D));for(Q="";P<D;){var L=E[P++];if(128&L){var $=63&E[P++];if((224&L)==192)Q+=String.fromCharCode((31&L)<<6|$);else{var ge=63&E[P++];65536>(L=(240&L)==224?(15&L)<<12|$<<6|ge:(7&L)<<18|$<<12|ge<<6|63&E[P++])?Q+=String.fromCharCode(L):(L-=65536,Q+=String.fromCharCode(55296|L>>10,56320|1023&L))}}else Q+=String.fromCharCode(L)}return Q},Gd=(E,P)=>(E>>>=0)?Uy(fe(),E,P):"";function Oy(E,P,D){return l?N(3,1,E,P,D):0}function Ny(E,P){if(l)return N(4,1,E,P)}function Qy(E,P){if(l)return N(5,1,E,P)}function Ly(E,P,D){if(l)return N(6,1,E,P,D)}function zy(E,P,D){return l?N(7,1,E,P,D):0}function Wy(E,P){if(l)return N(8,1,E,P)}function Vy(E,P,D){if(l)return N(9,1,E,P,D)}function Hy(E,P,D,Q){if(l)return N(10,1,E,P,D,Q)}function Gy(E,P,D,Q){if(l)return N(11,1,E,P,D,Q)}function Yy(E,P,D,Q){if(l)return N(12,1,E,P,D,Q)}function Ky(E){if(l)return N(13,1,E)}function qy(E,P){if(l)return N(14,1,E,P)}function jy(E,P,D){if(l)return N(15,1,E,P,D)}var D1=()=>Qe("");function M1(E){$d(E>>>0,!c,1,!o,131072,!1),ht()}var Xy=E=>{if(!j)try{if(E(),!(0<K))try{l?Zd(b):oe(b)}catch(P){P instanceof T||P=="unwind"||h(0,P)}}catch(P){P instanceof T||P=="unwind"||h(0,P)}};function Yd(E){E>>>=0,typeof Atomics.eb=="function"&&(Atomics.eb(G(),E>>>2,E).value.then(ic),E+=128,Atomics.store(G(),E>>>2,1))}var ic=()=>{var E=Jd();E&&(Yd(E),Xy(A0))};function U1(E,P){(E>>>=0)==P>>>0?setTimeout(ic):l?postMessage({Ta:E,Ra:"checkMailbox"}):(E=te[E])&&E.postMessage({Ra:"checkMailbox"})}var Kd=[];function O1(E,P,D,Q,L){for(P>>>=0,Q/=2,Kd.length=Q,D=L>>>0>>>3,L=0;L<Q;L++)Kd[L]=v[D+2*L]?v[D+2*L+1]:_e()[D+2*L+1>>>0];return(P?f0[P]:sP[E])(...Kd)}var N1=()=>{K=0};function Q1(E){E>>>=0,l?postMessage({Ra:"cleanupThread",cb:E}):be(te[E])}function L1(E){}function z1(E,P){E=-9007199254740992>E||9007199254740992<E?NaN:Number(E),P>>>=0,E=new Date(1e3*E),G()[P>>>2>>>0]=E.getUTCSeconds(),G()[P+4>>>2>>>0]=E.getUTCMinutes(),G()[P+8>>>2>>>0]=E.getUTCHours(),G()[P+12>>>2>>>0]=E.getUTCDate(),G()[P+16>>>2>>>0]=E.getUTCMonth(),G()[P+20>>>2>>>0]=E.getUTCFullYear()-1900,G()[P+24>>>2>>>0]=E.getUTCDay(),E=(E.getTime()-Date.UTC(E.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,G()[P+28>>>2>>>0]=E}var Jy=E=>E%4==0&&(E%100!=0||E%400==0),$y=[0,31,60,91,121,152,182,213,244,274,305,335],Zy=[0,31,59,90,120,151,181,212,243,273,304,334];function W1(E,P){E=-9007199254740992>E||9007199254740992<E?NaN:Number(E),P>>>=0,E=new Date(1e3*E),G()[P>>>2>>>0]=E.getSeconds(),G()[P+4>>>2>>>0]=E.getMinutes(),G()[P+8>>>2>>>0]=E.getHours(),G()[P+12>>>2>>>0]=E.getDate(),G()[P+16>>>2>>>0]=E.getMonth(),G()[P+20>>>2>>>0]=E.getFullYear()-1900,G()[P+24>>>2>>>0]=E.getDay();var D=(Jy(E.getFullYear())?$y:Zy)[E.getMonth()]+E.getDate()-1|0;G()[P+28>>>2>>>0]=D,G()[P+36>>>2>>>0]=-60*E.getTimezoneOffset(),D=new Date(E.getFullYear(),6,1).getTimezoneOffset();var Q=new Date(E.getFullYear(),0,1).getTimezoneOffset();E=0|(D!=Q&&E.getTimezoneOffset()==Math.min(Q,D)),G()[P+32>>>2>>>0]=E}function V1(E){E>>>=0;var P=new Date(G()[E+20>>>2>>>0]+1900,G()[E+16>>>2>>>0],G()[E+12>>>2>>>0],G()[E+8>>>2>>>0],G()[E+4>>>2>>>0],G()[E>>>2>>>0],0),D=G()[E+32>>>2>>>0],Q=P.getTimezoneOffset(),L=new Date(P.getFullYear(),6,1).getTimezoneOffset(),$=new Date(P.getFullYear(),0,1).getTimezoneOffset(),ge=Math.min($,L);return 0>D?G()[E+32>>>2>>>0]=+(L!=$&&ge==Q):0<D!=(ge==Q)&&(L=Math.max($,L),P.setTime(P.getTime()+6e4*((0<D?ge:L)-Q))),G()[E+24>>>2>>>0]=P.getDay(),D=(Jy(P.getFullYear())?$y:Zy)[P.getMonth()]+P.getDate()-1|0,G()[E+28>>>2>>>0]=D,G()[E>>>2>>>0]=P.getSeconds(),G()[E+4>>>2>>>0]=P.getMinutes(),G()[E+8>>>2>>>0]=P.getHours(),G()[E+12>>>2>>>0]=P.getDate(),G()[E+16>>>2>>>0]=P.getMonth(),G()[E+20>>>2>>>0]=P.getYear(),E=P.getTime(),BigInt(isNaN(E)?-1:E/1e3)}function e0(E,P,D,Q,L,$,ge){return l?N(16,1,E,P,D,Q,L,$,ge):-52}function t0(E,P,D,Q,L,$){if(l)return N(17,1,E,P,D,Q,L,$)}var da={},H1=()=>performance.timeOrigin+performance.now();function r0(E,P){if(l)return N(18,1,E,P);if(da[E]&&(clearTimeout(da[E].id),delete da[E]),!P)return 0;var D=setTimeout(()=>{delete da[E],Xy(()=>g0(E,performance.timeOrigin+performance.now()))},P);return da[E]={id:D,lb:P},0}var as=(E,P,D)=>{var Q=fe();if(P>>>=0,0<D){var L=P;D=P+D-1;for(var $=0;$<E.length;++$){var ge=E.charCodeAt($);if(55296<=ge&&57343>
536=ge&&(ge=65536+((1023&ge)<<10)|1023&E.charCodeAt(++$)),127>=ge){if(P>=D)break;Q[P++>>>0]=ge}else{if(2047>=ge){if(P+1>=D)break;Q[P++>>>0]=192|ge>>6}else{if(65535>=ge){if(P+2>=D)break;Q[P++>>>0]=224|ge>>12}else{if(P+3>=D)break;Q[P++>>>0]=240|ge>>18,Q[P++>>>0]=128|ge>>12&63}Q[P++>>>0]=128|ge>>6&63}Q[P++>>>0]=128|63&ge}}Q[P>>>0]=0,E=P-L}else E=0;return E};function G1(E,P,D,Q){E>>>=0,P>>>=0,D>>>=0,Q>>>=0;var L=new Date().getFullYear(),$=new Date(L,0,1).getTimezoneOffset();L=new Date(L,6,1).getTimezoneOffset();var ge=Math.max($,L);ue()[E>>>2>>>0]=60*ge,G()[P>>>2>>>0]=+($!=L),E=(P=lt=>{var _t=Math.abs(lt);return`UTC${0<=lt?"-":"+"}${String(Math.floor(_t/60)).padStart(2,"0")}${String(_t%60).padStart(2,"0")}`})($),P=P(L),L<$?(as(E,D,17),as(P,Q,17)):(as(E,Q,17),as(P,D,17))}var Y1=()=>Date.now();function K1(E,P,D){return 0<=E&&3>=E?(E===0?E=Date.now():E=performance.timeOrigin+performance.now(),v[D>>>0>>>3]=BigInt(Math.round(1e6*E)),0):28}var qd=[];function q1(E,P,D){E>>>=0,P>>>=0,D>>>=0,qd.length=0;for(var Q;Q=fe()[P++>>>0];){var L=Q!=105;D+=(L&=Q!=112)&&D%8?4:0,qd.push(Q==112?ue()[D>>>2>>>0]:Q==106?v[D>>>3]:Q==105?G()[D>>>2>>>0]:_e()[D>>>3>>>0]),D+=L?8:4}return f0[E](...qd)}var j1=()=>{};function X1(E,P){return U(Gd(E>>>0,P>>>0))}var J1=()=>{throw K+=1,"unwind"};function $1(){return 4294901760}var Z1=()=>navigator.hardwareConcurrency;function eP(){return Qe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function tP(E){E>>>=0;var P=fe().length;if(E<=P||4294901760<E)return!1;for(var D=1;4>=D;D*=2){var Q=P*(1+.2/D);Q=Math.min(Q,E+100663296);e:{Q=(Math.min(4294901760,65536*Math.ceil(Math.max(E,Q)/65536))-g.buffer.byteLength+65535)/65536|0;try{g.grow(Q),xe();var L=1;break e}catch{}L=void 0}if(L)return!0}return!1}var sc=()=>(Qe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),fa={},n0=E=>{E.forEach(P=>{sc()})};function rP(){var E=Error().stack.toString().split(`
537`);return E[0]=="Error"&&E.shift(),n0(E),fa.Wa=sc(),fa.$a=E,fa.Wa}function nP(E,P,D){if(E>>>=0,P>>>=0,fa.Wa==E)var Q=fa.$a;else(Q=Error().stack.toString().split(`
538`))[0]=="Error"&&Q.shift(),n0(Q);for(var L=3;Q[L]&&sc()!=E;)++L;for(E=0;E<D&&Q[E+L];++E)G()[P+4*E>>>2>>>0]=sc();return E}var jd,Xd={},i0=()=>{if(!jd){var E,P={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(E in Xd)Xd[E]===void 0?delete P[E]:P[E]=Xd[E];var D=[];for(E in P)D.push(`${E}=${P[E]}`);jd=D}return jd};function s0(E,P){if(l)return N(19,1,E,P);E>>>=0,P>>>=0;var D,Q=0,L=0;for(D of i0()){var $=P+Q;ue()[E+L>>>2>>>0]=$,Q+=as(D,$,1/0)+1,L+=4}return 0}var a0=E=>{for(var P=0,D=0;D<E.length;++D){var Q=E.charCodeAt(D);127>=Q?P++:2047>=Q?P+=2:55296<=Q&&57343>=Q?(P+=4,++D):P+=3}return P};function o0(E,P){if(l)return N(20,1,E,P);E>>>=0,P>>>=0;var D=i0();for(var Q of(ue()[E>>>2>>>0]=D.length,E=0,D))E+=a0(Q)+1;return ue()[P>>>2>>>0]=E,0}function c0(E){return l?N(21,1,E):52}function l0(E,P,D,Q){return l?N(22,1,E,P,D,Q):52}function u0(E,P,D,Q){return l?N(23,1,E,P,D,Q):70}var iP=[null,[],[]];function d0(E,P,D,Q){if(l)return N(24,1,E,P,D,Q);P>>>=0,D>>>=0,Q>>>=0;for(var L=0,$=0;$<D;$++){var ge=ue()[P>>>2>>>0],lt=ue()[P+4>>>2>>>0];P+=8;for(var _t=0;_t<lt;_t++){var Qt=E,ha=fe()[ge+_t>>>0],rf=iP[Qt];ha===0||ha===10?((Qt===1?H:U)(Uy(rf)),rf.length=0):rf.push(ha)}L+=lt}return ue()[Q>>>2>>>0]=L,0}l||(function(){for(var E=s.numThreads-1;E--;)vt();F.push(()=>{Ee++,(function(P){l?P():Promise.all(ie.map(at)).then(P)})(()=>Fe())})})(),l||(g=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xe()),s.wasmBinary&&(A=s.wasmBinary),s.stackSave=()=>tf(),s.stackRestore=E=>ac(E),s.stackAlloc=E=>ef(E),s.setValue=function(E,P,D="i8"){switch(D.endsWith("*")&&(D="*"),D){case"i1":case"i8":ee()[E>>>0]=P;break;case"i16":he()[E>>>1>>>0]=P;break;case"i32":G()[E>>>2>>>0]=P;break;case"i64":v[E>>>3]=BigInt(P);break;case"float":we()[E>>>2>>>0]=P;break;case"double":_e()[E>>>3>>>0]=P;break;case"*":ue()[E>>>2>>>0]=P;break;default:Qe(`invalid type for setValue: ${D}`)}},s.getValue=function(E,P="i8"){switch(P.endsWith("*")&&(P="*"),P){case"i1":case"i8":return ee()[E>>>0];case"i16":return he()[E>>>1>>>0];case"i32":return G()[E>>>2>>>0];case"i64":return v[E>>>3];case"float":return we()[E>>>2>>>0];case"double":return _e()[E>>>3>>>0];case"*":return ue()[E>>>2>>>0];default:Qe(`invalid type for getValue: ${P}`)}},s.UTF8ToString=Gd,s.stringToUTF8=as,s.lengthBytesUTF8=a0;var sP=[X,re,Ry,Oy,Ny,Qy,Ly,zy,Wy,Vy,Hy,Gy,Yy,Ky,qy,jy,e0,t0,r0,s0,o0,c0,l0,u0,d0],f0={851916:(E,P,D,Q,L)=>{if(s===void 0||!s.Sa)return 1;if((E=Gd(Number(E>>>0))).startsWith("./")&&(E=E.substring(2)),!(E=s.Sa.get(E)))return 2;if(P=Number(P>>>0),D=Number(D>>>0),Q=Number(Q>>>0),P+D>E.byteLength)return 3;try{let $=E.subarray(P,P+D);switch(L){case 0:fe().set($,Q>>>0);break;case 1:s.hb?s.hb(Q,$):s.jb(Q,$);break;default:return 4}return 0}catch{return 4}},852740:()=>typeof wasmOffsetConverter<"u"};function aP(){return typeof wasmOffsetConverter<"u"}var ye=await(async function(){function E(Q,L){return ye=Q.exports,ye=(function(){var $=ye,ge=_t=>()=>_t()>>>0,lt=_t=>Qt=>_t(Qt)>>>0;return($=Object.assign({},$)).Aa=ge($.Aa),$.Ca=lt($.Ca),$.Oa=lt($.Oa),$.Pa=ge($.Pa),$.__cxa_get_exception_ptr=lt($.__cxa_get_exception_ptr),$})(),Ne.push(ye.Da),_n=ye.Ea,w=L,Fe(),ye}Ee++;var P=ze();if(s.instantiateWasm)return new Promise(Q=>{s.instantiateWasm(P,(L,$)=>{Q(E(L,$))})});if(l)return new Promise(Q=>{M=L=>{var $=new WebAssembly.Instance(L,ze());Q(E($,L))}});Pe??(Pe=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.wasm",m):m+"ort-wasm-simd-threaded.wasm":new 
538URL("/build/assets/ort-wasm-simd-threaded-CpHjICJN.wasm",self.location.href).href);try{var D=await(async function(Q){var L=Pe;if(!A&&typeof WebAssembly.instantiateStreaming=="function"&&!ce(L))try{var $=fetch(L,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming($,Q)}catch(ge){U(`wasm streaming compile failed: ${ge}`),U("falling back to ArrayBuffer instantiation")}return(async function(ge,lt){try{var _t=await(async function(Qt){if(!A)try{var ha=await u(Qt);return new Uint8Array(ha)}catch{}if(Qt==Pe&&A)Qt=new Uint8Array(A);else{if(!d)throw"both async and sync fetching of the wasm failed";Qt=d(Qt)}return Qt})(ge);return await WebAssembly.instantiate(_t,lt)}catch(Qt){U(`failed to asynchronously prepare wasm: ${Qt}`),Qe(Qt)}})(L,Q)})(P);return E(D.instance,D.module)}catch(Q){return i(Q),Promise.reject(Q)}})();s._OrtInit=(E,P)=>(s._OrtInit=ye.aa)(E,P),s._OrtGetLastError=(E,P)=>(s._OrtGetLastError=ye.ba)(E,P),s._OrtCreateSessionOptions=(E,P,D,Q,L,$,ge,lt,_t,Qt)=>(s._OrtCreateSessionOptions=ye.ca)(E,P,D,Q,L,$,ge,lt,_t,Qt),s._OrtAppendExecutionProvider=(E,P,D,Q,L)=>(s._OrtAppendExecutionProvider=ye.da)(E,P,D,Q,L),s._OrtAddFreeDimensionOverride=(E,P,D)=>(s._OrtAddFreeDimensionOverride=ye.ea)(E,P,D),s._OrtAddSessionConfigEntry=(E,P,D)=>(s._OrtAddSessionConfigEntry=ye.fa)(E,P,D),s._OrtReleaseSessionOptions=E=>(s._OrtReleaseSessionOptions=ye.ga)(E),s._OrtCreateSession=(E,P,D)=>(s._OrtCreateSession=ye.ha)(E,P,D),s._OrtReleaseSession=E=>(s._OrtReleaseSession=ye.ia)(E),s._OrtGetInputOutputCount=(E,P,D)=>(s._OrtGetInputOutputCount=ye.ja)(E,P,D),s._OrtGetInputOutputMetadata=(E,P,D,Q)=>(s._OrtGetInputOutputMetadata=ye.ka)(E,P,D,Q),s._OrtFree=E=>(s._OrtFree=ye.la)(E),s._OrtCreateTensor=(E,P,D,Q,L,$)=>(s._OrtCreateTensor=ye.ma)(E,P,D,Q,L,$),s._OrtGetTensorData=(E,P,D,Q,L)=>(s._OrtGetTensorData=ye.na)(E,P,D,Q,L),s._OrtReleaseTensor=E=>(s._OrtReleaseTensor=ye.oa)(E),s._OrtCreateRunOptions=(E,P,D,Q)=>(s._OrtCreateRunOptions=ye.pa)(E,P,D,Q),s._OrtAddRunConfigEntry=(E,P,D)=>(s._OrtAddRunConfigEntry=ye.qa)(E,P,D),s._OrtReleaseRunOptions=E=>(s._OrtReleaseRunOptions=ye.ra)(E),s._OrtCreateBinding=E=>(s._OrtCreateBinding=ye.sa)(E),s._OrtBindInput=(E,P,D)=>(s._OrtBindInput=ye.ta)(E,P,D),s._OrtBindOutput=(E,P,D,Q)=>(s._OrtBindOutput=ye.ua)(E,P,D,Q),s._OrtClearBoundOutputs=E=>(s._OrtClearBoundOutputs=ye.va)(E),s._OrtReleaseBinding=E=>(s._OrtReleaseBinding=ye.wa)(E),s._OrtRunWithBinding=(E,P,D,Q,L)=>(s._OrtRunWithBinding=ye.xa)(E,P,D,Q,L),s._OrtRun=(E,P,D,Q,L,$,ge,lt)=>(s._OrtRun=ye.ya)(E,P,D,Q,L,$,ge,lt),s._OrtEndProfiling=E=>(s._OrtEndProfiling=ye.za)(E);var Jd=()=>(Jd=ye.Aa)();s._free=E=>(s._free=ye.Ba)(E),s._malloc=E=>(s._malloc=ye.Ca)(E);var $d=(E,P,D,Q,L,$)=>($d=ye.Fa)(E,P,D,Q,L,$),h0=()=>(h0=ye.Ga)(),m0=(E,P,D,Q,L)=>(m0=ye.Ha)(E,P,D,Q,L),p0=E=>(p0=ye.Ia)(E),Zd=E=>(Zd=ye.Ja)(E),g0=(E,P)=>(g0=ye.Ka)(E,P),A0=()=>(A0=ye.La)(),w0=(E,P)=>(w0=ye.Ma)(E,P),ac=E=>(ac=ye.Na)(E),ef=E=>(ef=ye.Oa)(E),tf=()=>(tf=ye.Pa)();return(function E(){if(0<Ee)me=E;else if(l)n(s),ne();else{for(;0<F.length;)F.shift()(s);0<Ee?me=E:(s.calledRun=!0,j||(ne(),n(s)))}})(),s.PTR_SIZE=4,a},qw=Ad,jw=(e=(r=globalThis.self)==null?void 0:r.name)==null?void 0:e.startsWith("em-pthread"),jw&&Ad()}),wd,yd,Xw,sr,Jw,qo,$w,Zw,bd,ey,Ed,ty,kd,ry,Td=Oe(()=>{md(),wd=typeof location>"u"?void 0:location.origin,yd=self.location.href>"file:"&&self.location.href<"file;",Xw=()=>{{if(yd){let r=URL;return new URL(new r("ort.wasm.bundle.min.mjs",self.location.href).href,wd).href}return self.location.href}},sr=Xw(),Jw=()=>
vendor: 4,371 bytes, line 538
538{if(sr&&!sr.startsWith("blob:"))return sr.substring(0,sr.lastIndexOf("/")+1)},qo=(r,e)=>{try{let t=e??sr;return(t?new URL(r,t):new URL(r)).origin===wd}catch{return!1}},$w=(r,e)=>{let t=e??sr;try{return(t?new URL(r,t):new URL(r)).href}catch{return}},Zw=(r,e)=>`${e??"./"}${r}`,bd=async r=>{let e=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},ey=async r=>(await import(r)).default,Ed=(S1(),cd(Gw)).default,ty=async()=>{if(!sr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qo(sr))return[void 0,Ed()];let r=await bd(sr);return[r,Ed(r)]},kd=(C1(),cd(Kw)).default,ry=async(r,e,t,n)=>{let i=kd&&!(r||e);if(i)if(sr)i=qo(sr);else if(n&&!t)i=!0;else throw new Error("cannot determine the script source URL.");if(i)return[void 0,kd];{let s="ort-wasm-simd-threaded.mjs",a=r??$w(s,e),o=t&&a&&!qo(a,e),c=o?await bd(a):a??Zw(s,e);return[o?c:void 0,await ey(c)]}}}),Sd,jo,aa,Cd,ny,iy,sy,Id,Ze,rs=Oe(()=>{Td(),jo=!1,aa=!1,Cd=!1,ny=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},iy=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},sy=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Id=async r=>{if(jo)return Promise.resolve();if(aa)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Cd)throw new Error("previous call to 'initializeWebAssembly()' failed.");aa=!0;let e=r.initTimeout,t=r.numThreads;if(r.simd!==!1){if(r.simd==="relaxed"){if(!sy())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!iy())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=ny();t>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),r.numThreads=t=1);let i=r.wasmPaths,s=typeof i=="string"?i:void 0,a=i==null?void 0:i.mjs,o=(a==null?void 0:a.href)??a,c=i==null?void 0:i.wasm,l=(c==null?void 0:c.href)??c,u=r.wasmBinary,[d,f]=await ry(o,s,t>1,!!u||!!l),h=!1,p=[];if(e>0&&p.push(new Promise(m=>{setTimeout(()=>{h=!0,m()},e)})),p.push(new Promise((m,A)=>{let g={numThreads:t};if(u)g.wasmBinary=u;else if(l||s)g.locateFile=w=>l??s+w;else if(o&&o.indexOf("blob:")!==0)g.locateFile=w=>new URL(w,o).href;else if(d){let w=Jw();w&&(g.locateFile=b=>w+b)}f(g).then(w=>{aa=!1,jo=!0,Sd=w,m(),d&&URL.revokeObjectURL(d)},w=>{aa=!1,Cd=!0,A(w)})})),await Promise.race(p),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ze=()=>{if(jo&&Sd)return Sd;throw new Error("WebAssembly is not initialized yet.")}}),Cr,Xo,Xe,Bd=Oe(()=>{rs(),Cr=(r,e)=>{let t=Ze(),n=t.lengthBytesUTF8(r)+1,i=t._malloc(n);return t.stringToUTF8(r,i,n),e.push(i),i},Xo=(r,e,t,n)=>{if(typeof r=="object"&&r!==null){if(t.has(r))throw new Error("Circular reference in options");t.add(r)}Object.entries(r).forEach(([i,s])=>{let a=e?e+i:i;if(typeof s=="object")Xo(s,a+".",t,n);else if(typeof s=="string"||typeof s=="number")n(a,s.toString());else if(typeof s=="boolean")n(a,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},Xe=r=>{let e=Ze(),t=e.stackSave();try{let n=e.PTR_SIZE,i=e.stackAlloc(2*n);e._OrtGetLastError(i,i+n);let s=Number(e.getValue(i,n===4?"i32":"i64")),a=e.getValue(i+n,"*"),o=a?e.UTF8ToString(a):"";throw new Error(`${r} ERROR_CODE: ${s}, ERROR_MESSAGE: ${o}`)}finally{e.stackRestore(t)}}}),ay,I1=Oe(()=>{rs(),Bd(),ay=r=>{let e=Ze(),t=0,n=[],i=r||{};try{if((r==null?void 0:r.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof r.logSeverityLevel!="number"||!Number.isInteger(r.logSeverityLevel)||r.logSeverityLevel<0||r.logSeverityLevel>
5384)throw new Error(`log severity level is not valid: ${r.logSeverityLevel}`);if((r==null?void 0:r.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof r.logVerbosityLevel!="number"||!Number.isInteger(r.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${r.logVerbosityLevel}`);(r==null?void 0:r.terminate)===void 0&&(i.terminate=!1);let s=0;return(r==null?void 0:r.tag)!==void 0&&(s=Cr(r.tag,n)),t=e._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,s),t===0&&Xe("Can't create run options."),(r==null?void 0:r.extra)!==void 0&&Xo(r.extra,"",new WeakSet,(a,o)=>{let c=Cr(a,n),l=Cr(o,n);e._OrtAddRunConfigEntry(t,c,l)!==0&&Xe(`Can't set a run config entry: ${a} - ${o}.`)}),[t,n]}catch(s){throw t!==0&&e._OrtReleaseRunOptions(t),n.forEach(a=>e._free(a)),s}}}),oy,cy,ly,oa,uy,dy,B1=Oe(()=>{rs(),Bd(),oy=r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}},cy=r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}},ly=r=>{r.extra||(r.extra={}),r.extra.session||(r.extra.session={});let e=r.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),r.executionProviders&&r.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(r.enableMemPattern=!1)},oa=(r,e,t,n)=>{let i=Cr(e,n),s=Cr(t,n);Ze()._OrtAddSessionConfigEntry(r,i,s)!==0&&Xe(`Can't set a session config entry: ${e} - ${t}.`)},uy=async(r,e,t)=>{for(let n of e){let i=typeof n=="string"?n:n.name,s=[];switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let u=n==null?void 0:n.deviceType;u&&oa(r,"deviceType",u,t)}break;case"webgpu":if(i="JS",typeof n!="string"){let u=n;if(u!=null&&u.preferredLayout){if(u.preferredLayout!=="NCHW"&&u.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${u.preferredLayout}`);oa(r,"preferredLayout",u.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=Cr(i,t),o=s.length,c=0,l=0;if(o>0){c=Ze()._malloc(o*Ze().PTR_SIZE),t.push(c),l=Ze()._malloc(o*Ze().PTR_SIZE),t.push(l);for(let u=0;u<o;u++)Ze().setValue(c+u*Ze().PTR_SIZE,s[u][0],"*"),Ze().setValue(l+u*Ze().PTR_SIZE,s[u][1],"*")}await Ze()._OrtAppendExecutionProvider(r,a,c,l,o)!==0&&Xe(`Can't append execution provider: ${i}.`)}},dy=async r=>{let e=Ze(),t=0,n=[],i=r||{};ly(i);try{let s=oy(i.graphOptimizationLevel??"all"),a=cy(i.executionMode??"sequential"),o=typeof i.logId=="string"?Cr(i.logId,n):0,c=i.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log severity level is not valid: ${c}`);let l=i.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u=typeof i.optimizedModelFilePath=="string"?Cr(i.optimizedModelFilePath,n):0;if(t=e._OrtCreateSessionOptions(s,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,c,l,u),t===0&&Xe("Can't create session options."),i.executionProviders&&await uy(t,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);oa(t,"enableGraphCapture",i.enableGraphCapture.toString(),n)}if(i.freeDimensionOverrides)for(let[d,f]of Object.entries(i.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let h=Cr(d,n);e._OrtAddFreeDimensionOverride(t,h,f)!==0&&Xe(`Can't set a free dimension override: ${d} - ${f}.`)}return i.extra!==void 0&&Xo(i.extra,"",new WeakSet,(d,f)=>{oa(t,d,f,n)}),[t,n]}catch(s){throw t!==0&&e._OrtReleaseSessionOptions(t)!==0&&Xe("Can't release session options."),n.forEach(a=>e._free(a)),s}}}),ns,Jo,is,fy,hy,xd,Pd,my,py=Oe(()=>{ns=r=>{switch(r){case"int8":return 3;case"uint8":return 2;case"bool":return 9;
vendor: 4,354 bytes, line 538
538case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${r}`)}},Jo=r=>{switch(r){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${r}`)}},is=(r,e)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][r],n=typeof e=="number"?e:e.reduce((i,s)=>i*s,1);return t>0?Math.ceil(n*t):void 0},fy=r=>{switch(r){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${r}`)}},hy=r=>{switch(r){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${r}`)}},xd=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint8"||r==="bool"||r==="uint4"||r==="int4",Pd=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint64"||r==="int8"||r==="uint8"||r==="bool"||r==="uint4"||r==="int4",my=r=>{switch(r){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${r}`)}}}),vd,gy=Oe(()=>{md(),vd=async r=>{if(typeof r=="string"){let e=await fetch(r);if(!e.ok)throw new Error(`failed to load external data file: ${r}`);let t=e.headers.get("Content-Length"),n=t?parseInt(t,10):0;if(n<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${r}, no response body.`);let i=e.body.getReader(),s;try{s=new ArrayBuffer(n)}catch(o){if(o instanceof RangeError){let c=Math.ceil(n/65536);s=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw o}let a=0;for(;;){let{done:o,value:c}=await i.read();if(o)break;let l=c.byteLength;new Uint8Array(s,a,l).set(c),a+=l}return new Uint8Array(s,0,n)}}else return r instanceof Blob?new Uint8Array(await r.arrayBuffer()):r instanceof Uint8Array?r:new Uint8Array(r)}}),Ay,_d,Fd,li,wy,Rd,$o,Dd,Md,Ud,Od,Nd,Qd,yy=Oe(()=>{ci(),I1(),B1(),py(),rs(),Bd(),gy(),Ay=(r,e)=>{Ze()._OrtInit(r,e)!==0&&Xe("Can't initialize onnxruntime.")},_d=async r=>{Ay(r.wasm.numThreads,hy(r.logLevel))},Fd=async(r,e)=>{var n,i;(i=(n=Ze()).asyncInit)==null||i.call(n);let t=r.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=r.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=r.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},li=new Map,wy=r=>{let e=Ze(),t=e.stackSave();try{let n=e.PTR_SIZE,i=e.stackAlloc(2*n);e._OrtGetInputOutputCount(r,i,i+n)!==0&&Xe("Can't get session input/output count.");let s=n===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+n,s))]}
538finally{e.stackRestore(t)}},Rd=(r,e)=>{let t=Ze(),n=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(r,e,a,a+s)!==0&&Xe("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let c=t.HEAP32[i/4];if(c===0)return[o,0];let l=t.HEAPU32[i/4+1],u=[];for(let d=0;d<l;d++){let f=Number(t.getValue(i+8+d*s,"*"));u.push(f!==0?t.UTF8ToString(f):Number(t.getValue(i+8+(d+l)*s,"*")))}return[o,c,u]}finally{t.stackRestore(n),i!==0&&t._OrtFree(i)}},$o=r=>{let e=Ze(),t=e._malloc(r.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${r.byteLength}.`);return e.HEAPU8.set(r,t),[t,r.byteLength]},Dd=async(r,e)=>{var u,d,f;let t,n,i=Ze();Array.isArray(r)?[t,n]=r:r.buffer===i.HEAPU8.buffer?[t,n]=[r.byteOffset,r.byteLength]:[t,n]=$o(r);let s=0,a=0,o=[],c=[],l=[];try{if([a,o]=await dy(e),(e==null?void 0:e.externalData)&&i.mountExternalData){let S=[];for(let x of e.externalData){let B=typeof x=="string"?x:x.path;S.push(vd(typeof x=="string"?x:x.data).then(I=>{i.mountExternalData(B,I)}))}await Promise.all(S)}for(let S of(e==null?void 0:e.executionProviders)??[])if((typeof S=="string"?S:S.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof S!="string"){let x=S,B=x==null?void 0:x.context,I=x==null?void 0:x.gpuDevice,C=x==null?void 0:x.deviceType,v=x==null?void 0:x.powerPreference;B?i.currentContext=B:I?i.currentContext=await i.webnnCreateMLContext(I):i.currentContext=await i.webnnCreateMLContext({deviceType:C,powerPreference:v})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,n,a),(u=i.webgpuOnCreateSession)==null||u.call(i,s),s===0&&Xe("Can't create a session."),(d=i.jsepOnCreateSession)==null||d.call(i),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=wy(s),m=!!(e!=null&&e.enableGraphCapture),A=[],g=[],w=[],b=[],k=[];for(let S=0;S<h;S++){let[x,B,I]=Rd(s,S);x===0&&Xe("Can't get an input name."),c.push(x);let C=i.UTF8ToString(x);A.push(C),w.push(B===0?{name:C,isTensor:!1}:{name:C,isTensor:!0,type:Jo(B),shape:I})}for(let S=0;S<p;S++){let[x,B,I]=Rd(s,S+h);x===0&&Xe("Can't get an output name."),l.push(x);let C=i.UTF8ToString(x);g.push(C),b.push(B===0?{name:C,isTensor:!1}:{name:C,isTensor:!0,type:Jo(B),shape:I})}return li.set(s,[s,c,l,null,m,!1]),[s,A,g,w,b]}catch(h){throw c.forEach(p=>i._OrtFree(p)),l.forEach(p=>i._OrtFree(p)),s!==0&&i._OrtReleaseSession(s)!==0&&Xe("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&Xe("Can't release session options."),o.forEach(h=>i._free(h)),(f=i.unmountExternalData)==null||f.call(i)}},Md=r=>{var c,l,u;let e=Ze(),t=li.get(r);if(!t)throw new Error(`cannot release session. invalid session id: ${r}`);let[n,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&Xe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Xe("Can't release IO binding.")),(c=e.jsepOnReleaseSession)==null||c.call(e,r),(l=e.webnnOnReleaseSession)==null||l.call(e,r),(u=e.webgpuOnReleaseSession)==null||u.call(e,r),i.forEach(d=>e._OrtFree(d)),s.forEach(d=>e._OrtFree(d)),e._OrtReleaseSession(n)!==0&&Xe("Can't release session."),li.delete(r)},Ud=async(r,e,t,n,i,s,a=!1)=>{if(!r){e.push(0);return}let o=Ze(),c=o.PTR_SIZE,l=r[0],u=r[1],d=r[3],f=d,h,p;if(l==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let g=r[2].gpuBuffer;p=is(ns(l),u);{let w=o.jsepRegisterBuffer;if(!w)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=w(n,s,g,p)}}else if(d==="ml-tensor"){let g=r[2].mlTensor;p=is(ns(l),u);let w=o.webnnRegisterMLTensor;if(!w)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=w(n,g,ns(l),u)}else{let g=r[2];if(Array.isArray(g)){p=c*g.length,h=o._malloc(p),t.push(h);for(let w=0;w<g.length;
vendor: 4,550 bytes, line 538
538w++){if(typeof g[w]!="string")throw new TypeError(`tensor data at index ${w} is not a string`);o.setValue(h+w*c,Cr(g[w],t),"*")}}else{let w=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(l!=="string"&&w&&b){let k=o.UTF8ToString(i);if(w(n,k)||b(n,k)){let S=ns(l);p=is(S,u),f="ml-tensor";let x=o.webnnCreateTemporaryTensor,B=o.webnnUploadTensor;if(!x||!B)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let I=await x(n,S,u);B(I,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),h=I}else p=g.byteLength,h=o._malloc(p),t.push(h),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,p),h)}else p=g.byteLength,h=o._malloc(p),t.push(h),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,p),h)}}let m=o.stackSave(),A=o.stackAlloc(4*u.length);try{u.forEach((w,b)=>o.setValue(A+b*c,w,c===4?"i32":"i64"));let g=o._OrtCreateTensor(ns(l),h,p,A,u.length,my(f));g===0&&Xe(`Can't create tensor for input/output. session=${n}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},Od=async(r,e,t,n,i,s)=>{var v,R,M;let a=Ze(),o=a.PTR_SIZE,c=li.get(r);if(!c)throw new Error(`cannot run inference. invalid session id: ${r}`);let l=c[0],u=c[1],d=c[2],f=c[3],h=c[4];c[5];let p=e.length,m=n.length,A=0,g=[],w=[],b=[],k=[],S=a.stackSave(),x=a.stackAlloc(p*o),B=a.stackAlloc(p*o),I=a.stackAlloc(m*o),C=a.stackAlloc(m*o);try{[A,g]=ay(s),ai("wasm prepareInputOutputTensor");for(let U=0;U<p;U++)await Ud(t[U],w,k,r,u[e[U]],e[U],h);for(let U=0;U<m;U++)await Ud(i[U],b,k,r,d[n[U]],p+n[U],h);oi("wasm prepareInputOutputTensor");for(let U=0;U<p;U++)a.setValue(x+U*o,w[U],"*"),a.setValue(B+U*o,u[e[U]],"*");for(let U=0;U<m;U++)a.setValue(I+U*o,b[U],"*"),a.setValue(C+U*o,d[n[U]],"*");(v=a.jsepOnRunStart)==null||v.call(a,l),(R=a.webnnOnRunStart)==null||R.call(a,l);let z;z=await a._OrtRun(l,B,x,p,C,m,I,A),z!==0&&Xe("failed to call OrtRun().");let W=[],H=[];ai("wasm ProcessOutputTensor");for(let U=0;U<m;U++){let j=Number(a.getValue(I+U*o,"*"));if(j===b[U]){W.push(i[U]);continue}let ce=a.stackSave(),ee=a.stackAlloc(4*o),fe=!1,he,G=0;try{a._OrtGetTensorData(j,ee,ee+o,ee+2*o,ee+3*o)!==0&&Xe(`Can't access output tensor data on index ${U}.`);let ue=o===4?"i32":"i64",we=Number(a.getValue(ee,ue));G=a.getValue(ee+o,"*");let _e=a.getValue(ee+o*2,"*"),Ye=Number(a.getValue(ee+o*3,ue)),xe=[];for(let Ee=0;Ee<Ye;Ee++)xe.push(Number(a.getValue(_e+Ee*o,ue)));a._OrtFree(_e)!==0&&Xe("Can't free memory for tensor dims.");let ne=xe.reduce((Ee,me)=>Ee*me,1);he=Jo(we);let Pe=f==null?void 0:f.outputPreferredLocations[n[U]];if(he==="string"){if(Pe==="gpu-buffer"||Pe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ee=[];for(let me=0;me<ne;me++){let Fe=a.getValue(G+me*o,"*"),Qe=a.getValue(G+(me+1)*o,"*"),ze=me===ne-1?void 0:Qe-Fe;Ee.push(a.UTF8ToString(Fe,ze))}W.push([he,xe,Ee,"cpu"])}else if(Pe==="gpu-buffer"&&ne>0){let Ee=a.jsepGetBuffer;if(!Ee)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let me=Ee(G),Fe=is(we,ne);if(Fe===void 0||!xd(he))throw new Error(`Unsupported data type: ${he}`);fe=!0,W.push([he,xe,{gpuBuffer:me,download:a.jsepCreateDownloader(me,Fe,he),dispose:()=>{a._OrtReleaseTensor(j)!==0&&Xe("Can't release tensor.")}},"gpu-buffer"])}else if(Pe==="ml-tensor"&&ne>0){let Ee=a.webnnEnsureTensor,me=a.webnnIsGraphInputOutputTypeSupported;if(!Ee||!me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(is(we,ne)===void 0||!Pd(he))throw new Error(`Unsupported data type: ${he}`);if(!me(r,he,!1))throw new Error(`preferredLocation "ml-tensor" for ${he} output is not supported by current WebNN Context.`);let Fe=await Ee(r,G,we,xe,!1);fe=!0,W.push([he,xe,{mlTensor:Fe,download:a.webnnCreateMLTensorDownloader(G,he),dispose:()=>{a.webnnReleaseTensorId(G),a._OrtReleaseTensor(j)}},"ml-tensor"])}else if(Pe==="ml-tensor-cpu-output"&&ne>0){let Ee=a.webnnCreateMLTensorDownloader(G,he)(),me=W.length;fe=!0,H.push((async()=>{let Fe=[me,await Ee];return a.webnnReleaseTensorId(G),a._OrtReleaseTensor(j),Fe})()),W.push([he,xe,[],"cpu"])}else{let Ee=fy(he),me=new Ee(ne);new Uint8Array(me.buffer,me.byteOffset,me.byteLength).set(a.HEAPU8.subarray(G,G+me.byteLength)),W.push([he,xe,me,"cpu"])}}finally{a.stackRestore(ce),he==="string"&&G&&a._free(G),fe||a._OrtReleaseTensor(j)}}f&&!h&&(a._OrtClearBoundOutputs(f.handle)!==0&&Xe("Can't clear bound outputs."),li.set(r,[l,u,d,f,h,!1]));for(let[U,j]of await Promise.all(H))W[U][2]=j;return oi("wasm ProcessOutputTensor"),W}finally{(M=a.webnnOnRunEnd)==null||M.call(a,l),a.stackRestore(S),w.forEac
vendor: 6,275 bytes, line 538
538h(z=>a._OrtReleaseTensor(z)),b.forEach(z=>a._OrtReleaseTensor(z)),k.forEach(z=>a._free(z)),A!==0&&a._OrtReleaseRunOptions(A),g.forEach(z=>a._free(z))}},Nd=r=>{let e=Ze(),t=li.get(r);if(!t)throw new Error("invalid session id");let n=t[0],i=e._OrtEndProfiling(n);i===0&&Xe("Can't get an profile file name."),e._OrtFree(i)},Qd=r=>{let e=[];for(let t of r){let n=t[2];!Array.isArray(n)&&"buffer"in n&&e.push(n.buffer)}return e}}),Pn,qt,ss,ca,la,Zo,Ld,ec,ui,di,by,Ey,ky,Ty,Sy,Cy,Iy,By,xy=Oe(()=>{ci(),yy(),rs(),Td(),Pn=()=>!!st.wasm.proxy&&typeof document<"u",ss=!1,ca=!1,la=!1,ec=new Map,ui=(r,e)=>{let t=ec.get(r);t?t.push(e):ec.set(r,[e])},di=()=>{if(ss||!ca||la||!qt)throw new Error("worker not ready")},by=r=>{switch(r.data.type){case"init-wasm":ss=!1,r.data.err?(la=!0,Ld[1](r.data.err)):(ca=!0,Ld[0]()),Zo&&(URL.revokeObjectURL(Zo),Zo=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ec.get(r.data.type);r.data.err?e.shift()[1](r.data.err):e.shift()[0](r.data.out);break}}},Ey=async()=>{if(!ca){if(ss)throw new Error("multiple calls to 'initWasm()' detected.");if(la)throw new Error("previous call to 'initWasm()' failed.");if(ss=!0,Pn())return new Promise((r,e)=>{qt==null||qt.terminate(),ty().then(([t,n])=>{try{qt=n,qt.onerror=s=>e(s),qt.onmessage=by,Ld=[r,e];let i={type:"init-wasm",in:st};!i.in.wasm.wasmPaths&&(t||yd)&&(i.in.wasm.wasmPaths={wasm:new URL("/build/assets/ort-wasm-simd-threaded-CpHjICJN.wasm",self.location.href).href}),qt.postMessage(i),Zo=t}catch(i){e(i)}},e)});try{await Id(st.wasm),await _d(st),ca=!0}catch(r){throw la=!0,r}finally{ss=!1}}},ky=async r=>{if(Pn())return di(),new Promise((e,t)=>{ui("init-ep",[e,t]);let n={type:"init-ep",in:{epName:r,env:st}};qt.postMessage(n)});await Fd(st,r)},Ty=async r=>Pn()?(di(),new Promise((e,t)=>{ui("copy-from",[e,t]);let n={type:"copy-from",in:{buffer:r}};qt.postMessage(n,[r.buffer])})):$o(r),Sy=async(r,e)=>{if(Pn()){if(e!=null&&e.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return di(),new Promise((t,n)=>{ui("create",[t,n]);let i={type:"create",in:{model:r,options:{...e}}},s=[];r instanceof Uint8Array&&s.push(r.buffer),qt.postMessage(i,s)})}else return Dd(r,e)},Cy=async r=>{if(Pn())return di(),new Promise((e,t)=>{ui("release",[e,t]);let n={type:"release",in:r};qt.postMessage(n)});Md(r)},Iy=async(r,e,t,n,i,s)=>{if(Pn()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return di(),new Promise((a,o)=>{ui("run",[a,o]);let c=t,l={type:"run",in:{sessionId:r,inputIndices:e,inputs:c,outputIndices:n,options:s}};qt.postMessage(l,Qd(c))})}else return Od(r,e,t,n,i,s)},By=async r=>{if(Pn())return di(),new Promise((e,t)=>{ui("end-profiling",[e,t]);let n={type:"end-profiling",in:r};qt.postMessage(n)});Nd(r)}}),zd,Py,vy,x1=Oe(()=>{ci(),xy(),py(),md(),gy(),zd=(r,e)=>{switch(r.location){case"cpu":return[r.type,r.dims,r.data,"cpu"];case"gpu-buffer":return[r.type,r.dims,{gpuBuffer:r.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[r.type,r.dims,{mlTensor:r.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${r.location} for ${e()}`)}},Py=r=>{switch(r[3]){case"cpu":return new Sr(r[0],r[2],r[1]);case"gpu-buffer":{let e=r[0];if(!xd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:n,dispose:i}=r[2];return Sr.fromGpuBuffer(t,{dataType:e,dims:r[1],download:n,dispose:i})}case"ml-tensor":{let e=r[0];if(!Pd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:n,dispose:i}=r[2];return Sr.fromMLTensor(t,{dataType:e,dims:r[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${r[3]}`)}},vy=class{async fetchModelAndCopyToWasmMemory(r){return Ty(await vd(r))}async loadModel(r,e){ii();let t;typeof r=="string"?t=await this.fetchModelAndCopyToWasmMemory(r):t=r,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Sy(t,e),si()}async dispose(){return Cy(this.sessionId)}async run(r,e,t){ii();let n=[],i=[];Object.entries(r).forEach(d=>{let f=d[0],h=d[1],p=this.inputNames.indexOf(f);if(p===-1)throw new Error(`invalid input '${f}'`);n.push(h),i.push(p)});let s=[],a=[];Object.entries(e).forEach(d=>{let f=d[0],h=d[1],p=this.outputNames.indexOf(f);if(p===-1)throw new Error(`invalid output '${f}'`);s.push(h),a.push(p)});let o=n.map((d,f)=>zd(d,()=>`input "${this.inputNames[i[f]]}"`)),c=s.map((d,f)=>d?zd(d,()=>`output "${this.outputNames[a[f]]}"`):null),l=await Iy(this.sessionId,i,o,a,c,t),u={};for(let d=0;d<l.length;d++)u[this.outputNames[a[d]]]=s[d]??Py(l[d]);return si(),u}startProfiling(){}endProfiling(){By(this.sessionId)}}}),_y={};Go(_y,{OnnxruntimeWebAssemblyBackend:()=>Vd,initializeFlags:()=>Wd,wasmBackend:()=>Fy});var Wd,Vd,Fy,P1=Oe(()=>{ci(),xy(),x1(),Wd=()=>{(typeof st.wasm.initTimeout!="number"||st.wasm.initTimeout<0)&&(st.wasm.initTimeout=0);let r=st.wasm.simd;if(typeof r!="boolean"&&r!==void 0&&r!=="fixed"&&r!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${r}". Reset it to \`false\` and ignore SIMD feature checking.`),st.wasm.simd=!1),typeof st.wasm.proxy!="boolean"&&(st.wasm.proxy=!1),typeof st.wasm.trace!="boolean"&&(st.wasm.trace=!1),typeof st.wasm.numThreads!="number"||!Number.isInteger(st.wasm.numThreads)||st.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)st.wasm.numThreads=1;else{let e=typeof navigator>"u"?l1("node:os").cpus().length:navigator.hardwareConcurrency;st.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Vd=class{async init(r){Wd(),await Ey(),await ky(r)}async createInferenceSessionHandler(r,e){let t=new vy;return await t.loadModel(r,e),t}},Fy=new Vd});ci(),ci(),ci();var v1="1.23.0",_1=Hw;{let r=(P1(),cd(_y)).wasmBackend;ia("cpu",r,10),ia("wasm",r,10)}Object.defineProperty(st.versions,"web",{value:v1,enumerable:!0});var F1=Object.freeze({__proto__:null,get InferenceSession(){return hd},get TRACE(){return Ko},get TRACE_EVENT_BEGIN(){return ai},get TRACE_EVENT_END(){return oi},get TRACE_FUNC_BEGIN(){return ii},get TRACE_FUNC_END(){return si}
538,get Tensor(){return Sr},default:_1,get env(){return st},get registerBackend(){return ia}})})();
539!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5e2fd67d-7bac-5d3a-9299-9a4375ec9775")}catch(e){}}()
540//# debugId=5e2fd67d-7bac-5d3a-9299-9a4375ec9775
541//# sourceMappingURL=upload-entry-worker-web.worker-B-_eEOYp.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.