1import{i as ca,a as ge,b as p,B as K,c as Ks,g as nc,r as B,t as q,d as xe,e as la,f as it,A as jr,l as ce,h as $,k as ei,j as ac,m as ie,s as pr,n as gr,V as Qr,o as Gs,u as ua,P as ot,p as Ue,q as G,v as rs,M as Xi,T as ji,C as Qi,O as ti,w as wi,U as le,x as yi,y as oc,z as kr,D as wr,E as Ti,F as ns,G as ee,H as Oe,I as Ei,J as cc,K as lc,L as Rt,N as uc,Q as da,R as Ai,S as as,W as Ps,X as di,Y as Zt,Z as ii,_ as Hi,$ as me,a0 as J,a1 as os,a2 as dc,a3 as hc,a4 as fc,a5 as ha,a6 as Xs,a7 as fa,a8 as ma,a9 as de,aa as _e,ab as mi,ac as Ne,ad as $i,ae as mc,af as pc,ag as pa,ah as ga,ai as $r,aj as gc,ak as Le,al as bi,am as ka,an as wa,ao as Ee,ap as Yr,aq as Yi,ar as kc,as as je,at as Ut,au as Tt,av as ya,aw as Ta,ax as wt,ay as ba,az as Sa,aA as yr,aB as Tr,aC as br,aD as cs,aE as wc,aF as Sr,aG as Pa,aH as yc,aI as Tc,aJ as bc,aK as Sc,aL as Pr,aM as xr,aN as Pc,aO as xc,aP as Ft,aQ as xa,aR as _a,aS as _c,aT as Cc,aU as Ic,aV as Zr,aW as Ec,aX as Ac,aY as vc,aZ as Xt,a_ as jt,a$ as Mt,b0 as Jr,b1 as Fc,b2 as en,b3 as Ca,b4 as xh,b5 as _h}from"./custom-coder-DyYUgi0m.js";import{b6 as Yh,b7 as Zh,b8 as Jh,b9 as ef,ba as tf,bb as sf,bc as rf,bd as nf,be as af,bf as of,bg as cf,bh as lf,bi as uf,bj as df,bk as hf,bl as ff,bm as mf,bn as pf,bo as gf,bp as kf,bq as wf,br as yf,bs as Tf,bt as bf,bu as Sf,bv as Pf,bw as xf,bx as _f,by as Cf}from"./custom-coder-DyYUgi0m.js";import{n as Zi}from"./__vite-browser-external-ke9ZaMpT.js";/*! 2 * Copyright (c) 2026-present, Vanilagy and contributors 3 * 4 * This Source Code Form is subject to the terms of the Mozilla Public 5 * License, v. 2.0. If a copy of the MPL was not distributed with this 6 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 7 */class Qt{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 _r{constructor(e,t,i,s){if(this.data=e,this.mimeType=t,this.name=i,this.description=s,!(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(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}}const js=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
7h 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 Qt)&&!(e instanceof _r)&&!ca(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Si=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),ct={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Bc=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.")};/*! 8 * Copyright (c) 2026-present, Vanilagy and contributors 9 * 10 * This Source Code Form is subject to the terms of the Mozilla Public 11 * License, v. 2.0. If a copy of the MPL was not distributed with this 12 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 13 */const At=4,Rc=[44100,48e3,32e3],Qs=[-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],ls=1483304551,Cr=1231971951,$s=(r,e,t,i,s)=>e===0?0:e===1?Math.floor(144*t/(i<<r))+s:e===2?Math.floor(144*t/i)+s:(Math.floor(12*t/i)+s)*4,Mc=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,us=(r,e)=>r===3?e===3?21:36:e===3?13:21,ds=(r,e)=>{const t=r>>>24,i=r>>>16&255,s=r>>>8&255,n=r&255;if(t!==255&&i!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((i&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;i&16?a=i&8?0:1:(a=1,o=1);const c=i>>3&3,l=i>>1&3,d=s>>4&15,u=(s>>2&3)%3,h=s>>1&1,f=n>>6&3,g=n>>4&3,m=n>>3&1,w=n>>2&1,k=n&3,y=Qs[a*16*4+l*16+d];if(y===-1)return{header:null,bytesAdvanced:1};const T=y*1e3,b=Rc[u]>>a+o,P=$s(a,l,T,b,h);if(e!==null&&e<P)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:P,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:T,frequencyIndex:u,sampleRate:b,channel:f,modeExtension:g,copyright:m,original:w,emphasis:k,audioSamplesInFrame:x},bytesAdvanced:1}},zc=r=>{let e=127,t=0,i=r;for(;(e^2147483647)!==0;)t=i&~e,t<<=1,t|=i&e,e=(e+1<<8)-1,i=t;return t},Ys=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var vt;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(vt||(vt={}));const Pi=r=>r===3?1:2;/*! 14 * Copyright (c) 2026-present, Vanilagy and contributors 15 * 16 * This Source Code Form is subject to the terms of the Mozilla Public 17 * License, v. 2.0. If a copy of the MPL was not distributed with this 18 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 19 */const hs=[48e3,44100,32e3],Ia=[24e3,22050,16e3];/*! 20 * Copyright (c) 2026-present, Vanilagy and contributors 21 * 22 * This Source Code Form is subject to the terms of the Mozilla Public 23 * License, v. 2.0. If a copy of the MPL was not distributed with this 24 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 25 */var Pe;(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"})(Pe||(Pe={}));var ne;(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"})(ne||(ne={}));const si=function*(r){let e=0,t=-1;for(;e<r.length-2;){const i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let s=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?s=4:r[e+1]===0&&r[e+2]===1&&(s=3),s===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+s,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},Ir=function*(r,e){let t=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let s;e===1?s=i.getUint8(t):e===2?s=i.getUint16(t,!1):e===3?s=gr(i,t,!1):(p(e===4),s=i.getUint32(t,!1)),t+=e,yield{offset:t,length:s},t+=s}},Ea=(r,e)=>{if(e.description){const s=(ie(e.description)[4]&3)+1;return Ir(r,s)}else return si(r)}
25,Jt=r=>r&31,fs=r=>{const e=[],t=r.length;for(let i=0;i<t;i++)i+2<t&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(0,0),i+=2):e.push(r[i]);return new Uint8Array(e)},xs=new Uint8Array([0,0,0,1]),Ji=r=>{const e=r.reduce((s,n)=>s+xs.byteLength+n.byteLength,0),t=new Uint8Array(e);let i=0;for(const s of r)t.set(xs,i),i+=xs.byteLength,t.set(s,i),i+=s.byteLength;return t},Er=(r,e)=>{const t=r.reduce((n,a)=>n+e+a.byteLength,0),i=new Uint8Array(t);let s=0;for(const n of r){const a=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:pr(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,i.set(n,s),s+=n.byteLength}return i},Dc=(r,e)=>{if(e.description){const s=(ie(e.description)[4]&3)+1;return Er(r,s)}else return Ji(r)},Ar=r=>{try{const e=[],t=[],i=[];for(const o of si(r)){const c=r.subarray(o.offset,o.offset+o.length),l=Jt(c[0]);l===Pe.SPS?e.push(c):l===Pe.PPS?t.push(c):l===Pe.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const s=e[0],n=vr(s);p(n!==null);const a=n.profileIdc===100||n.profileIdc===110||n.profileIdc===122||n.profileIdc===144;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?n.chromaFormatIdc:null,bitDepthLumaMinus8:a?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},Uc=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 i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}e.push(r.pictureParameterSets.length);for(const t of r.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}if(r.avcProfileIndication===100||r.avcProfileIndication===110||r.avcProfileIndication===122||r.avcProfileIndication===144){p(r.chromaFormat!==null),p(r.bitDepthLumaMinus8!==null),p(r.bitDepthChromaMinus8!==null),p(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 i=t.byteLength;e.push(i>>8),e.push(i&255);for(let s=0;s<i;s++)e.push(t[s])}}return new Uint8Array(e)},Aa=r=>{try{const e=q(r);let t=0;const i=e.getUint8(t++),s=e.getUint8(t++),n=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let f=0;f<c;f++){const g=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+g)),t+=g}const d=e.getUint8(t++),u=[];for(let f=0;f<d;f++){const g=e.getUint16(t,!1);t+=2,u.push(r.subarray(t,t+g)),t+=g}const h={configurationVersion:i,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&t+4<=r.length){const f=e.getUint8(t++)&3,g=e.getUint8(t++)&7,m=e.getUint8(t++)&7,w=e.getUint8(t++);h.chromaFormat=f,h.bitDepthLumaMinus8=g,h.bitDepthChromaMinus8=m;const k=[];for(let y=0;y<w;y++){const T=e.getUint16(t,!1);t+=2,k.push(r.subarray(t,t+T)),t+=T}h.sequenceParameterSetExt=k}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},va={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}},vr=r=>{try{const e=new K(fs(r));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const i=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();B(e);let a=1,o=0,c=0,l=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=B(e),a===3&&(l=e.readBits(1)),o=B(e),c=B(e),e.skipBits(1),e.readBits(1))){for(let v=0;v<(a!==3?8:12);v++)if(e.readBits(1)){const W=v<6?16:64;let O=8,U=8;for(let j=0;j<W;j++){if(U!==0){const ae=it(e);U=(O+ae+256)%256}O=U===0?O:U}}}B(e);const d=B(e);if(d===0)B(e);else if(d===1){e.skipBits(1),it(e),it(e);const R=B(e);for(let v=0;v<R;v++)it(e)}B(e),e.skipBits(1);const u=B(e),h=B(e),f=16*(u+1),g=16*(h+1);let m=f,w=g;
25const k=e.readBits(1);if(k||e.skipBits(1),e.skipBits(1),e.readBits(1)){const R=B(e),v=B(e),z=B(e),W=B(e);let O,U;if((l===0?a:0)===0)O=1,U=2-k;else{const ae=a===3?1:2,ke=a===1?2:1;O=ae,U=ke*(2-k)}m-=O*(R+v),w-=U*(z+W)}let T=2,b=2,P=2,x=0,I={num:1,den:1},C=null,_=null;if(e.readBits(1)){if(e.readBits(1)){const ke=e.readBits(8);if(ke===255)I={num:e.readBits(16),den:e.readBits(16)};else{const Mi=va[ke];Mi&&(I=Mi)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),x=e.readBits(1),e.readBits(1)&&(T=e.readBits(8),b=e.readBits(8),P=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const U=e.readBits(1);U&&tn(e);const j=e.readBits(1);j&&tn(e),(U||j)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),B(e),B(e),B(e),B(e),C=B(e),_=B(e))}if(C===null){p(_===null);const R=s&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&R)C=0,_=0;else{const v=u+1,z=h+1,W=(2-k)*z,O=jr.find(j=>j.level>=n)??ce(jr),U=Math.min(Math.floor(O.maxDpbMbs/(v*W)),16);C=U,_=U}}return p(_!==null),{profileIdc:i,constraintFlags:s,levelIdc:n,frameMbsOnlyFlag:k,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:g,displayWidth:m,displayHeight:w,pixelAspectRatio:I,colourPrimaries:T,matrixCoefficients:P,transferCharacteristics:b,fullRangeFlag:x,numReorderFrames:C,maxDecFrameBuffering:_}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},tn=r=>{const e=B(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)B(r),B(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Oc=(r,e)=>{if(e.description){const s=(ie(e.description)[21]&3)+1;return Er(r,s)}else return Ji(r)},es=(r,e)=>{if(e.description){const s=(ie(e.description)[21]&3)+1;return Ir(r,s)}else return si(r)},yt=r=>r>>1&63,Fa=r=>{try{const e=new K(fs(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:s,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Nc(e,t);B(e);const d=B(e);let u=0;d===3&&(u=e.readBits(1));const h=B(e),f=B(e);let g=h,m=f;if(e.readBits(1)){const v=B(e),z=B(e),W=B(e),O=B(e);let U=1,j=1;const ae=u===0?d:0;ae===1?(U=2,j=2):ae===2&&(U=2,j=1),g-=(v+z)*U,m-=(W+O)*j}const w=B(e),k=B(e);B(e);const T=e.readBits(1)?0:t;let b=0;for(let v=T;v<=t;v++)B(e),b=B(e),B(e);B(e),B(e),B(e),B(e),B(e),B(e),e.readBits(1)&&e.readBits(1)&&Lc(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),B(e),B(e),e.skipBits(1));const P=B(e);if(Wc(e,P),e.readBits(1)){const v=B(e);for(let z=0;z<v;z++)B(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,I=2,C=2,_=0,E=0,R={num:1,den:1};if(e.readBits(1)){const v=Hc(e,t);R=v.pixelAspectRatio,x=v.colourPrimaries,I=v.transferCharacteristics,C=v.matrixCoefficients,_=v.fullRangeFlag,E=v.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:m,pixelAspectRatio:R,colourPrimaries:x,transferCharacteristics:I,matrixCoefficients:C,fullRangeFlag:_,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:d,bitDepthLumaMinus8:w,bitDepthChromaMinus8:k,minSpatialSegmentationIdc:E}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},Fr=r=>{try{const e=[],t=[],i=[],s=[];for(const l of si(r)){const d=r.subarray(l.offset,l.offset+l.length),u=yt(d[
250]);u===ne.VPS_NUT?e.push(d):u===ne.SPS_NUT?t.push(d):u===ne.PPS_NUT?i.push(d):(u===ne.PREFIX_SEI_NUT||u===ne.SUFFIX_SEI_NUT)&&s.push(d)}if(t.length===0||i.length===0)return null;const n=Fa(t[0]);if(!n)return null;let a=0;if(i.length>0){const l=i[0],d=new K(fs(l));d.skipBits(16),B(d),B(d),d.skipBits(1),d.skipBits(1),d.skipBits(3),d.skipBits(1),d.skipBits(1),B(d),B(d),it(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&B(d),it(d),it(d),d.skipBits(1),d.skipBits(1),d.skipBits(1),d.skipBits(1);const u=d.readBits(1),h=d.readBits(1);!u&&!h?a=0:u&&!h?a=2:!u&&h?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:ne.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:ne.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ne.PPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:yt(s[0][0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.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),i=r.readBits(1),s=r.readBits(5);let n=0;for(let d=0;d<32;d++)n=n<<1|r.readBits(1);const a=new Uint8Array(6);for(let d=0;d<6;d++)a[d]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let d=0;d<e;d++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let d=e;d<8;d++)r.skipBits(2);for(let d=0;d<e;d++)c[d]&&r.skipBits(88),l[d]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},Lc=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))B(r);else{const s=Math.min(64,1<<4+(e<<1));e>1&&it(r);for(let n=0;n<s;n++)it(r)}},Wc=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=Vc(r,i,e,t)},Vc=(r,e,t,i)=>{let s=0,n=0,a=0;if(e!==0&&(n=r.readBits(1)),n){if(e===t){const c=B(r);a=e-(c+1)}else a=e-1;r.readBits(1),B(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);s=i[a]}else{const o=B(r),c=B(r);for(let l=0;l<o;l++)B(r),r.readBits(1);for(let l=0;l<c;l++)B(r),r.readBits(1);s=o+c}return s},Hc=(r,e)=>{let t=2,i=2,s=2,n=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=va[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),n=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),s=r.readBits(8))),r.readBits(1)&&(B(r),B(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(B(r),B(r),B(r),B(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&B(r),r.readBits(1)&&qc(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=B(r),B(r),B(r),B(r),B(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:s,fullRangeFlag:n,minSpatialSegmentationIdc:a}},qc=(r,e,t)=>{let i=!1,s=!1,n=!1;i=r.readBits(1)===1,s=r.readBits(1)===1,(i||s)&&(n=r.readBits(1)===1,n&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),n&&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?B(r):l=r.readBits(1)===1;let d=1;l||(d=B(r)+1),i&&sn(r,d,n),s&&sn(r,d,n)}},sn=(r,e,t)=>{for(let i=0;i<e;i++)B(r),B(r),t&&(B(r),B(r)),r.readBits(1)},Kc=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
25UnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let s=0;s<i.length;s++)e.push(i[s])}}return new Uint8Array(e)},Gc=r=>{try{const e=q(r);let t=0;const i=e.getUint8(t++),s=e.getUint8(t++),n=s>>6&3,a=s>>5&1,o=s&31,c=e.getUint32(t,!1);t+=4;const l=r.subarray(t,t+6);t+=6;const d=e.getUint8(t++),u=(e.getUint8(t++)&15)<<8|e.getUint8(t++),h=e.getUint8(t++)&3,f=e.getUint8(t++)&3,g=e.getUint8(t++)&7,m=e.getUint8(t++)&7,w=e.getUint16(t,!1);t+=2;const k=e.getUint8(t++),y=k>>6&3,T=k>>3&7,b=k>>2&1,P=k&3,x=e.getUint8(t++),I=[];for(let C=0;C<x;C++){const _=e.getUint8(t++),E=_>>7&1,R=_&63,v=e.getUint16(t,!1);t+=2;const z=[];for(let W=0;W<v;W++){const O=e.getUint16(t,!1);t+=2,z.push(r.subarray(t,t+O)),t+=O}I.push({arrayCompleteness:E,nalUnitType:R,nalUnits:z})}return{configurationVersion:i,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:d,minSpatialSegmentationIdc:u,parallelismType:h,chromaFormatIdc:f,bitDepthLumaMinus8:g,bitDepthChromaMinus8:m,avgFrameRate:w,constantFrameRate:y,numTemporalLayers:T,temporalIdNested:b,lengthSizeMinusOne:P,arrays:I}}catch(e){return console.error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var he;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl
25=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(he||(he={}));const Xc=(r,e)=>{const t=new Set;let i=he.audAllowed;for(const n of es(r,e)){if(i===he.noMoreDataAllowed){t.add(n.offset);continue}const a=yt(r[n.offset]);if(i===he.eoBitstreamAllowed&&a!==37){t.add(n.offset);continue}let o=!1;a===35?i>he.audAllowed?o=!0:i=he.beforeFirstVcl:a<=31?i>he.afterFirstVcl?o=!0:i=he.afterFirstVcl:a===36?i!==he.afterFirstVcl?o=!0:i=he.eoBitstreamAllowed:a===37?i<he.afterFirstVcl?o=!0:i=he.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>he.beforeFirstVcl?o=!0:i=he.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<he.afterFirstVcl&&(o=!0),o&&t.add(n.offset)}if(t.size===0)return null;const s=[];for(const n of es(r,e))t.has(n.offset)||s.push(r.subarray(n.offset,n.offset+n.length));return Oc(s,e)},Ba=r=>{const e=new K(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),n=(e.readBits(1)<<1)+i;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);const d=e.readBits(3);let u=0,h=0;if(d!==7)if(h=e.readBits(1),n===1||n===3){const I=e.readBits(1),C=e.readBits(1);u=!I&&!C?3:I&&!C?2:1,e.skipBits(1)}else u=1;else u=3,h=1;const f=e.readBits(16),g=e.readBits(16),m=f+1,w=g+1,k=m*w;let y=ce(Qr).level;for(const x of Qr)if(k<=x.maxPictureSize){y=x.level;break}return{profile:n,level:y,bitDepth:l,chromaSubsampling:u,videoFullRangeFlag:h,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},Ra=function*(r){const e=new K(r),t=()=>{let i=0;for(let s=0;s<8;s++){const n=e.readAlignedByte();if(i|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Ma=r=>{for(const{type:e,data:t}of Ra(r)){if(e!==1)continue;const i=new K(t),s=i.readBits(3);i.readBits(1);const n=i.readBits(1);let a=0,o=0,c=0;if(n)a=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;const P=i.readBits(1);P&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));const x=i.readBits(5);for(let I=0;I<=x;I++){i.skipBits(12);const C=i.readBits(5);if(I===0&&(a=C),C>7){const E=i.readBits(1);I===0&&(o=E)}if(P&&i.readBits(1)){const R=c+1;i.skipBits(R),i.skipBits(R),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(4),d=i.readBits(4),u=l+1;i.skipBits(u);const h=d+1;i.skipBits(h);let f=0;if(n?f=0:f=i.readBits(1),f&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!n){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const b=i.readBits(1);b&&(i.skipBits(1),i.skipBits(1));const P=i.readBits(1);let x=0;P?x=2:x=i.readBits(1),x>0&&(i.readBits(1)||i.skipBits(1)),b&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const g=i.readBits(1);let m=8;s===2&&g?m=i.readBits(1)?12:10:s<=2&&(m=g?10:8);let w=0;s!==1&&(w=i.readBits(1));let k=1,y=1,T=0;return w||(s===0?(k=1,y=1):s===1?(k=0,y=0):m===12&&(k=i.readBits(1),k&&(y=i.readBits(1))),k&&y&&(T=i.readBits(2))),{profile:s,level:a,tier:o,bitDepth:m,monochrome:w,chromaSubsamplingX:k,chromaSubsamplingY:y,chromaSamplePosition:T}}return null},ms=r=>{const e=q(r),t=e.getUint8(9),i=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},jc=[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],Qc=r=>{const e=r[0]>>3;return{durationInSamples:jc[e]}},za=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,i=new Uint8Array(t);for(let u=0;u<t;u++)i[u]=r[t-1-u];const s=new K(i);let n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){const u=s.pos,h=s.readBits(8),f=s.readBits(16),g=s.readBits(16);if(h>63||f!==0||g!==0){s.pos=u;break}if(s.skipBits(1),a++,a>64)break;s.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;s.pos=0,s.skipBits(n);const d=Array(l).fill(0);for(let u=l-1;u>=0;u--)s.skipBits(40),d[u]=s.readBits(1);return{modeBlockflags:d}},ps=(r,e,t)=>{switch(r){case"avc":{for(const i of Ea(t,e)){const s=t[i.offset],n=Jt(s);if(n>=Pe.NON_IDR_SLICE&&n<=Pe.SLICE_DPC)return"delta";if(n===Pe.IDR)return"key";if(n===Pe.SEI&&(!Ks()||nc()>=144)){const a=t.subarray(i.offset,i.offset+i.length),o=fs(a);let c=1;do{let l=0;for(;;){const h=o[c++];if(h===void 0||(l+=h,h<255))break}let d=0;for(;;){const h=o[c++];if(h===void 0||(d+=h,h<255))break}if(l===6){const h=new K(o);h.pos=8*c;const f=B(h),g=h.readBits(1);if(f===0&&g===1)return"key"}c+=d}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of es(t,e)){const s=yt(t[i.offset]);if(s<ne.BLA_W_LP)return"delta";if(s<=ne.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new K(t);if(i.readBits(2)!==2)return null;const s=i.readBits(1);return(i.readBits(1)<<1)+s===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:s,data:n}of Ra(t))if(s===1){const a=new K(n);a.skipBits(4),i=!!a.readBits(1)}else if(s===3||s===6||s===7){if(i)return"key";const a=new K(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:ge(r),p(!1)}};var st;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(st||(st={}));const Zs=(r,e)=>{const t=q(r);let i=0;const s=t.getUint32(i,!0);i+=4;const n=xe.decode(r.subarray(i,i+s));i+=s,s>0&&(e.raw??={},e.raw.vendor??=n);const a=t.getUint32(i,!0);i+=4;for(let o=0;o<a;o++){const c=t.getUint32(i,!0);i+=4;const l=xe.decode(r.subarray(i,i+c));i+=c;const d=l.indexOf("=");if(d===-1)continue;const u=l.slice(0,d).toUpperCase(),h=l.slice(d+1);switch(e.raw??={},e.raw[u]??=h,u){case"TITLE":e.title??=h;break;case"DESCRIPTION":e.description??=h;break;case"ARTIST":e.artist??=h;break;case"ALBUM":e.album??=h;break;case"ALBUMARTIST":e.albumArtist??=h;break;case"COMMENT":e.comment??=h;break;case"LYRICS":e.lyrics??=h;break;case"TRACKNUMBER":{const f=h.split("/"),g=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(g)&&g>0&&(e.trackNumber??=g),m&&Number.isInteger(m)&&m>0&&(e.tracksTotal??=m)}break;case"TRACKTOTAL":{const f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??=f)}break;case"DISCNUMBER":{const f=h.split("/"),g=Number.parseInt(f[0],10),m=f[1]&&Number.parseInt(f[1],10);Number.isInteger(g)&&g>0&&(e.discNumber??=g),m&&Number.isInteger(m)&&m>0&&(e.discsTotal??=m)}break;case"DISCTOTAL":{const f=Number.parseInt(h,10);Number.isInteger(f)&&f>0&&(e.discsTotal??=f)}break;case"DATE":{const f=new Date(h);Number.isNaN(f.getTime())||(e.date??=f)}break;case"GENRE":e.genre??=h;break;case"METADATA_BLOCK_PICTURE":{const f=la(h),g=q(f),m=g.getUint32(0,!1),w=g.getUint32(4,!1),k=String.fromCharCode(...f.subarray(8,8+w)),y=g.getUint32(8+w,!1),T=xe.decode(f.subarray(12+w,12+w+y)),b=g.getUint32(w+y+28),P=f.subarray(w+y+32,w+y+32+b);e.images??=[],e.images.push({data:P,mimeType:k,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:T||void 0})}break}}},Js=(r,e,t)=>{const i=[r],n=$.encode("Mediabunny");let a=new Uint8Array(4+n.length),o=new DataView(a.buffer);o.setUint32(0,n.length,!0),a.set(n,4),i.push(a);const c=new Set,l=(g,m)=>{const w=`${g}=${m}`,k=$.encode(w);a=new Uint8Array(4+k.length),o=new DataView(a.buffer),o.setUint32(0,k.length,!0),a.set(k,4),i.push(a),c.add(g)};for(const{key:g,value:m}of ei(e))switch(g){case"title":l("TITLE",m);break;
25case"description":l("DESCRIPTION",m);break;case"artist":l("ARTIST",m);break;case"album":l("ALBUM",m);break;case"albumArtist":l("ALBUMARTIST",m);break;case"genre":l("GENRE",m);break;case"date":{const w=e.raw?.DATE??e.raw?.date;w&&typeof w=="string"?l("DATE",w):l("DATE",m.toISOString().slice(0,10))}break;case"comment":l("COMMENT",m);break;case"lyrics":l("LYRICS",m);break;case"trackNumber":l("TRACKNUMBER",m.toString());break;case"tracksTotal":l("TRACKTOTAL",m.toString());break;case"discNumber":l("DISCNUMBER",m.toString());break;case"discsTotal":l("DISCTOTAL",m.toString());break;case"images":{if(!t)break;for(const w of m){const k=w.kind==="coverFront"?3:w.kind==="coverBack"?4:0,y=new Uint8Array(w.mimeType.length);for(let I=0;I<w.mimeType.length;I++)y[I]=w.mimeType.charCodeAt(I);const T=$.encode(w.description??""),b=new Uint8Array(8+y.length+4+T.length+16+4+w.data.length),P=q(b);P.setUint32(0,k,!1),P.setUint32(4,y.length,!1),b.set(y,8),P.setUint32(8+y.length,T.length,!1),b.set(T,12+y.length),P.setUint32(28+y.length+T.length,w.data.length,!1),b.set(w.data,32+y.length+T.length);const x=ac(b);l("METADATA_BLOCK_PICTURE",x)}}break;case"raw":break;default:ge(g)}if(e.raw)for(const g in e.raw){const m=e.raw[g]??e.raw[g.toLowerCase()];g==="vendor"||m==null||c.has(g)||typeof m=="string"&&l(g,m)}const d=new Uint8Array(4);q(d).setUint32(0,c.size,!0),i.splice(2,0,d);const u=i.reduce((g,m)=>g+m.length,0),h=new Uint8Array(u);let f=0;for(const g of i)h.set(g,f),f+=g.length;return h},Br=[2,1,2,3,3,4,4,5],Da=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new K(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),s=e.readBits(5);if(s>8)return null;const n=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(i/2);return{fscod:t,bsid:s,bsmod:n,acmod:a,lfeon:o,bitRateCode:c}},$c=[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],Yc=1536,zi=new Uint8Array([5,4,65,67,45,51]),Di=new Uint8Array([5,4,69,65,67,51]),Ua=[1,2,3,6],Oa=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new K(r);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const i=e.readBits(11),s=e.readBits(2);let n=0,a;s===3?(n=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 d=Ua[a];let u;return s<3?u=hs[s]/1e3:u=Ia[n]/1e3,{dataRate:Math.round((i+1)*u/(d*16)),substreams:[{fscod:s,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Zc=r=>{if(r.length<2)return null;const e=new K(r),t=e.readBits(13),i=e.readBits(3),s=[];for(let n=0;n<=i&&!(Math.ceil(e.pos/8)+3>r.length);n++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),l=e.readBits(3),d=e.readBits(1);e.skipBits(3);const u=e.readBits(4);let h=0;u>0?h=e.readBits(9):e.skipBits(1),s.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:d,numDepSub:u,chanLoc:h})}return s.length===0?null:{dataRate:t,substreams:s}},Na=r=>{const e=r.substreams[0];return p(e),e.fscod<3?hs[e.fscod]:e.fscod2!==null&&e.fscod2<3?Ia[e.fscod2]:null},La=r=>{const e=r.substreams[0];p(e);let t=Br[e.acmod]+e.lfeon;if(e.numDepSub>0){const i=[2,2,1,1,2,2,2,1,1];for(let s=0;s<9;s++)e.chanLoc&1<<8-s&&(t+=i[s])}return t};/*! 26 * Copyright (c) 2026-present, Vanilagy and contributors 27 * 28 * This Source Code Form is subject to the terms of the Mozilla Public 29 * License, v. 2.0. If a copy of the MPL was not distributed with this 30 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 31 */class lt{constructor(e){this.input=e}dispose(){}}/*! 32 * Copyright (c) 2026-present, Vanilagy and contributors 33 * 34 * This Source Code Form is subject to the terms of the Mozilla Public 35 * License, v. 2.0. If a copy of the MPL was not distributed with this 36 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 37 */const Wa=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isQuickTime?"quicktime":"mp4");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},Va=r=>{const e=q(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const s=Gs(r.subarray(t,t+16));t+=16;let n=null;if(i>0){const o=e.getUint32(t);if(t+=4,o>0){n=[];for(let c=0;c<o;c++)n.push(Gs(r.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:s,keyIds:n,data:r.slice(t,t+a)}},Ha=(r,e)=>r.systemId===e.systemId&&ua(r.data,e.data);/*! 38 * Copyright (c) 2026-present, Vanilagy and contributors 39 * 40 * This Source Code Form is subject to the terms of the Mozilla Public 41 * License, v. 2.0. If a copy of the MPL was not distributed with this 42 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 43 */const Je=8,Ct=16,mt=r=>{let e=F(r);const t=te(r,4);let i=8;e===1&&(e=Ce(r),i=16);const n=e-i;return n<0?null:{name:t,totalSize:e,headerSize:i,contentSize:n}}
43,bt=r=>Et(r)/65536,_s=r=>Et(r)/1073741824,Cs=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=M(r);if(e|=i&127,(i&128)===0)break}return e},Ve=r=>{let e=re(r);return r.skip(2),e=Math.min(e,r.remainingLength),xe.decode(D(r,e))},Jc=r=>{const e=mt(r);if(!e||e.name!=="data"||r.remainingLength<8)return null;const t=F(r);r.skip(4);const i=D(r,e.contentSize-8);switch(t){case 1:return xe.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Qt(i,"image/jpeg");case 14:return new Qt(i,"image/png");case 27:return new Qt(i,"image/bmp");default:return i}};/*! 44 * Copyright (c) 2026-present, Vanilagy and contributors 45 * 46 * This Source Code Form is subject to the terms of the Mozilla Public 47 * License, v. 2.0. If a copy of the MPL was not distributed with this 48 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 49 */const Ke=16,Qe=new Uint32Array(256),Ot=new Uint32Array(256),Nt=new Uint32Array(256),Lt=new Uint32Array(256),Wt=new Uint32Array(256),ue=new Uint32Array(256),qa=new Uint32Array(10);let Ka=!1;const el=()=>{const r=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let n=0,a=1;n<256;n++)t[n]=a,e[a]=n,a=a^a<<1^(a&128?283:0);const i=(n,a)=>n&&a?t[(e[n]+e[a])%255]:0;r[0]=99;for(let n=1;n<256;n++){const a=t[255-e[n]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,r[n]=o}for(let n=0;n<256;n++){const a=r[n],o=r.indexOf(n);Qe[n]=a<<24|a<<16|a<<8|a,ue[n]=o<<24|o<<16|o<<8|o;const c=i(o,14),l=i(o,9),d=i(o,13),u=i(o,11),h=c<<24|l<<16|d<<8|u;Ot[n]=h,Nt[n]=h>>>8|h<<24,Lt[n]=h>>>16|h<<16,Wt[n]=h>>>24|h<<8}let s=1;for(let n=0;n<10;n++)qa[n]=s<<24,s=s<<1^(s&128?283:0);Ka=!0};class Ga{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Ke/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Ke),this.out=new Uint8Array(Ke),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){p(e.byteLength===16),p(t.byteLength===16),Ka||el();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=s.getUint32(0,!1),this.iv[1]=s.getUint32(4,!1),this.iv[2]=s.getUint32(8,!1),this.iv[3]=s.getUint32(12,!1);for(let n=4;n<44;n+=4){const a=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^Qe[a>>>16&255]&4278190080^Qe[a>>>8&255]&16711680^Qe[a>>>0&255]&65280^Qe[a>>>24&255]&255^qa[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,a=40;n<a;n+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[n+o];this.roundkey[n+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let n=4;n<40;n+=4)for(let a=0;a<4;a++){const o=this.roundkey[n+a];this.roundkey[n+a]=Ot[Qe[o>>>24&255]&255]^Nt[Qe[o>>>16&255]&255]^Lt[Qe[o>>>8&255]&255]^Wt[Qe[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],s=this.inView.getUint32(12,!1)^this.roundkey[3];const n=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,d,u,h;for(let k=1;k<10;k++){const y=k*4;l=Ot[e>>>24]^Nt[s>>>16&255]^Lt[i>>>8&255]^Wt[t&255]^this.roundkey[y],d=Ot[t>>>24]^Nt[e>>>16&255]^Lt[s>>>8&255]^Wt[i&255]^this.roundkey[y+1],u=Ot[i>>>24]^Nt[t>>>16&255]^Lt[e>>>8&255]^Wt[s&255]^this.roundkey[y+2],h=Ot[s>>>24]^Nt[i>>>16&255]^Lt[t>>>8&255]^Wt[e&255]^this.roundkey[y+3],e=l,t=d,i=u,s=h}const f=ue[e>>>24&255]&4278190080^ue[s>>>16&255]&16711680^ue[i>>>8&255]&65280^ue[t>>>0&255]&255^this.roundkey[40],g=ue[t>>>24&255]&4278190080^ue[e>>>16&255]&16711680^ue[s>>>8&255]&65280^ue[i>>>0&255]&255^this.roundkey[41],m=ue[i>>>24&255]&4278190080^ue[t>>>16&255]&16711680^ue[e>>>8&255]&65280^ue[s>>>0&255]&255^this.roundkey[42],w=ue[s>>>24&255]&4278190080^ue[i>>>16&255]&16711680^ue[t>>>8&255]&65280^ue[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,g^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,w^this.iv[3],!1),this.iv[0]=n,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const tl=(r,e,t)=>{let i=!1,s=0;const n=2**16,a=16,o=new Ga;return new ReadableStream({pull:async c=>{i||(o.init(await e()),i=!0);const l=n+a;
49let d=r.requestSliceRange(s,0,l);if(d instanceof Promise&&(d=await d),!d||d.length===0)throw new Error("Invalid ciphertext.");const u=d.length;if(u%16!==0)throw new Error("Invalid ciphertext.");const h=u===l?u-a:u,f=D(d,h),g=new Uint8Array(h);for(let m=0;m<h;m+=16)o.in.set(f.subarray(m,m+16)),o.decrypt(),g.set(o.out,m);if(h<u)c.enqueue(g),s+=h;else{const m=g[h-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const w=g.subarray(0,h-m);c.enqueue(w),c.close(),t()}},cancel:()=>{t()}})};/*! 50 * Copyright (c) 2026-present, Vanilagy and contributors 51 * 52 * This Source Code Form is subject to the terms of the Mozilla Public 53 * License, v. 2.0. If a copy of the MPL was not distributed with this 54 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 55 */class Rr extends lt{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.psshBoxes=[],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(i=>i.getDecoderConfig().then(s=>s?.codec??null)));return Wa({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(i=>i.info?.type==="video"),hasAudio:this.tracks.some(i=>i.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,Je,Ct);if(i instanceof Promise&&(i=await i),!i)break;const s=e,n=mt(i);if(!n)break;if(n.name==="ftyp"||n.name==="styp"){const a=te(i,4);this.isQuickTime=a==="qt "}else if(n.name==="moov"){let a=this.reader.requestSlice(i.filePos,n.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>s+n.totalSize;break}else if(n.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!==Rr)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(p(c.info),c.info.type==="video"&&c.info.width!==-1){const l=c;c.trackBacking=new rn(l),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){const l=c;c.trackBacking=new nn(l),this.tracks.push(c)}}}t=!1;break}e=s+n.totalSize}if(t){p(this.reader.fileSize!==null);let i=this.reader.requestSlice(this.reader.fileSize-4,4);i instanceof Promise&&(i=await i),p(i);const s=F(i),n=this.reader.fileSize-s;if(n>=0&&n<=this.reader.fileSize-Ct){let a=this.reader.requestSliceRange(n,Je,Ct);if(a instanceof Promise&&(a=await a),a){const o=mt(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){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;p(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ot.includes(e.info.codec)&&t.sampleC
55ompositionTimeOffsets.length===0){p(e.info?.type==="audio");const n=Ue(e.info.codec),a=[],o=[];for(let c=0;c<t.sampleToChunk.length;c++){const l=t.sampleToChunk[c],d=t.sampleToChunk[c+1],u=(d?d.startChunkIndex:t.chunkOffsets.length)-l.startChunkIndex;for(let h=0;h<u;h++){const f=l.startSampleIndex+h*l.samplesPerChunk,g=f+l.samplesPerChunk,m=G(t.sampleTimingEntries,f,C=>C.startIndex),w=t.sampleTimingEntries[m],k=G(t.sampleTimingEntries,g,C=>C.startIndex),y=t.sampleTimingEntries[k],T=w.startDecodeTimestamp+(f-w.startIndex)*w.delta,P=y.startDecodeTimestamp+(g-y.startIndex)*y.delta-T,x=ce(a);x&&x.delta===P?x.count++:a.push({startIndex:l.startChunkIndex+h,startDecodeTimestamp:T,count:1,delta:P});const I=l.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;o.push(I)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const n of t.sampleTimingEntries)for(let a=0;a<n.count;a++)t.presentationTimestamps.push({presentationTimestamp:n.startDecodeTimestamp+a*n.delta,sampleIndex:n.startIndex+a});for(const n of t.sampleCompositionTimeOffsets)for(let a=0;a<n.count;a++){const o=n.startIndex+a,c=t.presentationTimestamps[o];c&&(c.presentationTimestamp+=n.offset)}t.presentationTimestamps.sort((n,a)=>n.presentationTimestamp-a.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let n=0;n<t.presentationTimestamps.length;n++)t.presentationTimestampIndexMap[t.presentationTimestamps[n].sampleIndex]=n}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,Je,Ct);t instanceof Promise&&(t=await t),p(t);const i=mt(t);p(i?.name==="moof");let s=this.reader.requestSlice(e,i.totalSize);s instanceof Promise&&(s=await s),p(s),this.traverseBox(s);const n=this.lastReadFragment;p(n&&n.moofOffset===e);for(const[,a]of n.trackData){const o=a.track,{fragmentPositionCache:c}=o;if(!a.startTimestampIsFinal){const d=o.fragmentLookupTable.find(u=>u.moofOffset===n.moofOffset);if(d)Is(a,d.timestamp);else{const u=G(c,n.moofOffset-1,h=>h.moofOffset);if(u!==-1){const h=c[u];Is(a,h.endTimestamp)}}a.startTimestampIsFinal=!0}const l=G(c,a.startTimestamp,d=>d.startTimestamp);if((l===-1||c[l].moofOffset!==n.moofOffset)&&c.splice(l+1,0,{moofOffset:n.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const d=await ja(this.reader,o.encryptionInfo,a.encryptionAuxInfo);for(let u=0;u<Math.min(a.samples.length,d.length);u++){const h=d[u];a.samples[u].encryption=h}}}return n}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Je&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Je;){const i=e.filePos,s=mt(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=i+s.totalSize}}traverseBox(e){const t=e.filePos,i=mt(e);if(!i)return!1;const s=e.filePos,n=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mvhd":{const a=M(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=F(e),this.movieDurationInTimescale=Ce(e)):(e.skip(8),this.movieTimescale=F(e),this.movieDurationInTimescale=F(e))}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...ct,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:le,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=a,this.readContiguousBoxes(e.slice(s,i.contentSize)),a.id!==-1&&a.timescale!==-1&&a.info!==null){if(a.info.type==="video"&&a.info.width!==-1){const o=a;a.trackBacking=new rn(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new nn(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=M(e),l=!!($e(e)&1);if(a.disposition.default=l,o===0)e.skip(8),a.id=F(e),e.skip(4),a.durationInMovieTimescale=F(e);else if(o===1)e.skip(16),a.id=F(e),e.skip(4),a.durationInMovieTimescale=Ce(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const d=[bt(e),bt(e),_s(e),bt(e),bt(e),_s(e),bt(e),bt(e),_s(e)],u=yi(oc(nl(d),90));p(u===0||u===90||u===180||u===270),a.rotation=u}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=M(e);e.skip(3);let c=!1,l=0;const d=F(e);for(let u=0;u<d;u++){const h=o===1?Ce(e):F(e),f=o===1?yu(e):Et(e),g=bt(e);if(h!==0){if(c){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(f===-1){l+=h;continue}if(g!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=f,c=!0}}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=M(e);e.skip(3),o===0?(e.skip(8),a.timescale=F(e),a.durationInMediaTimescale=F(e)):o===1&&(e.skip(16),a.timescale=F(e),a.durationInMediaTimescale=Ce(e));let c=re(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;wi(a.languageCode)||(a.languageCode=le)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=te(e,4);o==="vide"?a.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}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,i.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=M(e);e.skip(3);const c=F(e);for(let l=0;l<c;l++){const d=e.filePos,u=mt(e);if(!u)break;a.internalCodecId=u.name;const h=u.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=re(e),a.info.height=re(e),a.info.squarePixelWidth=a.info.width,a.info.squarePixelHeight=a.info.height,e.skip(50),a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));const f=h==="encv"?a.frmaCodecString:h;a.frmaCodecString=null,f==="avc1"||f==="avc3"?(a.info.codec="avc",a.info.avcType=f==="avc1"?1:3):f==="hvc1"||f==="hev1"?a.info.codec="hevc":f==="vp08"?a.info.codec="vp8":f==="vp09"?a.info.codec="vp9":f==="av01"?a.info.codec="av1":console.warn(f===null?"Unknown encrypted video codec due to missing frma box.":`Unsupported video codec (sample entry type '${u.name}').`)}else{e.skip(8);const f=re(e);e.skip(6);let g=re(e),m=re(e);e.skip(4);let w=F(e)/65536,k=null;o===0&&f>0&&(f===1?(e.skip(4),m=8*F(e),e.skip(8)):f===2&&(e.skip(4),w=Mo(e),g=F(e),e.skip(4),m=F(e),k=F(e),e.skip(8))),a.info.numberOfChannels=g,a.info.sampleRate=w,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+u.totalSize-e.filePos));const y=h==="enca"?a.frmaCodecString:h;if(a.frmaCodecString=null,y!=="mp4a")if(y==="opus")a.info.codec="opus",a.info.sampleRate=ti;else if(y==="flac")a.info.codec="flac";else if(y==="ulaw")a.info.codec="ulaw";else if(y==="alaw")a.info.codec="alaw";else if(y==="ac-3")a.info.codec="ac3";else if(y==="ec-3")a.info.codec="eac3";else if(y==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${m}
55 for codec 'twos'.`),a.info.codec=null);else if(y==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(y==="raw ")a.info.codec="pcm-u8";else if(y==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(y==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(y==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(y==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(y==="ipcm"){const T=a.info.pcmSampleSize;a.info.pcmLittleEndian?T===16?a.info.codec="pcm-s16":T===24?a.info.codec="pcm-s24":T===32?a.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${T}.`),a.info.codec=null):T===16?a.info.codec="pcm-s16be":T===24?a.info.codec="pcm-s24be":T===32?a.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${T}.`),a.info.codec=null)}else if(y==="fpcm"){const T=a.info.pcmSampleSize;a.info.pcmLittleEndian?T===32?a.info.codec="pcm-f32":T===64?a.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${T}.`),a.info.codec=null):T===32?a.info.codec="pcm-f32be":T===64?a.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${T}.`),a.info.codec=null)}else if(y==="lpcm"&&k!==null){const T=m+7>>3,b=!!(k&1),P=!!(k&2),x=k&4?-1:0;m>0&&m<=64&&(b?m===32&&(a.info.codec=P?"pcm-f32be":"pcm-f32"):x&1<<T-1?T===1?a.info.codec="pcm-s8":T===2?a.info.codec=P?"pcm-s16be":"pcm-s16":T===3?a.info.codec=P?"pcm-s24be":"pcm-s24":T===4&&(a.info.codec=P?"pcm-s32be":"pcm-s32"):T===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&console.warn("Unsupported PCM format.")}else console.warn(y===null?"Unknown encrypted audio codec due to missing frma box.":`Unsupported audio codec (sample entry type '${u.name}').`)}e.filePos=d+u.totalSize}}break;case"frma":{const a=this.currentTrack;if(!a)break;const c=te(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=te(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=M(e);e.skip(3),e.skip(1);const c=M(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=M(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=M(e),a.encryptionInfo.defaultKid=Gs(D(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const l=M(e),d=new Uint8Array(16);d.set(D(e,l),0),a.encryptionInfo.defaultConstantIv=d}}break;case"avcC":{const a=this.currentTrack;if(!a)break;p(a.info),a.info.codecDescription=D(e,i.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a)break;p(a.info),a.info.codecDescription=D(e,i.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(4);const o=M(e),c=M(e),l=M(e),d=l>>4,u=l>>1&7,h=l&1,f=M(e),g=M(e),m=M(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:d,chromaSubsampling:u,videoFullRangeFlag:h,colourPrimaries:f,transferCharacteristics:g,matrixCoefficients:m}}break;case"av1C":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(1);const o=M(e),c=o>>5,l=o&31,d=M(e),u=d>>7,h=d>>6&1,f=d>>5&1,g=d>>4&1,m=d>>3&1,w=d>>2&1,k=d&3,y=c===2&&h?f?12:10:h?10:8;a.info.av1CodecInfo={profile:c,level:l,tier:u,bitDepth:y,monochrome:g,chromaSubsamplingX:m,chromaSubsamplingY:w,chromaSamplePosition:k}}break;case"colr":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video");const o=te(e,4);if(o!=="nclx"&&o!=="nclc")break;const c=re(e),l=re(e),d=re(e);let u;o==="nclx"&&(u=!!(M(e)&128)),a.info.colorSpace={primaries:Qi[c],transfer:ji[l],matrix:Xi[d],fullRange:u}}break;case"pasp":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video");const o=F(e),c=F(e);o>0&&c>0&&(o>c?a.info.squarePixelWidth=Math.round(a.info.width*o/c):a.info.squarePixelHeight=Math.round(a.info.height*c/o))}break;case"wave":this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"esds":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);const o=M(e);p(o===3),Cs(e),e.skip(2);const c=M(e),l=(c&128)!==0,d=(c&64)!==0,u=(c&32)!==0;if(l&&e.skip(2),d){const w=M(e);e.skip(w)}u&&e.skip(2);const h=M(e);p(h===4);const f=Cs(e),g=e.filePos,m=M(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),f>e.filePos-g){const w=M(e);p(w===5);const k=Cs(e);if(a.info.codecDescription=D(e,k),a.info.codec==="aac"){const y=rs(a.info.codecDescription);y.numberOfChannels!==null&&(a.info.numberOfChannels=y.numberOfChannels),y.sampleRate!==null&&(a.info.sampleRate=y.sampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(re(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);const o=M(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=M(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(1);const o=M(e),c=re(e),l=F(e),d=dr(e),u=M(e);let h;u!==0?h=D(e,2+o):h=new Uint8Array(0);const f=new Uint8Array(19+h.byteLength),g=new DataView(f.buffer);g.setUint32(0,1332770163,!1),g.setUint32(4,1214603620,!1),g.setUint8(8,1),g.setUint8(9,o),g.setUint16(10,c,!0),g.setUint32(12,l,!0),g.setInt16(16,d,!0),g.setUint8(18,u),f.set(h,19),a.info.codecDescription=f,a.info.numberOfChannels=o}break;case"dfLa":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);const o=127,c=128,l=e.filePos;for(;e.filePos<n;){const g=M(e),m=$e(e);if((g&o)===st.STREAMINFO){e.skip(10);const k=F(e),y=k>>>12,T=(k>>9&7)+1;a.info.sampleRate=y,a.info.numberOfChannels=T,e.skip(20)}else e.skip(m);if(g&c)break}const d=e.filePos;e.filePos=l;const u=D(e,d-l),h=new Uint8Array(4+u.byteLength);
55new DataView(h.buffer).setUint32(0,1716281667,!1),h.set(u,4),a.info.codecDescription=h}break;case"dac3":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");const o=D(e,3),c=new K(o),l=c.readBits(2);c.skipBits(8);const d=c.readBits(3),u=c.readBits(1);l<3&&(a.info.sampleRate=hs[l]),a.info.numberOfChannels=Br[d]+u}break;case"dec3":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");const o=D(e,i.contentSize),c=Zc(o);if(!c){console.warn("Invalid dec3 box contents, ignoring.");break}const l=Na(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=La(c)}break;case"stts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e);let c=0,l=0;for(let d=0;d<o;d++){const u=F(e),h=F(e);a.sampleTable.sampleTimingEntries.push({startIndex:c,startDecodeTimestamp:l,count:u,delta:h}),c+=u,l+=u*h}}break;case"ctts":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e);let c=0;for(let l=0;l<o;l++){const d=F(e),u=Et(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:d,offset:u}),c+=d}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e),c=F(e);if(o===0)for(let l=0;l<c;l++){const d=F(e);a.sampleTable.sampleSizes.push(d)}else a.sampleTable.sampleSizes.push(o)}break;case"stz2":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),e.skip(3);const o=M(e),c=F(e),l=D(e,Math.ceil(c*o/8)),d=new K(l);for(let u=0;u<c;u++){const h=d.readBits(o);a.sampleTable.sampleSizes.push(h)}}break;case"stss":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4),a.sampleTable.keySampleIndices=[];const o=F(e);for(let c=0;c<o;c++){const l=F(e)-1;a.sampleTable.keySampleIndices.push(l)}a.sampleTable.keySampleIndices[0]!==0&&a.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e);for(let l=0;l<o;l++){const d=F(e)-1,u=F(e),h=F(e);a.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:d,samplesPerChunk:u,sampleDescriptionIndex:h})}let c=0;for(let l=0;l<a.sampleTable.sampleToChunk.length;l++)if(a.sampleTable.sampleToChunk[l].startSampleIndex=c,l<a.sampleTable.sampleToChunk.length-1){const u=a.sampleTable.sampleToChunk[l+1].startChunkIndex-a.sampleTable.sampleToChunk[l].startChunkIndex;c+=u*a.sampleTable.sampleToChunk[l].samplesPerChunk}}break;case"stco":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e);for(let c=0;c<o;c++){const l=F(e);a.sampleTable.chunkOffsets.push(l)}}break;case"co64":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=F(e);for(let c=0;c<o;c++){const l=Ce(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,i.contentSize));break;case"mehd":{const a=M(e);e.skip(3);const o=a===1?Ce(e):F(e);this.movieDurationInTimescale=o}break;case"trex":{e.skip(4);const a=F(e),o=F(e),c=F(e),l=F(e),d=F(e);this.fragmentTrackDefaults.push({trackId:a,defaultSampleDescriptionIndex:o,defaultSampleDuration:c,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{const a=M(e);e.skip(3);const o=F(e),c=this.tracks.find(y=>y.id===o);if(!c)break;const l=F(e),d=(l&48)>>4,u=(l&12)>>2,h=l&3,f=[M,re,$e,F],g=f[d],m=f[u],w=f[h],k=F(e);for(let y=0;y<k;y++){const T=a===1?Ce(e):F(e),b=a===1?Ce(e):F(e);g(e),m(e),w(e),c.fragmentLookupTable.push({timestamp:T,moofOffset:b})}c.fragmentLookupTable.sort((y,T)=>y.timestamp-T.timestamp);for(let y=0;y<c.fragmentLookupTable.length-1;y++){const T=c.fragmentLookupTable[y],b=c.fragmentLookupTable[y+1];T.timestamp===b.timestamp&&(c.fragmentLookupTable.splice(y+1,1),y--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(s,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(p(this.currentFragment),this.readContiguousBoxes(e.slice(s,i.contentSize)),this.currentTrack){const a=this.currentFragment.trackData.get(this.currentTrack.id);if(a){this.currentFragment.implicitBaseDataOffset=a.currentOffset,a.presentationTimestamps=a.samples.map((d,u)=>({presentationTimestamp:d.presentationTimestamp,sampleIndex:u})).sort((d,u)=>d.presentationTimestamp-u.presentationTimestamp);for(let d=0;d<a.presentationTimestamps.length;d++){const u=a.presentationTimestamps[d],h=a.samples[u.sampleIndex];if(a.firstKeyFrameTimestamp===null&&h.isKeyFrame&&(a.firstKeyFrameTimestamp=h.presentationTimestamp),d<a.presentationTimestamps.length-1){const g=a.presentationTimestamps[d+1].presentationTimestamp-u.presentationTimestamp;h.duration=g}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[ce(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:l}=this.currentTrack;p(l),l.startTimestamp!==null&&(Is(a,l.startTimestamp),a.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!a.samples[0].encryption&&(a.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const a=Va(D(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.pss
55hBoxes.push(a)}break;case"tfhd":{p(this.currentFragment),e.skip(1);const a=$e(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),d=!!(a&16),u=!!(a&32),h=!!(a&65536),f=!!(a&131072),g=F(e),m=this.tracks.find(k=>k.id===g);if(!m)break;const w=this.fragmentTrackDefaults.find(k=>k.trackId===g);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:w?.defaultSampleDescriptionIndex??null,defaultSampleDuration:w?.defaultSampleDuration??null,defaultSampleSize:w?.defaultSampleSize??null,defaultSampleFlags:w?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=Ce(e):f&&(m.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),c&&(m.currentFragmentState.sampleDescriptionIndex=F(e)),l&&(m.currentFragmentState.defaultSampleDuration=F(e)),d&&(m.currentFragmentState.defaultSampleSize=F(e)),u&&(m.currentFragmentState.defaultSampleFlags=F(e)),h&&(m.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const a=this.currentTrack;if(!a)break;p(a.currentFragmentState);const o=M(e);e.skip(3);const c=o===0?F(e):Ce(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;p(this.currentFragment),p(a.currentFragmentState);const o=M(e),c=$e(e),l=!!(c&1),d=!!(c&4),u=!!(c&256),h=!!(c&512),f=!!(c&1024),g=!!(c&2048),m=F(e);let w=null;l&&(w=Et(e));let k=null;d&&(k=F(e));let y;if(this.currentFragment.trackData.has(a.id)?(y=this.currentFragment.trackData.get(a.id),w!==null&&(y.currentOffset=a.currentFragmentState.baseDataOffset+w)):(y={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(w??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,y)),m===0){this.currentFragment.implicitBaseDataOffset=y.currentOffset;break}for(let T=0;T<m;T++){let b;u?b=F(e):(p(a.currentFragmentState.defaultSampleDuration!==null),b=a.currentFragmentState.defaultSampleDuration);let P;h?P=F(e):(p(a.currentFragmentState.defaultSampleSize!==null),P=a.currentFragmentState.defaultSampleSize);let x;f?x=F(e):(p(a.currentFragmentState.defaultSampleFlags!==null),x=a.currentFragmentState.defaultSampleFlags),T===0&&k!==null&&(x=k);let I=0;g&&(o===0?I=F(e):I=Et(e));const C=!(x&65536);y.samples.push({presentationTimestamp:y.currentTimestamp+I,duration:b,byteOffset:y.currentOffset,byteSize:P,isKeyFrame:C,encryption:null}),y.currentOffset+=P,y.currentTimestamp+=b}}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),$e(e)&1){const h=te(e,4),f=F(e);if(h!==a.encryptionInfo.scheme||f!==0)break}const c=M(e),l=F(e);let d=null;c===0&&l>0&&(d=D(e,l));const u=on(a);u.defaultSampleInfoSize=c,u.sampleSizes=d,u.sampleCount=l}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=M(e);if($e(e)&1){const h=te(e,4),f=F(e);if(h!==a.encryptionInfo.scheme||f!==0)break}const l=F(e);if(l===0)break;l>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let d=o===0?F(e):Number(Ce(e));this.currentFragment&&(d+=this.currentFragment.moofOffset);const u=on(a);u.offset=d}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;p(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const l=!!($e(e)&2),d=F(e),u=a.encryptionInfo.defaultPerSampleIvSize;p(u!==null);for(let h=0;h<Math.min(d,o.samples.length);h++){const f=new Uint8Array(16);u>0?f.set(D(e,u),0):f.set(a.encryptionInfo.defaultConstantIv,0);let g=null;if(l){const w=re(e);g=[];for(let k=0;k<w;k++){const y=re(e),T=F(e);g.push({clearLen:y,protectedLen:T})}}const m=o.samples[h];m.encryption={iv:f,subsamples:g}}}break;case"udta":{const a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(const{boxInfo:o,slice:c}of a){if(o.name!=="meta"&&!this.currentTrack){const l=c.filePos;this.metadataTags.raw??={},o.name[0]==="©"?this.metadataTags.raw[o.name]??=Ve(c):this.metadataTags.raw[o.name]??=D(c,o.contentSize),c.filePos=l}switch(o.name){case"meta":c.skip(-o.headerSize),this.traverseBox(c);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=xe.decode(D(c,o.contentSize)):this.metadataTags.title??=Ve(c);break;case"©des":this.currentTrack||(this.metadataTags.description??=Ve(c));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=Ve(c));break;case"©alb":this.currentTrack||(this.metadataTags.album??=Ve(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Ve(c));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=Ve(c));break;case"©day":if(!this.currentTrack){const l=new Date(Ve(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=Ve(c));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=Ve(c));break}}}break;case"meta":{if(this.currentTrack)break;const o=F(e)!==0;this.currentMetadataKeys=new Map,o?this.readContiguousBoxes(e.slice(s,i.contentSize)):this.readContiguousBoxes(e.slice(s+4,
55i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const a=F(e);for(let o=0;o<a;o++){const c=F(e);e.skip(4);const l=xe.decode(D(e,c-8));this.currentMetadataKeys.set(o+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const a=this.iterateContiguousBoxes(e.slice(s,i.contentSize));for(const{boxInfo:o,slice:c}of a){let l=o.name;const d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));const u=Jc(c);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=u,l){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof u=="string"&&(this.metadataTags.title??=u);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof u=="string"&&(this.metadataTags.description??=u);break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof u=="string"&&(this.metadataTags.artist??=u);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof u=="string"&&(this.metadataTags.album??=u);break;case"aART":case"album_artist":typeof u=="string"&&(this.metadataTags.albumArtist??=u);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof u=="string"&&(this.metadataTags.comment??=u);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof u=="string"&&(this.metadataTags.genre??=u);break;case"©lyr":case"lyrics":typeof u=="string"&&(this.metadataTags.lyrics??=u);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof u=="string"){const h=new Date(u);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"covr":case"com.apple.quicktime.artwork":u instanceof Qt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:u.data,kind:"coverFront",mimeType:u.mimeType})):u instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:u,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof u=="string"){const h=u.split("/"),f=Number.parseInt(h[0],10),g=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"trkn":if(u instanceof Uint8Array&&u.length>=6){const h=q(u),f=h.getUint16(2,!1),g=h.getUint16(4,!1);f>0&&(this.metadataTags.trackNumber??=f),g>0&&(this.metadataTags.tracksTotal??=g)}break;case"disc":case"disk":if(u instanceof Uint8Array&&u.length>=6){const h=q(u),f=h.getUint16(2,!1),g=h.getUint16(4,!1);f>0&&(this.metadataTags.discNumber??=f),g>0&&(this.metadataTags.discsTotal??=g)}break}}}break}return e.filePos=n,!0}}class Xa{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 i=0;for(const s of e.tracks)if(s.trackBacking.getType()===t&&i++,s===this.internalTrack)break;return i}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;return e.durationInMediaTimescale<=0?null:(p(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}
55async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,i=>i.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ti(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=er(s,i),a=await this.fetchPacketForSampleIndex(n,t);return!an(s)||!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=G(c.presentationTimestamps,i,h=>h.presentationTimestamp),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&i<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},i,i,t)}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);const s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){const a=n.trackData.get(this.internalTrack.id);if(s.sampleIndex+1<a.samples.length)return{sampleIndex:s.sampleIndex+1,correctSampleFound:!0}}else if(n.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 i=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=il(s,i),a=await this.fetchPacketForSampleIndex(n,t);return!an(s)||!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=ns(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=i),d=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,u=l!==-1&&i<c.endTimestamp;return{sampleIndex:d,correctSampleFound:u}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0){const n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=rl(n,i);return this.fetchPacketForSampleIndex(a,t)}const s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){const o=n.trackData.get(this.internalTrack.id).samples.findIndex((c,l)=>c.isKeyFrame&&l>s.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return p(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 i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=sl(i,e);if(!s)return null;let n;if(t.metadataOnly)n=Oe;else{let l=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);if(l instanceof Promise&&(l=await l),!l)return null;if(n=D(l,s.sampleSize),this.internalTrack.encryptionAuxInfo){p(this.internalTrack.encryptionInfo);const d=await ja(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<d.length&&(n=await cn(this.internalTrack,d[e],n,null))}}const a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,c=new ee(n,s.isKeyFrame?"key":"delta",a,o,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).samples[t];p(n);let a;if(i.metadataOnly)a=Oe;else{let d=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(d instanceof Promise&&(d=await d),!d)return null;a=D(d,n.byteSize),n.encryption&&(a=await cn(this.internalTrack,n.encryption,a,e))}const o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,l=ne
55w ee(a,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,i,s,n){const a=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:w,correctSampleFound:k}=t(e);if(k)return this.fetchPacketInFragment(e,w,n);w!==-1&&(c=e,l=w)}const d=G(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),u=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,h=G(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),f=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,g=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null;let m;for(e?g===null||e.moofOffset>=g?(m=e.moofOffset+e.moofSize,o=e):m=g:m=g??0;;){if(o){const T=o.trackData.get(this.internalTrack.id);if(T&&T.startTimestamp>s)break}let w=a.reader.requestSliceRange(m,Je,Ct);if(w instanceof Promise&&(w=await w),!w)break;const k=m,y=mt(w);if(!y)break;if(y.name==="moof"){o=await a.readFragment(k);const{sampleIndex:T,correctSampleFound:b}=t(o);if(b)return this.fetchPacketInFragment(o,T,n);T!==-1&&(c=o,l=T)}m=k+y.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){const w=this.internalTrack.fragmentLookupTable[d-1];p(!w||w.timestamp<u.timestamp);const k=w?.timestamp??-1/0;return this.performFragmentedLookup(null,t,k,s,n)}return c?this.fetchPacketInFragment(c,l,n):null}}class rn extends Xa{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(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}
55async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&Ba(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&Ma(t.data)}const e={codec:kr(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 nn extends Xa{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??={codec:wr(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const er=(r,e)=>{if(r.presentationTimestamps){const t=G(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=G(r.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},il=(r,e)=>{if(!r.keySampleIndices)return er(r,e);if(r.presentationTimestamps){const t=G(r.presentationTimestamps,e,i=>i.presentationTimestamp);if(t===-1)return-1;for(let i=t;i>=0;i--){const s=r.presentationTimestamps[i].sampleIndex;if(Ei(r.keySampleIndices,s,a=>a)!==-1)return s}return-1}else{const t=er(r,e),i=G(r.keySampleIndices,t,s=>s);return r.keySampleIndices[i]??-1}},sl=(r,e)=>{const t=G(r.sampleTimingEntries,e,k=>k.startIndex),i=r.sampleTimingEntries[t];if(!i||i.startIndex+i.count<=e)return null;let n=i.startDecodeTimestamp+(e-i.startIndex)*i.delta;const a=G(r.sampleCompositionTimeOffsets,e,k=>k.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(n+=o.offset);const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=G(r.sampleToChunk,e,k=>k.startSampleIndex),d=r.sampleToChunk[l];p(d);const u=d.startChunkIndex+Math.floor((e-d.startSampleIndex)/d.samplesPerChunk),h=r.chunkOffsets[u],f=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk;let g=0,m=h;if(r.sampleSizes.length===1)m+=c*(e-f),g+=c*d.samplesPerChunk;else for(let k=f;k<f+d.samplesPerChunk;k++){const y=r.sampleSizes[k];k<e&&(m+=y),g+=y}let w=i.delta;if(r.presentationTimestamps){const k=r.presentationTimestampIndexMap[e];p(k!==void 0),k<r.presentationTimestamps.length-1&&(w=r.presentationTimestamps[k+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:w,sampleOffset:m,sampleSize:c,chunkOffset:h,chunkSize:g,isKeyFrame:r.keySampleIndices?Ei(r.keySampleIndices,e,k=>k)!==-1:!0}},rl=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=G(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Is=(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},nl=r=>{const[e,t]=r,i=Math.atan2(t,e);return Number.isFinite(i)?i*(180/Math.PI):0},an=r=>r.sampleSizes.length===0,on=r=>r.currentFragmentState?r.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:r.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleC
55ount:0,offset:null,resolved:null},ja=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 i=0;if(t.defaultSampleInfoSize>0)i=t.defaultSampleInfoSize*t.sampleCount;else{p(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let s=r.requestSlice(t.offset,i);if(s instanceof Promise&&(s=await s),!s)throw new Error("Failed to read auxiliary encryption info.");const n=e.defaultPerSampleIvSize;p(n!==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);n>0?l.set(D(s,n),0):l.set(e.defaultConstantIv,0);let d=null;if(c>n){const u=re(s);d=[];for(let h=0;h<u;h++){const f=re(s),g=F(s);d.push({clearLen:f,protectedLen:g})}}a.push({iv:l,subsamples:d})}return t.resolved=a,a},cn=async(r,e,t,i)=>{p(r.encryptionInfo);const s=r.encryptionInfo;p(s.defaultKid!==null);const n=s.defaultKid;let a;const o=r.demuxer.decryptionKeyCache.get(n);if(o)a=await o;else{if(!r.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const c=(async()=>{let l=r.demuxer.psshBoxes;if(i){l=[...l,...i.psshBoxes].filter(u=>u.keyIds===null||u.keyIds.includes(n));for(let u=0;u<l.length-1;u++)for(let h=u+1;h<l.length;h++)Ha(l[u],l[h])&&(l.splice(h,1),h--)}const d=await r.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:n,psshBoxes:l});if(!(typeof d=="string"&&d.length===32&&cc.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:lc(d)})();r.demuxer.decryptionKeyCache.set(n,c),a=await c}return s.scheme==="cenc"||s.scheme==="cens"?al(a,s,e,t):ol(a,s,e,t)},al=async(r,e,t,i)=>{const s=new Uint8Array(16);s.set(t.iv,0);const n=await crypto.subtle.importKey("raw",r,{name:"AES-CTR"},!1,["decrypt"]),a=async g=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,g);return new Uint8Array(m)};if(!t.subsamples)return a(i);p(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=Qa(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const g of o)for(const m of g.perSubsample)c+=m.length;const l=new Uint8Array(c);let d=0;for(const g of o)for(const m of g.perSubsample)l.set(i.subarray(m.offset,m.offset+m.length),d),d+=m.length;const u=await a(l),h=new Uint8Array(i);let f=0;for(const g of o)for(const m of g.perSubsample)h.set(u.subarray(f,f+m.length),m.offset),f+=m.length;return h},ol=(r,e,t,i)=>{const s=new Ga;s.init({key:r,iv:t.iv});const n=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(p(n!==null&&a!==null),!t.subsamples){const d=new Uint8Array(i),u=Math.floor(i.length/16);for(let h=0;h<u;h++){const f=h*16;s.in.set(i.subarray(f,f+16)),s.decrypt(),d.set(s.out,f)}return d}if(n===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(i),c=Qa(t.subsamples,n,a),l=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const d of c){s.iv[0]=l.getUint32(0,!1),s.iv[1]=l.getUint32(4,!1),s.iv[2]=l.getUint32(8,!1),s.iv[3]=l.getUint32(12,!1);for(const u of d.perSubsample){const h=u.length/16;for(let f=0;f<h;f++){const g=u.offset+f*16;s.in.set(i.subarray(g,g+16)),s.decrypt(),o.set(s.out,g)}}}return o},Qa=(r,e,t)=>{const i=[],s=e!==0||t!==0;let n=0;for(const a of r){n+=a.clearLen;const o=[];if(!s)a.protectedLen>0&&o.push({offset:n,length:a.protectedLen}),n+=a.protectedLen;else{let c=a.protectedLen,l=n;for(;c>0&&!(c<16*e);){const d=16*e;o.push({offset:l,length:d}),l+=d,c-=d;const u=Math.min(16*t,c);l+=u,c-=u}n+=a.protectedLen}i.push({perSubsample:o})}return i};/*! 56 * Copyright (c) 2026-present, Vanilagy and contributors 57 * 58 * This Source Code Form is subject to the terms of the Mozilla Public 59 * License, v. 2.0. If a copy of the MPL was not distributed with this 60 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 61 */class tr{constructor(e){this.value=e}}class ir{constructor(e){this.value=e}}class $a{constructor(e){this.value=e}}class ht{constructor(e){this.value=e}}var S;(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
611934]="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"})(S||(S={}));const cl=[S.EBML,S.Segment],xi=[S.SeekHead,S.Info,S.Cluster,S.Tracks,S.Cues,S.Attachments,S.Chapters,S.Tags],qi=[...cl,...xi],ln=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,un=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,dn=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,ll=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 ul{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=ln(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=un(e)){let i=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(i++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=dn(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=ll(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}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(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){const n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,i),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??ln(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??un(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}
61else 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 tr)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof ir)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof $a){const t=e.size??dn(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof ht){const t=$.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else ge(e.data)}}const sr=8,Ie=2,et=2*sr,Ya=r=>{if(r.remainingLength<1)return null;const e=M(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},hi=r=>{if(r.remainingLength<1)return null;const e=M(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let s=e&i-1;for(let n=1;n<t;n++)s*=256,s+=M(r);return s},H=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=M(r);return t},dl=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(M(r));return t},Mr=r=>{const e=Ya(r);return e===null||r.remainingLength<e?null:H(r,e)},Za=r=>{if(r.remainingLength<1)return null;if(M(r)===255)return;r.skip(-1);const t=hi(r);if(t===null)return null;if(t!==72057594037927940)return t},Ze=r=>{p(r.remainingLength>=Ie);const e=Mr(r);if(e===null)return null;const t=Za(r);return t===null?null:{id:e,size:t}},Vt=(r,e)=>{const t=D(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},ni=(r,e)=>{const t=D(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return xe.decode(t.subarray(0,i))},Es=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?bu(r):Mo(r)},rr=async(r,e,t,i)=>{const s=new Set(t);let n=e;for(;i===null||n<i;){let a=r.requestSliceRange(n,Ie,et);if(a instanceof Promise&&(a=await a),!a)break;const o=Ze(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};ft(o.size),n=a.filePos+o.size}return{pos:i!==null&&i>n?i:n,found:!1}},Ja=async(r,e,t,i)=>{const n=new Set(t);let a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(o instanceof Promise&&(o=await o),!o||o.length<sr)break;for(let c=0;c<o.length-sr;c++){o.filePos=a;const l=Mr(o);if(l!==null&&n.has(l))return a;a++}}return null},ye={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 ft(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*! 62 * Copyright (c) 2026-present, Vanilagy and contributors 63 * 64 * This Source Code Form is subject to the terms of the Mozilla Public 65 * License, v. 2.0. If a copy of the MPL was not distributed with this 66 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 67 */const eo=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};/*! 68 * Copyright (c) 2026-present, Vanilagy and contributors 69 * 70 * This Source Code Form is subject to the terms of the Mozilla Public 71 * License, v. 2.0. If a copy of the MPL was not distributed with this 72 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 73 */var Ye;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(Ye||(Ye={}));var ts;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(ts||(ts={}));var pi;
73(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(pi||(pi={}));const As=[{id:S.SeekHead,flag:"seekHeadSeen"},{id:S.Info,flag:"infoSeen"},{id:S.Tracks,flag:"tracksSeen"},{id:S.Cues,flag:"cuesSeen"}],to=10*2**20;class hl extends lt{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(i=>i.getDecoderConfig().then(s=>s?.codec??null)));return eo({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(s=>s.info?.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??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Ie,et);if(t instanceof Promise&&(t=await t),!t)break;const i=Ze(t);if(!i)break;const s=i.id;let n=i.size;const a=t.filePos;if(s===S.EBML){ft(n);let o=this.reader.requestSlice(a,n);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===S.Segment){if(await this.readSegment(a,n),n===void 0||this.reader.fileSize===null)break}else if(s===S.Cluster){if(this.reader.fileSize===null)break;n===void 0&&(n=(await rr(this.reader,a,qi,this.reader.fileSize)).pos-a);const o=ce(this.segments);o&&(o.elementEndPos=a+n)}ft(n),e=a+n}})()}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 i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,Ie,et);if(o instanceof Promise&&(o=await o),!o)break;const c=i,l=Ze(o);if(!l||!xi.includes(l.id)&&l.id!==S.Void){const g=await Ja(this.reader,c,xi,Math.min(this.currentSegment.elementEndPos??1/0,c+to));if(g){i=g;continue}else break}const{id:d,size:u}=l,h=o.filePos,f=As.findIndex(g=>g.id===d);if(f!==-1){const g=As[f].flag;this.currentSegment[g]=!0,ft(u);let m=this.reader.requestSlice(h,u);m instanceof Promise&&(m=await m),m&&this.readContiguousElements(m)}else if(d===S.Tags||d===S.Attachments){d===S.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ft(u);let g=this.reader.requestSlice(h,u);g instanceof Promise&&(g=await g),g&&this.readContiguousElements(g)}else if(d===S.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(u===void 0)break;i=h+u}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=As.find(g=>g.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,Ie,et);if(l instanceof Promise&&(l=await l),!l)continue;const d=Ze(l);if(!d)continue;const{id:u,size:h}=d;if(u!==c.id)continue;ft(h),this.currentSegment[c.flag]=!0;let f=this.reader.requestSlice(l.filePos,h);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}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 s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=s.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],d=o.cuePoints[c+1];l.time===d.time&&(o.cuePoints.splice(c+1,1),c--)}}let n=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,Ie,et);i instanceof Promise&&(i=await i),p(i);const s=e,n=Ze(i);p(n);const a=n.id;p(a===S.Cluster);let o=n.size;const c=i.filePos;o===void 0&&(o=(await rr(this.reader,c,qi,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const d={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){const u=this.readContiguousElements(l,qi);d.elementEndPos=u}for(const[,u]of d.trackData){const h=u.track;p(u.blocks.length>0);let f=!1;for(let k=0;k<u.blocks.length;k++){const y=u.blocks[k];
73y.timestamp+=d.timestamp,f||=y.lacing!==Ye.None}u.presentationTimestamps=u.blocks.map((k,y)=>({timestamp:k.timestamp,blockIndex:y})).sort((k,y)=>k.timestamp-y.timestamp);for(let k=0;k<u.presentationTimestamps.length;k++){const y=u.presentationTimestamps[k],T=u.blocks[y.blockIndex];if(u.firstKeyFrameTimestamp===null&&T.isKeyFrame&&(u.firstKeyFrameTimestamp=T.timestamp),k<u.presentationTimestamps.length-1){const b=u.presentationTimestamps[k+1];T.duration=b.timestamp-T.timestamp}else T.duration===0&&h.defaultDuration!=null&&T.lacing===Ye.None&&(T.duration=h.defaultDuration)}f&&(this.expandLacedBlocks(u.blocks,h),u.presentationTimestamps=u.blocks.map((k,y)=>({timestamp:k.timestamp,blockIndex:y})).sort((k,y)=>k.timestamp-y.timestamp));const g=u.blocks[u.presentationTimestamps[0].blockIndex],m=u.blocks[ce(u.presentationTimestamps).blockIndex];u.startTimestamp=g.timestamp,u.endTimestamp=m.timestamp+m.duration;const w=G(h.clusterPositionCache,u.startTimestamp,k=>k.startTimestamp);(w===-1||h.clusterPositionCache[w].elementStartPos!==s)&&h.clusterPositionCache.splice(w+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=d,d}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const s=e.segment.tracks.find(n=>n.id===t);if(!s)return null;i={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.lacing===Ye.None)continue;s.decoded||(s.data=this.decodeBlockData(t,s.data),s.decoded=!0);const n=fe.tempFromBytes(s.data),a=[],o=M(n)+1;switch(s.lacing){case Ye.Xiph:{let l=0;for(let d=0;d<o-1;d++){let u=0;for(;n.bufferPos<n.length;){const h=M(n);if(u+=h,h<255){a.push(u),l+=u;break}}}a.push(n.length-(n.bufferPos+l))}break;case Ye.FixedSize:{const l=n.length-1,d=Math.floor(l/o);for(let u=0;u<o;u++)a.push(d)}break;case Ye.Ebml:{const l=hi(n);p(l!==null);let d=l;a.push(d);let u=d;for(let h=1;h<o-1;h++){const f=n.bufferPos,g=hi(n);p(g!==null);const m=g,k=(1<<(n.bufferPos-f)*7-1)-1,y=m-k;d+=y,a.push(d),u+=d}a.push(n.length-(n.bufferPos+u))}break;default:p(!1)}p(a.length===o),e.splice(i,1);const c=s.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){const d=a[l],u=D(n,d),h=s.timestamp+c*l/o,f=c/o;e.splice(i+l,0,{timestamp:h,duration:f,isKeyFrame:s.isKeyFrame,data:u,lacing:Ye.None,decoded:!0,mainAdditional:s.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===S.Tags&&!e.tagsSeen)){if(!(t.id===S.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Ie,et);if(i instanceof Promise&&(i=await i),!i)continue;const s=Ze(i);if(!s||s.id!==t.id)continue;const{size:n}=s;ft(n),p(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,n);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===S.Tags?e.tagsSeen=!0:t.id===S.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Ie;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Ze(e);if(!i||t&&t.includes(i.id))return!1;const{id:s,size:n}=i,a=e.filePos;switch(ft(n),s){case S.DocType:this.isWebM=Vt(e,n)==="webm";break;case S.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,n)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case S.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=H(e,n)}break;case S.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=H(e,n)}break;case S.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=H(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case S.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Es(e,n)}break;case S.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ct,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,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==ts.Block||o.data.algorithm!==pi.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 o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);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 d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,u=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>0&&u>
730&&(d>u?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/u):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*u/d))}this.currentTrack.codecId===ye.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ye.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.vp8?this.currentTrack.info.codec="vp8":c===ye.vp9?this.currentTrack.info.codec="vp9":c===ye.av1&&(this.currentTrack.info.codec="av1");const l=this.currentTrack;this.currentTrack.trackBacking=new fl(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===ye.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===ye.mp3?this.currentTrack.info.codec="mp3":c===ye.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ti):c===ye.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ye.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 l=this.currentTrack;this.currentTrack.trackBacking=new ml(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case S.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=H(e,n)}break;case S.TrackType:{if(!this.currentTrack)break;const o=H(e,n);o===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}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case S.FlagEnabled:{if(!this.currentTrack)break;H(e,n)||(this.currentTrack=null)}break;case S.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!H(e,n)}break;case S.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!H(e,n)}break;case S.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!H(e,n)}break;case S.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!H(e,n)}break;case S.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!H(e,n)}break;case S.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!H(e,n)}break;case S.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Vt(e,n)}break;
73case S.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=D(e,n)}break;case S.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=H(e,n)}break;case S.Name:{if(!this.currentTrack)break;this.currentTrack.name=ni(e,n)}break;case S.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Vt(e,n),wi(this.currentTrack.languageCode)||(this.currentTrack.languageCode=le)}break;case S.LanguageBCP47:{if(!this.currentTrack)break;const c=Vt(e,n).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=le,this.currentTrack.hasLanguageBcp47=!0}break;case S.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case S.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=H(e,n)}break;case S.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=H(e,n)}break;case S.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=H(e,n)}break;case S.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=H(e,n)}break;case S.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=H(e,n)}break;case S.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=H(e,n)===1}break;case S.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,n))}break;case S.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=H(e,n),c=Xi[o]??null;this.currentTrack.info.colorSpace.matrix=c}break;case S.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=H(e,n)===2}break;case S.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=H(e,n),c=ji[o]??null;this.currentTrack.info.colorSpace.transfer=c}break;case S.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const o=H(e,n),c=Qi[o]??null;this.currentTrack.info.colorSpace.primaries=c}break;case S.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case S.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Es(e,n);try{this.currentTrack.info.rotation=yi(c)}catch{}}break;case S.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case S.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Es(e,n)}break;case S.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=H(e,n)}break;case S.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=H(e,n)}break;case S.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case S.CueTime:this.currentCueTime=H(e,n);break;case S.CueTrackPositions:{if(this.currentCueTime===null)break;p(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,n)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case S.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=H(e,n)}break;case S.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;p(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+H(e,n)}break;case S.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=H(e,n)}break;case S.SimpleBlock:{if(!this.currentCluster)break;const o=hi(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=dr(e),d=M(e),u=d>>1&3;let h=!!(d&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);
73const f=D(e,n-(e.filePos-a)),g=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:f,lacing:u,decoded:!g,mainAdditional:null})}break;case S.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case S.Block:{if(!this.currentCluster)break;const o=hi(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=dr(e),u=M(e)>>1&3,h=D(e,n-(e.filePos-a)),f=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:u,decoded:!f,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case S.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case S.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case S.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=D(e,n)}break;case S.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=H(e,n)}break;case S.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=H(e,n)}break;case S.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case S.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case S.Targets:this.readContiguousElements(e.slice(a,n));break;case S.TargetTypeValue:H(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case S.TagTrackUID:case S.TagEditionUID:case S.TagChapterUID:case S.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case S.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case S.TagName:this.currentSimpleTagName=ni(e,n);break;case S.TagString:{if(!this.currentSimpleTagName)break;const o=ni(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case S.TagBinary:{if(!this.currentSimpleTagName)break;const o=D(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case S.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new _r(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const c=this.currentAttachedFile.fileName;let l="unknown";if(c){const d=c.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}o.images??=[],o.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case S.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=dl(e,n)}break;case S.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ni(e,n)}break;
73case S.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Vt(e,n)}break;case S.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=D(e,n)}break;case S.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ni(e,n)}break;case S.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case S.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ts.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case S.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=H(e,n)}break;case S.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=H(e,n)}break;case S.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:pi.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case S.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=H(e,n)}break;case S.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=D(e,n)}break;case S.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){p(e.decodingInstructions.length>0);let i=t;for(const s of e.decodingInstructions)switch(p(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case pi.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){const n=s.data.settings,a=new Uint8Array(n.length+i.length);a.set(n,0),a.set(i,n.length),i=a}break}break}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{const s=new Date(t);Number.isNaN(s.getTime())||(i.date??=s)}break;case"track_number":case"part_number":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.trackNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.discNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}}class io{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 i=0;for(const s of e.segments)for(const n of s.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}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 i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}
73async 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 Ti(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=G(n.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){const n=s.trackData.get(this.internalTrack.id);if(i.blockIndex+1<n.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(s.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 i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=ns(n.presentationTimestamps,l=>n.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){const a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){const a=n.blocks.findIndex(o=>o.isKeyFrame);return p(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];p(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const a=i.metadataOnly?Oe:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Oe:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const d=new ee(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:t}),d}async performClusterLookup(e,t,i,s,n){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,d=-1;if(e){const{blockIndex:k,correctBlockFound:y}=t(e);if(y)return this.fetchPacketInCluster(e,k,n);k!==-1&&(l=e,d=k)}const u=G(this.internalTrack.cuePoints,i,k=>k.time),h=u!==-1?this.internalTrack.cuePoints[u]:null,f=G(this.internalTrack.clusterPositionCache,i,k=>k.startTimestamp),g=f!==-1?this.internalTrack.clusterPositionCache[f]:null,m=Math.max(h?.clusterPosition??0,g?.elementStartPos??0)||null;let w;for(e?m===null||e.elementStartPos>=m?(w=e.elementEndPos,c=e):w=m:w=m??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-Ie;){if(c){const C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>s)break}let k=a.reader.requestSliceRange(w,Ie,et);if(k instanceof Promise&&(k=await k),!k)break;const y=w,T=Ze(k);if(!T||!xi.includes(T.id)&&T.id!==S.Void){const C=await Ja(a.reader,y,xi,Math.min(o.elementEndPos??1/0,y+to));if(C){w=C;continue}else break}const b=T.id;let P=T.size;const x=k.filePos;if(b===S.Cluster){c=await a.readCluster(y,o),P=c.elementEndPos-x;const{blockIndex:C,correctBlockFound:_}=t(c);if(_)return this.fetchPacketInCluster(c,C,n);C!==-1&&(l=c,d=C)}P===void 0&&(p(b!==S.Cluster),P=(await rr(a.reader,x,qi,o.elementEndPos)).pos-x);const I=x+P;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(I,Ie,et);if(C instanceof Promise&&(C=await C),!C)break;if(Mr(C)===S.Segment){o.elementEndPos=I;break}}w=I}if(h&&(!l||l.elementStartPos<h.clusterPosition)){const k=this.internalTrack.cuePoints[u-1];p(!k||k.time<h.time);const y=k?.time??-1/0;return this.performClusterLookup(null,t,y,s,n)}return l?this.fetchPacketInCluster(l,d,n):null}}class fl extends io{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(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}
73async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?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 i={codec:kr({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?Ar(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Fr(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Ba(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Ma(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)&&(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i})():null}}class ml extends io{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??={codec:wr({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}}/*! 74 * Copyright (c) 2026-present, Vanilagy and contributors 75 * 76 * This Source Code Form is subject to the terms of the Mozilla Public 77 * License, v. 2.0. If a copy of the MPL was not distributed with this 78 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 79 */const nr=async(r,e,t,i=null)=>{let n=e;for(;t===null||n<t;){const a=t!==null?Math.min(65536,t-n):65536;let o=r.requestSliceRange(n,At,a);if(o instanceof Promise&&(o=await o),!o||o.length<At)break;for(;o.remainingLength>=At;){const c=o.filePos,l=F(o),d=r.fileSize!==null?r.fileSize-n:null,u=ds(l,d);if(u.header&&(!i||u.header.sampleRate===i.sampleRate&&u.header.mpegVersionId===i.mpegVersionId&&u.header.layer===i.layer&&Pi(u.header.channel)===Pi(i.channel)))return{header:u.header,startPos:n};o.filePos=c+u.bytesAdvanced,n=o.filePos}}return null};/*! 80 * Copyright (c) 2026-present, Vanilagy and contributors 81 * 82 * This Source Code Form is subject to the terms of the Mozilla Public 83 * License, v. 2.0. If a copy of the MPL was not distributed with this 84 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 85 */class pl extends lt{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 Rt,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return 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 gl(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,at);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=Bt(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await nr(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 i=us(t.mpegVersionId,t.channel);let s=this.reader.requestSlice(e.startPos+i,4);if(s instanceof Promise&&(s=await s),s){const o=F(s);if(o===ls||o===Cr){if(!this.xingData){let l=this.reader.requestSlice(e.startPos+i+4,12);if(l instanceof Promise&&(l=await l),l){const d=D(l,12),u=q(d),h=u.getUint32(0,!1);this.xingData={frameCount:h&vt.FrameCount?u.getUint32(4,!1):null,fileSize:h&vt.FileSize?u.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,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,i=!1;for(;;){let s=this.reader.requestSlice(t,at);if(s instanceof Promise&&(s=await s),!s)break;
85const n=Bt(s);if(!n)break;i=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(a instanceof Promise&&(a=await a),!a)break;Lr(a,n,this.metadataTags),t=s.filePos+n.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=Gi){let s=this.reader.requestSlice(this.reader.fileSize-Gi,Gi);s instanceof Promise&&(s=await s),p(s),te(s,3)==="TAG"&&Su(s,this.metadataTags)}return this.metadataTags}finally{e()}}}class gl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return p(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(p(e.firstFrameHeader!==null),p(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=Mc(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),i=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(i)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}
85async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return le}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.firstFrameHeader),Pi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ct}}async getDecoderConfig(){return p(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Pi(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Oe;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=D(n,i.dataSize)}return new ee(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=G(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 86 * Copyright (c) 2026-present, Vanilagy and contributors 87 * 88 * This Source Code Form is subject to the terms of the Mozilla Public 89 * License, v. 2.0. If a copy of the MPL was not distributed with this 90 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 91 */const zr=1399285583,kl=79764919,so=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^kl:e<<1;so[r]=e>>>0&4294967295}const ro=r=>{const e=q(r),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let i=0;for(let s=0;s<r.length;s++){const n=r[s];i=(i<<8^so[i>>>24^n])>>>0}return e.setUint32(22,t,!0),i},no=(r,e,t)=>{let i=0,s=null;if(r.length>0)if(e.codec==="vorbis"){p(e.vorbisInfo);const n=e.vorbisInfo.modeBlockflags.length,o=(1<<uc(n-1))-1<<1,c=(r[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=t;const d=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[d],d===1){const u=(o|1)+1,h=r[0]&u?1:0;l=e.vorbisInfo.blocksizes[h]}i=l!==null?l+s>>2:0}else e.codec==="opus"&&(i=Qc(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:s}},ao=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*! 92 * Copyright (c) 2026-present, Vanilagy and contributors 93 * 94 * This Source Code Form is subject to the terms of the Mozilla Public 95 * License, v. 2.0. If a copy of the MPL was not distributed with this 96 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 97 */const It=27,$t=282,oo=$t+65025,gi=r=>{const e=r.filePos;if(qt(r)!==zr)return null;r.skip(1);const i=M(r),s=Tu(r),n=qt(r),a=qt(r),o=qt(r),c=M(r),l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=M(r);const d=27+c,u=l.reduce((f,g)=>f+g,0),h=d+u;return{headerStartPos:e,totalSize:h,dataStartPos:e+d,dataSize:u,headerType:i,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:l}},wl=(r,e)=>{for(;r.filePos<e-3;){const t=qt(r),i=t&255,s=t>>>8&255,n=t>>>16&255,a=t>>>24&255,o=79;if(!(i!==o&&s!==o&&n!==o&&a!==o)){if(r.skip(-4),t===zr)return!0;r.skip(1)}}return!1};/*! 98 * Copyright (c) 2026-present, Vanilagy and contributors 99 * 100 * This Source Code Form is subject to the terms of the Mozilla Public 101 * License, v. 2.0. If a copy of the MPL was not distributed with this 102 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 103 */class yl extends lt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,It,$t);if(t instanceof Promise&&(t=await t),!t)break;const i=gi(t);if(!i||!!!(i.headerType&2))break;
103this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const i=await this.readPacket(t.bosPage,0);i&&(i.data.byteLength>=7&&i.data[0]===1&&i.data[1]===118&&i.data[2]===111&&i.data[3]===114&&i.data[4]===98&&i.data[5]===105&&i.data[6]===115?await this.readVorbisMetadata(i,t):i.data.byteLength>=8&&i.data[0]===79&&i.data[1]===112&&i.data[2]===117&&i.data[3]===115&&i.data[4]===72&&i.data[5]===101&&i.data[6]===97&&i.data[7]===100&&await this.readOpusMetadata(i,t),t.codecInfo.codec!==null&&this.trackBackings.push(new Tl(t,this)))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s||(i=await this.findNextPacketStart(s),!i))return;const n=await this.readPacket(i.startPage,i.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;const a=[],o=u=>{for(;a.push(Math.min(255,u)),!(u<255);)u-=255};o(e.data.length),o(s.data.length);const c=new Uint8Array(1+a.length+e.data.length+s.data.length+n.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(s.data,1+a.length+e.data.length),c.set(n.data,1+a.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;const l=q(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const d=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:za(n.data).modeBlockflags},Zs(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const s=await this.readPacket(i.startPage,i.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;const n=ms(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=ti,t.codecInfo.opusInfo={preSkip:n.preSkip},Zs(s.data.subarray(8),this.metadataTags)}async readPacket(e,t){p(t<e.lacingValues.length);let i=0;for(let u=0;u<t;u++)i+=e.lacingValues[u];let s=e,n=i,a=t;const o=[];e:for(;;){let u=this.reader.requestSlice(s.dataStartPos,s.dataSize);u instanceof Promise&&(u=await u),p(u);const h=D(u,s.dataSize);for(;;){if(a===s.lacingValues.length){o.push(h.subarray(i,n));break}const g=s.lacingValues[a];if(n+=g,g<255){o.push(h.subarray(i,n));break e}a++}let f=s.headerStartPos+s.totalSize;for(;;){let g=this.reader.requestSliceRange(f,It,$t);if(g instanceof Promise&&(g=await g),!g)return null;const m=gi(g);if(!m)return null;if(s=m,s.serialNumber===e.serialNumber)break;f=s.headerStartPos+s.totalSize}i=0,n=0,a=0}const c=o.reduce((u,h)=>u+h.length,0);if(c===0)return null;const l=new Uint8Array(c);let d=0;for(let u=0;u<o.length;u++){const h=o[u];l.set(h,d),d+=h.length}return{data:l,endPage:s,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 i=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(i,It,$t);if(s instanceof Promise&&(s=await s),!s)return null;const n=gi(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};i=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(i=>i?.codec??null)));return ao({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Tl{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Rt,this.internalSampleRate=e.codecInfo.codec==="opus"?ti:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return p(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}
103async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return p(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 le}getDisposition(){return{...ct,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(p(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:s,vorbisBlockSize:n}=no(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new ee(i.metadataOnly?Oe:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),a}async getFirstPacket(e){p(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(p(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const s=await this.demuxer.findNextPacketStart(i.packet);if(!s)return null;const n=i.timestampInSamples+i.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const i=Ti(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;p(this.bitstream.lastMetadataPacket);const s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,a=this.demuxer.reader.fileSize;const o=[n];e:for(;n.headerStartPos+n.totalSize<a;){const y=n.headerStartPos,T=Math.floor((y+a)/2);let b=T;for(;;){const P=Math.min(b+oo,a-It);let x=this.demuxer.reader.requestSlice(b,P-b);if(x instanceof Promise&&(x=await x),p(x),!wl(x,P)){a=T+It;continue e}let C=this.demuxer.reader.requestSliceRange(x.filePos,It,$t);C instanceof Promise&&(C=await C),p(C);const _=gi(C);p(_);let E=!1;if(_.serialNumber===this.bitstream.serialNumber)E=!0;else{let v=this.demuxer.reader.requestSlice(_.headerStartPos,_.totalSize);v instanceof Promise&&(v=await v),p(v);const z=D(v,_.totalSize);E=ro(z)===_.checksum}if(!E){b=_.headerStartPos+4;continue}if(E&&_.serialNumber!==this.bitstream.serialNumber){b=_.headerStartPos+_.totalSize;continue}if(_.granulePosition===-1){b=_.headerStartPos+_.totalSize;continue}this.granulePositionToTimestampInSamples(_.granulePosition)>i?a=_.headerStartPos:(n=_,o.push(_));continue e}}let c=s.startPage;for(const y of o){if(y.granulePosition===n.granulePosition)break;(!c||y.headerStartPos>c.headerStartPos)&&(c=y)}let l=c;const d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===n.granulePosition);){const y=l.headerStartPos+l.totalSize;let T=this.demuxer.reader.requestSliceRange(y,It,$t);T instanceof Promise&&(T=await T),p(T);const b=gi(T);p(b),l=b,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}p(l.granulePosition!==-1);let u=null,h,f,g=l,m=0;if(l.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{h=0,f=!1;for(let b=l.lacingValues.length-1;b>=0;b--)if(l.lacingValues[b]<255){u=b+1;break}if(u===null)throw new Error("Invalid page with granule position: no packets end on this page.");m=u-1;const y={data:Oe,endPage:g,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(y)){const b=fn(d,l,u);p(b);const P=hn(d,b.page,b.segmentIndex);P&&(l=P.page,u=P.segmentIndex)}else for(;;){const b=fn(d,l,u);if(!b)break;const P=hn(d,b.page,b.segmentIndex);if(!P)break;
103if(l=P.page,u=P.segmentIndex,b.page.headerStartPos!==g.headerStartPos){g=b.page,m=b.segmentIndex;break}}}let w=null,k=null;for(;l!==null;){p(u!==null);const y=await this.demuxer.readPacket(l,u);if(!y)break;if(!(l.headerStartPos===s.startPage.headerStartPos&&u<s.startSegmentIndex)){let P=this.createEncodedPacketFromOggPacket(y,{timestampInSamples:h,vorbisLastBlocksize:k?.vorbisBlockSize??null},t);p(P);let x=this.encodedPacketToMetadata.get(P);if(p(x),!f&&y.endPage.headerStartPos===g.headerStartPos&&y.endSegmentIndex===m?(h=this.granulePositionToTimestampInSamples(l.granulePosition),f=!0,P=this.createEncodedPacketFromOggPacket(y,{timestampInSamples:h-x.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},t),p(P),x=this.encodedPacketToMetadata.get(P),p(x)):h+=x.durationInSamples,w=P,k=x,f&&(Math.max(h,0)>i||Math.max(x.timestampInSamples,0)===i))break}const b=await this.demuxer.findNextPacketStart(y);if(!b)break;l=b.startPage,u=b.startSegmentIndex}return w}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const s=Ti(e*this.internalSampleRate);e=s/this.internalSampleRate;const n=G(this.sequentialScanCache,s,c=>c.timestampInSamples);let a;if(n!==-1){const c=this.sequentialScanCache[n];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);p(l),this.sequentialScanCache.length>0&&p(ce(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const hn=(r,e,t)=>{let i=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(i.lacingValues[s]<255){s++;break e}if(p(s===-1),!(i.headerType&1)){s=0;break}const a=da(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,s=i.lacingValues.length}if(p(s!==-1),s===i.lacingValues.length){const n=r[r.indexOf(i)+1];p(n),i=n,s=0}return{page:i,segmentIndex:s}},fn=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=da(r,s=>s.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};/*! 104 * Copyright (c) 2026-present, Vanilagy and contributors 105 * 106 * This Source Code Form is subject to the terms of the Mozilla Public 107 * License, v. 2.0. If a copy of the MPL was not distributed with this 108 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 109 */var Te;(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"})(Te||(Te={}));class bl extends lt{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??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),p(e);const t=te(e,4),i=t!=="RIFX",s=t==="RF64",n=gt(e,i);let a=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(te(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,l=null,d=e.filePos;for(;a===null||d<a;){let h=this.reader.requestSlice(d,8);if(h instanceof Promise&&(h=await h),!h)break;const f=te(h,4),g=gt(h,i),m=h.filePos;if(s&&c===0&&f!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(f==="fmt ")await this.parseFmtChunk(m,g,i);else if(f==="data"){if(l??=g,this.dataStart=h.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(f==="ds64"){let w=this.reader.requestSlice(m,g);if(w instanceof Promise&&(w=await w),!w)break;const k=Nn(w,i);l=Nn(w,i),a=Math.min(k+8,this.reader.fileSize??1/0)}else f==="LIST"?await this.parseListChunk(m,g,i):(f==="ID3 "||f==="id3 ")&&await this.parseId3Chunk(m,g);d=m+g+(g&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 u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.trackBackings.push(new Sl(this))})()}async parseFmtChunk(e,t,i){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=ci(s,i);const a=ci(s,i),o=gt(s,i);s.skip(4);const c=ci(s,i);let l;if(t===14?l=8:l=ci(s,i),t>=18&&n!==357){const d=ci(s,i),u=t-18;if(Math.min(u,d)>=22&&n===Te.EXTENSIBLE){s.skip(6);const f=D(s,16);n=f[0]|f[1]<<8}}(n===Te.MULAW||n===Te.ALAW)&&(l=8),this.audioInfo={format:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:c}
109}async parseListChunk(e,t,i){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;const n=te(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+t-8;){s.filePos=a;const o=te(s,4),c=gt(s,i),l=D(s,c);let d=0;for(let h=0;h<l.length&&l[h]!==0;h++)d++;const u=String.fromCharCode(...l.subarray(0,d));switch(this.metadataTags.raw??={},this.metadataTags.raw[o]=u,o){case"INAM":case"TITL":this.metadataTags.title??=u;break;case"TIT3":this.metadataTags.description??=u;break;case"IART":this.metadataTags.artist??=u;break;case"IPRD":this.metadataTags.album??=u;break;case"IPRT":case"ITRK":case"TRCK":{const h=u.split("/"),f=Number.parseInt(h[0],10),g=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"ICRD":case"IDIT":{const h=new Date(u);Number.isNaN(h.getTime())||(this.metadataTags.date??=h)}break;case"YEAR":{const h=Number.parseInt(u,10);Number.isInteger(h)&&h>0&&(this.metadataTags.date??=new Date(h,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=u;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=u;break}a+=8+c+(c&1)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const s=Bt(i);if(s){const n=t-at;if(s.size=Math.min(s.size,n),s.size>0){const a=i.slice(e+at,s.size);Lr(a,s,this.metadataTags)}}}getCodec(){if(p(this.audioInfo),this.audioInfo.format===Te.MULAW)return"ulaw";if(this.audioInfo.format===Te.ALAW)return"alaw";if(this.audioInfo.format===Te.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===Te.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 zt=2048;class Sl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(p(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return p(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
109async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...ct}}async getPacketAtIndex(e,t){p(e>=0),p(this.demuxer.audioInfo);const i=e*zt*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const s=Math.min(zt*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=Oe;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,s);c instanceof Promise&&(c=await c),p(c),n=D(c,s)}const a=e*zt/this.demuxer.audioInfo.sampleRate,o=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ee(n,"key",a,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){p(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/zt,(this.demuxer.dataSize-1)/(zt*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const s=await this.getPacketAtIndex(i,t);if(s)return s;if(i===0)return null;p(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const a=await this.getNextPacket(n,t);if(!a)break;n=a}return n}getNextPacket(e,t){p(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/zt);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 110 * Copyright (c) 2026-present, Vanilagy and contributors 111 * 112 * This Source Code Form is subject to the terms of the Mozilla Public 113 * License, v. 2.0. If a copy of the MPL was not distributed with this 114 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 115 */const _i=7,kt=9,nt=r=>{const e=r.filePos,t=D(r,9),i=new K(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);const l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const d=i.readBits(13);i.skipBits(11);const u=i.readBits(2)+1;if(u!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:d,numberOfAacFrames:u,crcCheck:h,startPos:e}};/*! 116 * Copyright (c) 2026-present, Vanilagy and contributors 117 * 118 * This Source Code Form is subject to the terms of the Mozilla Public 119 * License, v. 2.0. If a copy of the MPL was not distributed with this 120 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 121 */const is=1024;class Pl extends lt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new Rt,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();p(this.firstFrameHeader),this.trackBackings=[new xl(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,at);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=Bt(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,_i,kt);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=nt(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 i=Ai[t.samplingFrequencyIndex];p(i!==void 0);const s=is/i,n={timestamp:this.nextTimestampInSamples/i,duration:s,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=is,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 i=this.reader.requestSlice(t,at);if(i instanceof Promise&&(i=await i),!i)break;
121const s=Bt(i);if(!s)break;let n=this.reader.requestSlice(i.filePos,s.size);if(n instanceof Promise&&(n=await n),!n)break;Lr(n,s,this.metadataTags),t=i.filePos+s.size}return this.metadataTags}finally{e()}}}class xl{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/is}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 le}getCodec(){return"aac"}getInternalCodecId(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){p(this.demuxer.firstFrameHeader);const e=as[this.demuxer.firstFrameHeader.channelConfiguration];return p(e!==void 0),e}getSampleRate(){p(this.demuxer.firstFrameHeader);const e=Ai[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return p(e!==void 0),e}getDisposition(){return{...ct}}async getDecoderConfig(){return p(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 i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Oe;else{let n=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=D(n,i.dataSize)}return new ee(s,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=G(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*! 122 * Copyright (c) 2026-present, Vanilagy and contributors 123 * 124 * This Source Code Form is subject to the terms of the Mozilla Public 125 * License, v. 2.0. If a copy of the MPL was not distributed with this 126 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 127 */const co=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,_l=(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}},lo=r=>{let e=0;const t=new K(D(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],s=e-1,n=new K(D(r,s)),a=8-e-1;for(let c=0;c<a;c++)i.unshift(t.readBits(1));for(let c=0;c<s;c++)for(let l=0;l<8;l++){const d=n.readBits(1);l<2||i.unshift(d)}return i.reduce((c,l,d)=>c|l<<d,0)},uo=(r,e)=>{if(e==="uncommon-u16")return re(r)+1;if(e==="uncommon-u8")return M(r)+1;if(typeof e=="number")return e;ge(e),p(!1)},Cl=(r,e)=>e==="uncommon-u16"?re(r):e==="uncommon-u16-10"?re(r)*10:e==="uncommon-u8"?M(r):typeof e=="number"?e:null,Il=r=>{let t=0;for(const i of r){t^=i;for(let s=0;s<8;s++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};/*! 128 * Copyright (c) 2026-present, Vanilagy and contributors 129 * 130 * This Source Code Form is subject to the terms of the Mozilla Public 131 * License, v. 2.0. If a copy of the MPL was not distributed with this 132 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 133 */class El extends lt{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 Rt,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),p(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);
133if(t instanceof Promise&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);p(t);const i=M(t),s=$e(t),n=(i&128)!==0;switch(i&127){case st.STREAMINFO:{let o=this.reader.requestSlice(e,s);if(o instanceof Promise&&(o=await o),p(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=D(o,34),l=new K(c),d=l.readBits(16),u=l.readBits(16),h=l.readBits(24),f=l.readBits(24),g=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);const w=l.readBits(36);l.skipBits(128);const k=new Uint8Array(42);k.set(new Uint8Array([102,76,97,67]),0),k.set(new Uint8Array([128,0,0,34]),4),k.set(c,8),this.audioInfo={numberOfChannels:m,sampleRate:g,totalSamples:w,minimumBlockSize:d,maximumBlockSize:u,minimumFrameSize:h,maximumFrameSize:f,description:k},this.trackBacking=new Al(this);break}case st.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),p(o),Zs(D(o,s),this.metadataTags);break}case st.PICTURE:{let o=this.reader.requestSlice(e,s);o instanceof Promise&&(o=await o),p(o);const c=F(o),l=F(o),d=xe.decode(D(o,l)),u=F(o),h=xe.decode(D(o,u));o.skip(16);const f=F(o),g=D(o,f);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,mimeType:d,kind:c===3?"coverFront":c===4?"coverBack":"unknown",description:h});break}}if(e+=s,n){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){p(this.audioInfo);const i=6,s=16,n=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+s+2,o=this.audioInfo.minimumFrameSize||n,l=(this.audioInfo.maximumFrameSize||a)+s,d=await this.reader.requestSliceRange(e,s,l);if(!d)return null;const u=this.readFlacFrameHeader({slice:d,isFirstPacket:t});if(!u)return null;for(d.filePos=e+o;;){if(d.filePos>d.end-i)return{num:u.num,blockSize:u.blockSize,sampleRate:u.sampleRate,size:d.end-e,isLastFrame:!0};if(M(d)===255){const f=d.filePos,g=M(d),m=this.blockingBit===1?249:248;if(g!==m){d.filePos=f;continue}d.skip(-2);const w=d.filePos-e,k=this.readFlacFrameHeader({slice:d,isFirstPacket:!1});if(!k){d.filePos=f;continue}if(this.blockingBit===0){if(k.num-u.num!==1){d.filePos=f;continue}}else if(k.num-u.num!==u.blockSize){d.filePos=f;continue}return{num:u.num,blockSize:u.blockSize,sampleRate:u.sampleRate,size:w,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,s=D(e,4),n=new K(s);if(n.readBits(15)!==32764)return null;if(this.blockingBit===null){p(t);const w=n.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(p(!t),n.readBits(1)!==1)return null}else if(this.blockingBit===0){if(p(!t),n.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=co(n.readBits(4));if(!o)return null;p(this.audioInfo);const c=_l(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;const d=lo(e),u=uo(e,o),h=Cl(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;const f=e.filePos-i,g=M(e);e.skip(-f),e.skip(-1);const m=Il(D(e,f));return g!==m?null:{num:d,blockSize:u,sampleRate:h}}async advanceReader(){await this.readMetadata(),p(this.lastLoadedPos!==null),p(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const i=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(n),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class Al{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}
133getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ct}}async getDecoderConfig(){return p(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(p(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const s=G(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(s===-1){await this.demuxer.advanceReader();continue}const n=this.demuxer.loadedSamples[s],a=n.blockOffset/this.demuxer.audioInfo.sampleRate,o=n.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(s,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let s;if(t.metadataOnly)s=Oe;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;s=D(o,i.byteSize)}p(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ee(s,"key",n,a,e,i.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*! 134 * Copyright (c) 2026-present, Vanilagy and contributors 135 * 136 * This Source Code Form is subject to the terms of the Mozilla Public 137 * License, v. 2.0. If a copy of the MPL was not distributed with this 138 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 139 */const Me=9e4,pe=188,ho=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};/*! 140 * Copyright (c) 2026-present, Vanilagy and contributors 141 * 142 * This Source Code Form is subject to the terms of the Mozilla Public 143 * License, v. 2.0. If a copy of the MPL was not distributed with this 144 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 145 */const fo="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.",mn=new Set;class vl extends lt{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??=(async()=>{const e=pe+16+1;let t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),p(t);const i=D(t,e);if(i[0]===71&&i[pe]===71)this.packetOffset=0,this.packetStride=pe;else if(i[0]===71&&i[pe+16]===71)this.packetOffset=0,this.packetStride=pe+16;else if(i[4]===71&&i[4+pe+4]===71)this.packetOffset=4,this.packetStride=pe+4;else throw new Error("Unreachable.");const s=256;this.minReferencePointByteDistance=s*this.packetStride;let n=this.packetOffset,a=null,o=!1,c=!1;for(;;){const l=await this.readPacketHeader(n);if(!l)break;if(l.payloadUnitStartIndicator===0){n+=this.packetStride;
145continue}const d=await this.readSection(n,!0,!c);if(!d)break;const u=3,h=32;let f=!1;if(!c&&d.pid!==0&&!(d.payload[0]===0&&d.payload[1]===0&&d.payload[2]===1)){const w=new K(d.payload),k=w.readAlignedByte();w.skipBits(8*k),f=w.readBits(8)===2}if(d.pid===0&&!o){const m=new K(d.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(14);const k=m.readBits(10);for(m.skipBits(40);8*(k+u)-m.pos>h;){const y=m.readBits(16);m.skipBits(3);const T=m.readBits(13);if(y!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=T}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((d.pid===a||f)&&!c){const m=new K(d.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(12);const k=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const y=m.readBits(10);for(m.skipBits(8*y);8*(k+u)-m.pos>h;){const T=m.readBits(8);m.skipBits(3);const b=m.readBits(13);m.skipBits(6);const P=m.readBits(10),x=m.pos+8*P;let I=!1,C=!1;for(;m.pos<x;){const E=m.readBits(8),R=m.readBits(8);E===106?I=!0:(E===122||E===204)&&(C=!0),m.skipBits(8*R)}let _=null;switch(T){case 27:case 36:_={type:"video",codec:T===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 E;if(T===3||T===4)E="mp3";else if(T===15)E="aac";else if(T===129)E="ac3";else if(T===135)E="eac3";else throw new Error("Unreachable.");_={type:"audio",codec:E,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:C?_={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:I&&(_={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:mn.has(T)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),mn.add(T))}_&&this.elementaryStreams.push({demuxer:this,pid:b,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:_,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(w=>w.pid===d.pid);e:if(m&&!m.initialized){const w=Ht(d,!0);if(!w)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${m.pid}`);if(m.firstSection=d,m.canBeTrustedWithKeyPackets=d.randomAccessIndicator===1,this.input._initInput){const T=(await this.input._initInput._getDemuxer()).elementaryStreams.find(b=>b.pid===d.pid&&b.info.codec===m.info.codec);if(T){m.info=T.info,m.initialized=!0;break e}}const k=new fi(m,w);if(m.info.type==="video"){for(;;){const y=k;if(y.suppliedPacket=null,await k.markNextPacket(),m.info.codec==="avc"){if(!k.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(m.info.avcCodecInfo=Ar(k.suppliedPacket.data),!m.info.avcCodecInfo)continue;const T=m.info.avcCodecInfo.sequenceParameterSets[0];p(T);const b=vr(T);m.info.width=b.displayWidth,m.info.height=b.displayHeight;const P=b.pixelAspectRatio.num,x=b.pixelAspectRatio.den;P>0&&x>0&&(P>x?(m.info.squarePixelWidth=Math.round(m.info.width*P/x),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*x/P))),m.info.colorSpace={primaries:Qi[b.colourPrimaries],transfer:ji[b.transferCharacteristics],matrix:Xi[b.matrixCoefficients],fullRange:!!b.fullRangeFlag},m.info.reorderSize=b.maxDecFrameBuffering;break}else if(m.info.codec==="hevc"){if(!k.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(m.info.hevcCodecInfo=Fr(k.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const b=m.info.hevcCodecInfo.arrays.find(x=>x.nalUnitType===ne.SPS_NUT).nalUnits[0];p(b);const P=Fa(b);m.info.width=P.displayWidth,m.info.height=P.displayHeight,P.pixelAspectRatio.num>P.pixelAspectRatio.den?(m.info.squarePixelWidth=Math.round(m.info.width*P.pixelAspectRatio.num/P.pixelAspectRatio.den),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*P.pixelAspectRatio.den/P.pixelAspectRatio.num)),m.info.colorSpace
145={primaries:Qi[P.colourPrimaries],transfer:ji[P.transferCharacteristics],matrix:Xi[P.matrixCoefficients],fullRange:!!P.fullRangeFlag},m.info.reorderSize=P.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:kr({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 k.markNextPacket(),!k.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${m.pid}`);if(m.info.codec==="aac"){const y=fe.tempFromBytes(k.suppliedPacket.data),T=nt(y);if(!T)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:T.objectType},m.info.numberOfChannels=as[T.channelConfiguration],m.info.sampleRate=Ai[T.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const y=F(fe.tempFromBytes(k.suppliedPacket.data)),T=ds(y,k.suppliedPacket.data.byteLength);if(!T.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Pi(T.header.channel),m.info.sampleRate=T.header.sampleRate}else if(m.info.codec==="ac3"){const y=Da(k.suppliedPacket.data);if(!y)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(y.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Br[y.acmod]+y.lfeon,m.info.sampleRate=hs[y.fscod]}else if(m.info.codec==="eac3"){const y=Oa(k.suppliedPacket.data);if(!y)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const T=Na(y);if(T===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=La(y),m.info.sampleRate=T}else throw new Error("Unhandled.");m.info.decoderConfig={codec:wr({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;n+=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 Fl(l)):this.trackBackingEntries.push(new Bl(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(i=>i?.codec??null)));return ho(e)}async readSection(e,t,i=!1){let s=e,n=e;const a=[];let o=0,c=null,l=!0,d=0;for(;;){const h=await this.readPacket(n);if(n+=this.packetStride,!h)break;if(c){if(h.pid!==c.pid){if(i)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;c=h}const f=!!(h.adaptationFieldControl&2),g=!!(h.adaptationFieldControl&1);let m=0;if(f&&(m=1+h.body[0],h===c&&m>1&&(d=h.body[1]>>6&1)),g&&(m===0?(a.push(h.body),o+=h.body.byteLength):(a.push(h.body.subarray(m)),o+=h.body.byteLength-m)),s=n,!t&&o>=64){l=!1;break}if(Ei(this.sectionEndPositions,s,k=>k)!==-1){l=!1;break}}if(l){const h=G(this.sectionEndPositions,s,f=>f);this.sectionEndPositions.splice(h+1,0,s)}if(!c)return null;let u;if(a.length===1)u=a[0];else{const h=a.reduce((g,m)=>g+m.length,0);u=new Uint8Array(h);let f=0;for(const g of a)u.set(g,f),f+=g.length}return{startPos:e,endPos:t?s:null,pid:c.pid,payload:u,randomAccessIndicator:d}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);
145if(t instanceof Promise&&(t=await t),!t)return null;if(M(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=re(t),n=s>>14&1,a=s&8191,c=M(t)>>4&3;return{payloadUnitStartIndicator:n,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,pe);if(t instanceof Promise&&(t=await t),!t)return null;const i=D(t,pe);if(i[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=(i[1]<<8)+i[2],a=n>>14&1,o=n&8191,l=i[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:l,body:i.subarray(4)}}}const Pt=(r,e)=>{if(r.payload.byteLength<3)return null;const t=new K(r.payload);if(t.readBits(24)!==1)return null;const s=t.readBits(8);if(t.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;t.skipBits(8);const n=t.readBits(2);t.skipBits(14);let a=null;if(n===2||n===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(fo);return{sectionStartPos:r.startPos,sectionEndPos:r.endPos,pts:a,randomAccessIndicator:r.randomAccessIndicator}},Ht=(r,e)=>{p(r.endPos!==null);const t=Pt(r,e);if(!t)return null;const i=new K(r.payload);i.skipBits(32);const s=i.readBits(16),n=6;i.skipBits(16);const a=i.readBits(8),o=i.pos+8*a;i.pos=o;const c=o/8;p(Number.isInteger(c));const l=r.payload.subarray(c,s>0?n+s:r.payload.byteLength);return{...t,data:l}};class gs{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 i=0;for(const s of e.trackBackingEntries)if(s.getType()===t&&i++,p(s instanceof gs),s.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...ct,primary:!1}}getTimeResolution(){return Me}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
145async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let s;return this.allPacketsAreKeyPackets()?s="key":s=e.randomAccessIndicator===1?"key":"delta",new ee(i.metadataOnly?Oe:e.data,s,e.pts/Me,Math.max(t/Me,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;p(t);const i=Ht(t,!0);p(i);const s=new fi(this.elementaryStream,i),n=new vs(this,s),a=await n.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,n),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const d=await i.readNext();if(!d)return null;this.packetBuffers.delete(e);const u=this.createEncodedPacket(d.packet,d.duration,t);return this.packetBuffers.set(u,i),this.packetSectionStarts.set(u,d.packet.sectionStartPos),u}const s=this.packetSectionStarts.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");const a=await this.elementaryStream.demuxer.readSection(s,!0);p(a);const o=Ht(a,!0);p(o);const c=new fi(this.elementaryStream,o);i=new vs(this,c);const l=e.sequenceNumber;for(;;){const d=await i.readNext();if(!d)return null;if(d.packet.sequenceNumber>l){const u=this.createEncodedPacket(d.packet,d.duration,t);return this.packetBuffers.set(u,i),this.packetSectionStarts.set(u,d.packet.sectionStartPos),u}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if(i.type==="key")return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const s=Ti(e*Me),n=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=n,c=this.elementaryStream.pid,l=async(b,P,x)=>{let I=b;for(;I<P;){const C=await n.readPacketHeader(I);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){const _=await n.readSection(I,x);if(!_)return null;const E=Pt(_,!1);if(E&&E.pts!==null)return{pesPacketHeader:E,section:_}}I+=n.packetStride}return null},d=this.elementaryStream.firstSection;p(d);const u=Pt(d,!0);if(p(u),s<u.pts)return null;let h;const f=this.elementaryStream.referencePesPackets,g=G(f,s,b=>b.pts),m=g!==-1?f[g]:null;if(m&&s-m.pts<Me/2)h=m.sectionStartPos;else{let b=0;if(a.fileSize!==null){const P=Math.ceil(a.fileSize/o);if(P>1){let x=0,I=P-1;for(b=x;x<=I;){const C=Math.floor((x+I)/2),_=Ps(C*o,n.packetStride)+u.sectionStartPos,E=_+o,R=await l(_,E,!1);if(!R){I=C-1;continue}R.pesPacketHeader.pts<=s?(b=C,x=C+1):I=C-1}}}h=Ps(b*o,n.packetStride)+u.sectionStartPos}let k=(await l(h,a.fileSize??1/0,!1))?.pesPacketHeader??null;k||(k=u);const y=this.getReorderSize(),T=async(b,P)=>{const x=await n.readSection(b,!0);p(x);const I=Ht(x,!0);p(I);const C=new fi(this.elementaryStream,I),_=new vs(this,C);for(;!((ce(_.presentationOrderPackets)?.pts??-1/0)>=s||!await _.readNextPacket()););const E=ns(_.presentationOrderPackets,P);if(E===-1)return null;const R=_.presentationOrderPackets[E],v=E===0?0:R.pts-_.presentationOrderPackets[E-1].pts;for(;_.decodeOrderPackets[0]!==R;)_.decodeOrderPackets.shift();_.lastDuration=v;const z=await _.readNext();p(z);const W=this.createEncodedPacket(z.packet,z.duration,i);return this.packetBuffers.set(W,_),this.packetSectionStarts.set(W,z.packet.sectionStartPos),W};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let b=k.sectionStartPos+n.packetStride;for(;;){const P=await n.readPacketHeader(b);if(!P)break e;if(P.pid===c&&P.payloadUnitStartIndicator===1){const x=await n.readSection(b,!1);if(x){const I=Pt(x,!1);if(I&&I.pts!==null){if(I.pts>s)break e;k=I,ar(this.elementaryStream,k);break}}}b+=n.packetStride}}e:for(let b=0;b<y+1;b++){let P=k.sectionStartPos-n.packetStride;for(;P>=n.packetOffset;){const x=await n.readPacketHeader(P);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){const I=await n.readSection(P,!1);if(I){const C=Pt(I,!1);if(C&&C.pts!==null){k=C;break}}}P-=n.packetStride}}return T(k.sectionStartPos,b=>b.pts<=s)}else{let b=h,P=null;const x=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let I=null;const C=b<=u.sectionStartPos;let _,E=null;if(C)_=u,E=d;else{const z=await l(b,a.fileSize??1/0,x);_=z?.pesPacketHeader??null,E=z?.section??null}let R=!1,v=0;e:for(;_&&!(P!==null&&_.sectionStartPos>=P);){if(_.pts<=s){let W;if(this.elementaryStream.canBeTrustedWithKeyPackets)W=_.randomAccessIndicator===1;else{p(E);const O=Ht(E,!0);p(O);const U=new fi(this.elementaryStream,O);await U.markNextPacket(),W=U.suppliedPacket?.randomAccessIndicator===1}W&&(I=_)}if(_.pts>s&&(R=!0),R&&(v++,v>y))break;let z=_.sectionStartPos+n.packetStride;for(;;){const W=await n.readPacketHeader(z);if(!W)break e;if(W.pid===c&&W.payloadUnitStartIndicator===1){const O=await n.readSection(z,x);if(O){const U=Pt(O,!1);if(U&&U.pts!==null){_=U,E=O,ar(this.elementaryStream,_);break}}}z+=n.packetStride}}if(I){let z=I;if(v===0)e:for(let O=0;O<y;O++){let U=z.sectionStartPos-n.packetStride;for(;U>=n.packetOffset;){const j=await n.readPacketHeader(U);if(!j)break e;if(j.pid===c&&j.payloadUnitStartIndicator===1){const ae=await n.readSection(U,x);if(ae){const ke=Pt(ae,!1);if(ke&&ke.pts!==null){z=ke;break}}}U-=n.packetStride}}const W=await T(z.sectionStartPos,O=>O.pts<=s&&O.randomAccessIndicator===1);return p(W),W}if(C)return null;P=b,b=Math.max(Ps(b-u.sectionStartPos-o,n.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class Fl extends gs{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}
145async canBeTransparent(){return!1}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Bl extends gs{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const ar=(r,e)=>{const t=r.referencePesPackets,i=G(t,e.sectionStartPos,s=>s.sectionStartPos);if(i>=0){const s=t[i];if(e.pts<=s.pts)return!1;const n=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-s.sectionStartPos<n)return!1;if(i<t.length-1){const a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<n)return!1}}return t.splice(i+1,0,e),!0};class fi{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 p(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let i;if(this.pesPackets.length===0)i=this.startingPesPacket;else{let s=ce(this.pesPackets).sectionEndPos;for(p(s!==null);;){const n=await this.demuxer.readPacketHeader(s);if(!n)return;if(n.pid===this.pid){const a=await this.demuxer.readSection(s,!0);if(!a)return;const o=Ht(a,!1);if(o){i=o;break}}s+=this.demuxer.packetStride}}this.pesPackets.push(i),this.endPos+=i.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,s=i+e;if(this.currentPos+=e,s<=t.data.byteLength)return t.data.subarray(i,s);const n=new Uint8Array(e);n.set(t.data.subarray(i));let a=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){n.set(o.data.subarray(0,c),a);break}n.set(o.data,a),a+=o.data.byteLength}return n}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(),i=this.currentPesPacketPos+t.data.byteLength;if(e<i)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(){p(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const t=e.info.codec,i=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let s=null;for(;;){let n=this.ensureBuffered(i);if(n instanceof Promise&&(n=await n),n===0)break;const a=this.currentPos,o=this.readBytes(n),c=o.byteLength;let l=0;for(;l<c;){const d=o.indexOf(0,l);if(d===-1||d>=c)break;l=d;const u=a+l;if(l+4>=c){this.seekTo(u);break}const h=o[l+1],f=o[l+2],g=o[l+3];let m=0,w=null;if(h===0&&f===0&&g===1?(m=4,w=o[l+4]):h===0&&f===1&&(m=3,w=g),m===0){l++;continue}const k=u;if(s===null){s=k,l+=m;continue}if(w!==null){const y=t==="avc"?Jt(w):yt(w);if(t==="avc"?y===Pe.AUD:y===ne.AUD_NUT){const b=k-s;return this.seekTo(s),this.supplyPacket(b,0)}}l+=m}if(n<i)break}if(s!==null){const n=this.endPos-s;return this.seekTo(s),this.supplyPacket(n,0)}}else{const t=e.info.codec,i=128;for(;;){let s=this.ensureBuffered(i);s instanceof Promise&&(s=await s);const n=this.currentPos;for(;this.currentPos-n<s;){const a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(kt);if(c instanceof Promise&&(c=await c),c<kt)return;const l=this.readBytes(kt),d=nt(fe.tempFromBytes(l));if(d){this.seekTo(o);let u=this.ensureBuffered(d.frameLength);return u instanceof Promise&&(u=await u),this.supplyPacket(u,Math.round(is*Me/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(At);if(c instanceof Promise&&(c=await c),c<At)return;const l=this.readBytes(At),d=q(l).getUint32(0),u=ds(d,null);if(u.header){this.seekTo(o);let h=this.ensureBuffered(u.header.totalSize);h instanceof Promise&&(h=await h);const f=u.header.audioSamplesInFrame*Me/e.info.sampleRate;return this.supplyPacket(h,Math.round(f))}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 d=l[4]>>6,u=l[4]&63;if(d===3||u>37){this.seekTo(o+1);continue}const h=$c[3*u+d];p(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);const f=Math.round(Yc*Me/e.info.sampleRate);return this.supplyPacket(c,f)}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 u=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,g=Ua[f];this.seekTo(o),c=this.ensureBuffered(u),c instanceof Promise&&(c=await c);const m=g*256,w=Math.round(m*Me/e.info.sampleRate);return this.supplyPacket(c,w)}else throw new Error("Unhandled.")}if(s<i)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let s;if(this.lastSuppliedPesPacket===i)p(this.nextPts!==null),s=this.nextPts;else{if(i.pts===null)throw new Error(fo);s=i.pts,ar(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=s+t;const n=i.sectionStartPos,a=n+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=i.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const l=ps(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(l)}}this.suppliedPacket={pts:s,data:o,sequenceNumber:a,sectionStartPos:n,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class vs{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(),p(this.reorderSize>=0)}
145async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);p(t!==-1);let i;for(t===this.presentationOrderPackets.length-1?i=this.lastDuration:(i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const s=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(s))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}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(p(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 s=1;s<this.reorderBuffer.length;s++)this.reorderBuffer[s].pts<this.reorderBuffer[t].pts&&(t=s);const i=this.reorderBuffer[t];this.presentationOrderPackets.push(i),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*! 146 * Copyright (c) 2026-present, Vanilagy and contributors 147 * 148 * This Source Code Form is subject to the terms of the Mozilla Public 149 * License, v. 2.0. If a copy of the MPL was not distributed with this 150 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 151 */const Yt="application/vnd.apple.mpegurl",pn="#EXT-X-STREAM-INF:",gn="#EXT-X-I-FRAME-STREAM-INF:",kn="#EXT-X-MEDIA:",or="#EXTINF:",wn="#EXT-X-MAP:",yn="#EXT-X-KEY:",Tn="#EXT-X-MEDIA-SEQUENCE:",bn="#EXT-X-BYTERANGE:",Sn="#EXT-X-PROGRAM-DATE-TIME:",Rl="#EXT-X-DISCONTINUITY",Pn="#EXT-X-TARGETDURATION:",Ml="#EXT-X-ENDLIST",xn="#EXT-X-PLAYLIST-TYPE:",zl="#EXT-X-I-FRAMES-ONLY",mo=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class ki{constructor(e){this._attributes={};let t="",i="",s=!1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?n=!n:o==="="&&!s&&!n?s=!0:o===","&&!n?(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",s=!1):s?i+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}/*! 152 * Copyright (c) 2026-present, Vanilagy and contributors 153 * 154 * This Source Code Form is subject to the terms of the Mozilla Public 155 * License, v. 2.0. If a copy of the MPL was not distributed with this 156 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 157 */class Dl{constructor(e,t,i){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=i}
157async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const i=di(e,s=>s.getType()==="video")+1;e.push(new _n(this,t,i))}else if(t.type==="audio"){const i=di(e,s=>s.getType()==="audio")+1;e.push(new Cn(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const i=await this.getInputForSegment(this.firstSegment).getTracks();for(const s of i)if(s.type==="video"){const n=di(e,a=>a.getType()==="video")+1;e.push(new _n(this,{id:e.length+1,type:"video"},n))}else if(s.type==="audio"){const n=di(e,a=>a.getType()==="audio")+1;e.push(new Cn(this,{id:e.length+1,type:"audio"},n))}}return e})()}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(t!==void 0)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let s;if(this.firstSegmentFirstTimestamps.has(i))s=this.firstSegmentFirstTimestamps.get(i);else{const l=this.getInputForSegment(i);s=await this.getFirstTimestampForInput(l),this.firstSegmentFirstTimestamps.set(i,s)}if(i===e)return i.timestamp-s;const n=await this.getFirstTimestampForInput(t),a=e.timestamp-i.timestamp,c=n-s-a;return Math.abs(c)<=Math.min(.25,a)?i.timestamp-s:e.timestamp-n}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class po{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const i=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i})()}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(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??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(),p(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)}
157getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){p(e.sequenceNumber>=0),p(this.segmentedInput.firstSegment);const s=await this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Zt(e.timestamp+s,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:i,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),p(this.segmentedInput.firstSegment),p(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,i){const s=this.packetInfos.get(e);if(!s)throw new Error("Packet was not created from this track.");const n=i?await s.track._backing.getNextKeyPacket(s.sourcePacket,t):await s.track._backing.getNextPacket(s.sourcePacket,t);if(n)return this.createAdjustedPacket(n,s.segment,s.track);let a=s.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const d=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(h=>h.type===s.track.type&&h.number===s.track.number);if(!d){a=o;continue}const u=await d._backing.getFirstPacket(t);return u?this.createAdjustedPacket(u,o,d):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let s=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!s)return null;for(await this.hydrate();s;){const n=this.segmentedInput.getInputForSegment(s),o=(await n.getTracks()).find(u=>u.type===this.firstInputTrack.type&&u.number===this.firstInputTrack.number);if(!o){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(s,n),l=e-c,d=i?await o._backing.getKeyPacket(l,t):await o._backing.getPacket(l,t);if(!d){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(d,s,o)}return null}}class _n extends po{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())}
157async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Cn extends po{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())}}/*! 158 * Copyright (c) 2026-present, Vanilagy and contributors 159 * 160 * This Source Code Form is subject to the terms of the Mozilla Public 161 * License, v. 2.0. If a copy of the MPL was not distributed with this 162 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 163 */fa();const In=typeof Zi<"u"?Zi:void 0,go=0,ko=1/0;let cr=null;typeof FinalizationRegistry<"u"&&(cr=new FinalizationRegistry(r=>{r()}));class Ae extends os{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 be;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,go,ko),e=this._getFileSize(),p(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new be;
163const 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 Hl(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Dr(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Dr{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.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(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;p(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ri extends Ae{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),i=s=>{if(!(s instanceof Ae||s instanceof Dr))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const n=s instanceof Ae?s.ref():s;return n.source._usedForHls||=this._usedForHls,n};return t instanceof Promise?t.then(i):i(t)}}const En=(r,e)=>r.path===e.path;class Ul extends ri{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,s){if(!this._root){if(!this._rootRequest){const n=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof Ae?o.ref():o;return this._root=c,this._rootRequest=null,c};n instanceof Promise?this._rootRequest=n.then(a):(a(n),p(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,s))}return this._root.source._read(e,t,i,s)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class Ih extends Ae{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=ie(e),this._view=q(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 Eh extends Ae{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&&(!ii(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 Or({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Ur.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,s){return this._orchestrator.read(e,t,i,s)}async _runWorker(e){p(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!Hi()&&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:i,value:s}=await t.read();
163if(i)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+s.length),this._orchestrator.supplyWorkerData(e,s)}else{const i=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}}const Ol=.5*2**20,Nl=((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 s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==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)}),An=new Set;class wo extends ri{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&&(!ii(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 i=e instanceof Request?e.url:e instanceof URL?e.href:e;super(i,a=>new wo(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Nl,this._requestInit={...t.requestInit};let s=null;if(t.requestInit?.headers){const a={...dc(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(s=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){const a=e.headers.get("Range");if(a!==null){s??=a;const o=new Request(e);o.headers.delete("Range"),this._url=o}}if(s!==null){const a=Wl(s);a&&(this._offset=a.offset,this._length=a.length)}const n=2;this._orchestrator=new Or({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??n,runWorker:this._runWorker.bind(this),prefetchProfile:Ur.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:me(e-this._offset,0,this._length??1/0)}_read(e,t,i,s){if(this._length!==null&&t>this._length)return null;const n=this._offset,a=this._orchestrator.read(n+e,n+t,Math.max(n+i,n),n+Math.min(s,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return a instanceof Promise?a.then(o):o(a)}async _runWorker(e){for(;;){const t=new AbortController,i=await hc(this._options.fetchFn??fetch,this._url,fc(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);e:if(this._orchestrator.fileSize===null){const n=i.headers.get("Content-Range");if(n){const o=/\/(\d+)/.exec(n);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=i.headers.get("Content-Length");
163a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,i.status!==206){if(!this._usedForHls){const n=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);n.origin!=="null"&&!(n.pathname.endsWith(".m3u8")||n.pathname.endsWith(".m3u"))&&(An.has(n.origin)||(console.log(this._usedForHls,this._url,n.pathname),console.warn(`HTTP server (origin ${n.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.`),An.add(n.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(!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const s=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await s.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 ha(1e3*l);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=n;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()}}const Ll=/^bytes=(\d+)-(\d*)$/,Wl=r=>{const e=Ll.exec(r.trim());if(!e)return null;const t=Number(e[1]),i=e[2]===""?null:Number(e[2]);return i!==null&&i<t?null:{offset:t,length:i!==null?i-t+1:null}};class yo extends ri{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&&(!ii(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!In.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,i=>new yo(i.path,t)),this._fileHandle=null,this._customSource=new To({getSize:async()=>{const i=await In.fs.open(e,"r");return this._fileHandle=i,cr?.register(this,()=>{i.close()},this),(await i.stat()).size},read:async(i,s)=>{p(this._fileHandle);const n=new Uint8Array(s-i);return await this._fileHandle.read(n,0,s-i,i),n},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t,i,s){return this._customSource._read(e,t,i,s)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,cr?.unregister(this))}}class To extends Ae{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&&(!ii(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 Or({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Ur[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,i,s){if(this._orchestrator.fileSize!==null)return this._or
163chestrator.read(e,t,i,s);const n=this._options.getSize();if(n instanceof Promise)return n.then(a=>{if(!Number.isInteger(a)||a<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,i,s)});if(!Number.isInteger(n)||n<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=n,this._orchestrator.read(e,t,i,s)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,i=e.targetPos;let s=this._options.read(e.currentPos,i);if(s instanceof Promise&&(s=await s),e.aborted)break;if(s instanceof Uint8Array){if(s=ie(s),s.length!==i-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${i-e.currentPos} bytes, but got ${s.length}.`);this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else if(s instanceof ReadableStream){const n=s.getReader();for(;e.currentPos<i&&!e.aborted;){const{done:a,value:o}=await n.read();if(a){if(e.currentPos<i)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${i-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=ie(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(){this._orchestrator.dispose(),this._options.dispose?.()}}const Ah=To;class Vl extends Ae{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&&(!ii(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 i=G(this._cache,e,d=>d.start),s=i!==-1?this._cache[i]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e;const a=new Uint8Array(t-e);if(i!==-1)for(let d=i;d<this._cache.length;d++){const u=this._cache[d];if(u.start>=t)break;const h=Math.max(e,u.start);h>n&&this._throwDueToCacheMiss();const f=Math.min(t,u.end);h<f&&(a.set(u.bytes.subarray(h-u.start,f-u.start),h-e),n=f)}if(n===t)return{bytes:a,view:q(a),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=J();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(d=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(u=>u.reject(d)),this._pendingSlices.length=0;else throw d})),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._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const n of this._pendingSlices)n.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,s=this._currentIndex+t.byteLength;this._dispatchRead(i,s);for(let n=0;n<this._pendingSlices.length;n++){const a=this._pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.end);o<c&&(a.bytes.set(t.subarray(o-i,c-i),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:q(a.bytes),offset:a.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:i,end:s,bytes:t,view:q(t),age:0});this._cache.length>0;){const n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Ur={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 s of t){const a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(Xs(r,e,a,s.targetPos)){const o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),d=Math.min(l,c);e=Math.max(e,s.startPos+d)}}return e=Math.max(e,r+Ol),{start:r,end:e}}};class Or{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,i,s){p(!this.disposed);const n=this.options.prefetchProfile(e,t,this.workers),a=Math.max(n.start,i),o=Math.min(n.end,this.fileSize??1/0,s);p(a<=e&&t<=o);let c=null;const l=G(this.cache,e,P=>P.start),d=l!==-1?this.cache[l]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,c={bytes:d.bytes,view:d.view,offset:d.start});const u=G(this.cache,a,P=>P.start),h=c?null:new Uint8Array(t-e);let f=0,g=a;const m=[];
163if(u!==-1){for(let P=u;P<this.cache.length;P++){const x=this.cache[P];if(x.start>=o)break;if(x.end<=a)continue;const I=Math.max(a,x.start),C=Math.min(o,x.end);if(p(I<=C),g<I&&m.push({start:g,end:I}),g=C,h){const _=Math.max(e,x.start),E=Math.min(t,x.end);if(_<E){const R=_-e;h.set(x.bytes.subarray(_-x.start,E-x.start),R),R===f&&(f=E-e)}}x.age=this.nextAge++}g<o&&m.push({start:g,end:o})}else m.push({start:a,end:o});if(h&&f>=h.length&&(c={bytes:h,view:q(h),offset:e}),m.length===0)return p(c),c;const{promise:w,resolve:k,reject:y}=J(),T=[];for(const P of m){const x=Math.max(e,P.start),I=Math.min(t,P.end);x===P.start&&I===P.end?T.push(P):x<I&&T.push({start:x,end:I})}const b=h&&{start:e,bytes:h,holes:T,resolve:k,reject:y};e:for(const P of m){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,P,b?[b]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const x=P.end<o||this.fileSize!==null,I=this.createWorker(P.start,P.end,x);if(I)b&&(I.pendingSlices=[b]),this.runWorker(I);else{let C=G(this.queuedReads,P.start,E=>E.hole.start),_=C!==-1?this.queuedReads[C]:null;for(_&&P.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,P.end),_.strictTarget&&=x,b&&_.pendingSlices.push(b)):(C++,_={hole:{start:P.start,end:P.end},strictTarget:x,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(C,0,_));C+1<this.queuedReads.length;){const E=this.queuedReads[C+1];if(E.hole.start>_.hole.end)break;_.hole.end=Math.max(_.hole.end,E.hole.end),_.pendingSlices.push(...E.pendingSlices),_.strictTarget&&=E.strictTarget,_.age=Math.min(_.age,E.age),this.queuedReads.splice(C+1,1)}}}return c||(p(h),c=w.then(P=>P&&{bytes:P,view:q(P),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(Xs(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let n=0;n<i.length;n++){const a=i[n];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const s=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,s.hole,s.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let n=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!n||c.age<n.age)&&(a=o,n=c)}if(n)p(a!==null),p(n.pendingSlices.length===0),this.workers.splice(a,1);else return null}const s={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(s),s}runWorker(e){p(!e.running),p(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(i=>i.reject(t)),e.pendingSlices.length=0;else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let n=1;n<this.queuedReads.length;n++)this.queuedReads[n].age<this.queuedReads[t].age&&(t=n);const i=this.queuedReads[t];this.queuedReads.splice(t,1);const s=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);p(s),s.pendingSlices=i.pendingSlices,this.runWorker(s)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let i=0;i<this.workers.length;i++){const s=this.workers[i];if(s!==e){for(const n of s.pendingSlices)t.add(n);s.aborted=!0,s.pendingSlices.length=0,this.workers.splice(i,1),i--}}for(let i=0;i<this.queuedReads.length;i++){const s=this.queuedReads[i];for(const n of s.pendingSlices)t.add(n)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){p(!e.aborted);const i=e.currentPos,s=i+t.length;this.insertIntoCache({start:i,end:s,bytes:t,view:q(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){const a=e.pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){const d=a.holes[l];i<=d.start&&s>d.start&&(d.start=s),d.end<=d.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){const a=this.workers[n];e===a||a.running||Xs(i,s,a.currentPos,a.targetPos)&&(this.workers.splice(n,1),n--)}}supplyFileSize(e){p(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const s=t.pendingSlices[i];for(const n of s.holes)if(n.end>e){s.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const s of i.pendingSlices)s.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let s=0;s<i.pendingSlices.length;s++){const n=i.pendingSlices[s];n.start>=e&&(n.resolve(null),i.pendingSlices.splice(s,1),s--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}
163onWorkerFinished(e){const t=this.workers.indexOf(e);p(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=G(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const s=new Uint8Array(e.end-i.start);s.set(i.bytes,0),s.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=s,i.view=q(s),i.end=e.end,t--,e=i}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 i=t+1;i<this.cache.length;i++){const s=this.cache[i];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length,i--;continue}const n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=q(n),e.end=s.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){const a=this.cache[n];a.age<s.age&&(i=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class Hl extends Ae{constructor(e,t,i){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=i??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:me(e-this._offset,0,this._length??1/0)}_read(e,t,i,s){if(this._length!==null&&t>this._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+s),a=o=>o?(o.offset-=this._offset,o):null;return n instanceof Promise?n.then(a):a(n)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}/*! 164 * Copyright (c) 2026-present, Vanilagy and contributors 165 * 166 * This Source Code Form is subject to the terms of the Mozilla Public 167 * License, v. 2.0. If a copy of the MPL was not distributed with this 168 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 169 */var vn=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(s=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");s&&(i=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Fn=(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 i,s=0;function n(){for(;i=e.stack.pop();)try{if(!i.async&&s===1)return s=0,e.stack.push(i),Promise.resolve().then(n);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});const ql=/^0[xX][0-9a-fA-F]+$/,Kl=/^data:.*;base64,/i;class Bn extends Dl{constructor(e,t,i,s){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=s}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await ha(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 k={stack:[],error:void 0,hasError:!1};
169try{const y=vn(k,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),b=await new Ki(y.source).requestEntireFile();p(b),e=zo(b,b.length,{ignore:mo})}catch(y){k.error=y,k.hasError=!0}finally{Fn(k)}}let t=!1,i=0,s=null,n=null,a=0,o=null,c=null,l=null,d=null,u=null,h=null,f=!1,g=ce(this.segments)??null;const m=k=>{const y=k.indexOf("@"),T=Number(y===-1?k:k.slice(0,y));if(!Number.isInteger(T)||T<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${k}'.`);let b=null;if(y!==-1&&(b=Number(k.slice(y+1)),!Number.isInteger(b)||b<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:T,offset:b}},w=k=>{a=k,g&&(p(g.sequenceNumber!==null),g.sequenceNumber<k&&(i=g.timestamp+g.duration,o=g.firstSegment,c=g.initSegment,u=g.lastProgramDateTimeSeconds,g=null))};for(let k=0;k<e.length;k++){const y=e[k];if(!t){if(y!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0;continue}if(!y.startsWith("#")){if(!g){if(s===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let T=n;if(T&&T.method==="AES-128"&&!T.iv){const I=new Uint8Array(Ke),C=q(I);C.setUint32(8,Math.floor(a/2**32)),C.setUint32(12,a),T={...T,iv:I}}const P={path:de(this.path,y),offset:d?.offset??0,length:d?.length??null},x={timestamp:i,relativeToUnixEpoch:u!==null,firstSegment:o,sequenceNumber:a,location:P,duration:s,encryption:T,initSegment:c,lastProgramDateTimeSeconds:u};o??=x,i+=s,this.segments.push(x)}s=null,d===null?l=null:d=null,w(a+1)}if(y.startsWith(or)){if(g){f=!0;continue}f||(u===null&&a>0&&h!==null&&(i=a*h),f=!0);const T=y.slice(or.length),b=T.indexOf(","),P=b===-1?T:T.slice(0,b),x=Number(P);if(!Number.isFinite(x)||x<0)throw new Error(`Invalid #EXTINF tag duration '${P}'.`);s=x}else if(y.startsWith(wn)){const T=new ki(y.slice(wn.length)),b=T.get("uri");if(!b)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const P=T.get("byterange");let x=null;if(P!==null&&(x=m(P)),x&&x.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const C={path:de(this.path,b),offset:x?.offset??0,length:x?.length??null};if(n?.method==="AES-128"&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");c={timestamp:i,relativeToUnixEpoch:u!==null,firstSegment:null,sequenceNumber:null,location:C,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:u}}s=null,d===null?l=null:d=null}else if(y.startsWith(yn)){const T=new ki(y.slice(yn.length)),b=T.get("method");if(b==="NONE")n=null;else if(b==="AES-128"){const P=T.get("uri");if(!P)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let x=null;const I=T.get("iv");if(I){if(!ql.test(I))throw new Error(`Unsupported IV format '${I}'.`);let _=I.slice(2);_=_.padStart(Ke*2,"0"),x=new Uint8Array(Ke);for(let E=0;E<Ke;E++){const R=-Ke*2+E;x[E]=parseInt(_.slice(R,R+2),16)}}const C=T.get("keyformat")??"identity";if(C!=="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.");n={method:"AES-128",keyUri:de(this.path,P),iv:x,keyFormat:C}}else if(b==="SAMPLE-AES"||b==="SAMPLE-AES-CTR"){const P=T.get("uri");if(!P)throw new Error(`Invalid #EXT-X-KEY: ${b} requires a URI attribute.`);if((T.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 I=null;if(Kl.test(P)){const C=P.indexOf(","),_=la(P.slice(C+1));if(_.length>=8&&_[4]===112&&_[5]===115&&_[6]===115&&_[7]===104){const E=q(_).getUint32(0);I=Va(_.subarray(8,Math.min(E,_.length)))}}n={method:b,psshBox:I}}else throw new Error(`Unsupported encryption method '${b}'. If you think this method should be supported, please raise an issue.`)}else if(y.startsWith(Tn)){const T=y.slice(Tn.length),b=Number(T);if(!Number.isInteger(b)||b<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${T}'.`);w(b)}else if(y.startsWith(bn)){const T=m(y.slice(bn.length));if(T.offset===null){if(l===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");T.offset=l}d=T,l=T.offset+T.length}else if(y.startsWith(Sn)){if(g)continue;const T=y.slice(Sn.length),b=Date.parse(T);if(!Number.isFinite(b))continue;const P=b/1e3;if(u===P)continue;if(u===null&&this.segments.length>0){const x=ce(this.segments),I=x.timestamp+x.duration,C=P-I;for(const _ of this.segments)_.timestamp+=C,_.relativeToUnixEpoch=!0;i+=C}u=P,i=P}else if(y===Rl)o=null;else if(y.startsWith(Pn)){const T=y.slice(Pn.length),b=Number(T);
169if(!Number.isFinite(b)||b<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${T}'.`);this.refreshInterval=b,h=b}else if(y===Ml){this.streamHasEnded=!0;break}else y.startsWith(xn)&&y.slice(xn.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 i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const s=G(this.segments,e,a=>a.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||i)return this.segments[s];const n=this.segments[s];if(e<n.timestamp+n.duration)return n;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const i=this.segments.indexOf(e);p(i!==-1);const s=i+1;let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(s<this.segments.length)return this.segments[s];if(this.streamHasEnded||n)return null;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return p(t!==-1),this.segments[t-1]??null}getInputForSegment(e){const t=e,i=this.inputCache.find(c=>c.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let s=null;(t.initSegment||t.firstSegment)&&(s=this.getInputForSegment(t.initSegment??t.firstSegment));const n={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(c=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(c);let l=c.psshBoxes;const{psshBox:d}=t.encryption;return(d.keyIds===null||d.keyIds.includes(c.keyId))&&!l.some(u=>Ha(u,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new Ts({source:new Ul(t.location.path,async c=>{p(c.isRoot);const l={...c,isRoot:!1};let d;const u=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(l),u){const f=d.source.slice(t.location.offset,t.location.length??void 0).ref();d.free(),d=f}}else if(t.encryption.method==="AES-128"){const h=t.encryption;p(h.iv);let f=await this.input._getSourceCached(l);if(u){const k=f.source.slice(t.location.offset,t.location.length??void 0).ref();f.free(),f=k}const g=new Ki(f.source),m=tl(g,async()=>{const w={stack:[],error:void 0,hasError:!1};try{const k=vn(w,await this.input._getSourceCached({path:h.keyUri,isRoot:!1},ku),!1),T=await new Ki(k.source).requestSlice(0,Ke);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:D(T,Ke),iv:h.iv}}catch(k){w.error=k,w.hasError=!0}finally{Fn(w)}},()=>{f.free()});d=new Vl(m).ref()}else p(!1);return d}),formats:this.input._formats.filter(c=>!(c instanceof Co)),initInput:s??void 0,formatOptions:n});if(a._onFormatDetermined=c=>{if((t.encryption?.method==="SAMPLE-AES"||t.encryption?.method==="SAMPLE-AES-CTR")&&!c._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 c=ma(this.inputCache,l=>l.age);p(c!==-1),this.inputCache.splice(c,1)}return a}
169async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}/*! 170 * Copyright (c) 2026-present, Vanilagy and contributors 171 * 172 * This Source Code Form is subject to the terms of the Mozilla Public 173 * License, v. 2.0. If a copy of the MPL was not distributed with this 174 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 175 */class Gl extends lt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{p(this.input._rootSource instanceof ri);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();p(t);const i=zo(t,t.length,{ignore:mo}),s=[],n=[];for(let u=1;u<i.length;u++){const h=i[u];if(h.startsWith(pn)){const f=u,g=i[++u];if(g===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const m=de(e,g),w=new ki(h.slice(pn.length));if(w.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:m,attributes:w,lineNumber:f,hasOnlyKeyPackets:!1})}else if(h.startsWith(gn)){const f=new ki(h.slice(gn.length)),g=f.get("uri");if(g===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.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 w=de(e,g);s.push({fullPath:w,attributes:f,lineNumber:u,hasOnlyKeyPackets:!0})}else if(h.startsWith(kn)){const f=new ki(h.slice(kn.length));if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let w=null;const k=f.get("uri");k!==null&&(w=de(e,k)),n.push({fullPath:w,attributes:f,lineNumber:u})}else if(h!==zl){if(h.startsWith(or)){const f=new Bn(this,e,null,i);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}const a=[...new Set(n.filter(u=>u.attributes.get("type").toLowerCase()==="video").map(u=>u.attributes.get("group-id")))],o=[...new Set(n.filter(u=>u.attributes.get("type").toLowerCase()==="audio").map(u=>u.attributes.get("group-id")))],c=await Promise.all(s.map(async(u,h)=>{const f=[],g=u.attributes.get("codecs");let m;if(g)m=g.split(",").map(_=>_.trim());
175else{const E=await this.getSegmentedInputForPath(u.fullPath).getTrackBackings(),R=await Promise.all(E.map(async v=>({track:v,codec:await v.getCodec()})));m=await Promise.all(R.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(z=>z.codec)))}const w=u.attributes.get("video"),k=u.attributes.get("audio"),y=m.some(_=>_e.includes(mi(_))),T=m.some(_=>Ne.includes(mi(_)));if(w!==null&&!y){if(!a.includes(w))throw new Error(`Invalid M3U8 file; variant stream references video group "${w}" which is not defined in any #EXT-X-MEDIA tags.`);const _=n.find(E=>{const R=E.attributes.get("group-id"),v=E.attributes.get("type");return R===w&&v.toLowerCase()==="video"});e:if(_){const E=_.attributes.get("uri");if(E===null)break e;const R=de(e,E),W=(await this.getSegmentedInputForPath(R).getTrackBackings()).find(U=>U.getType()==="video");if(!W||await W.getCodec()===null)break e;const O=await W.getDecoderConfig().then(U=>U?.codec??null);p(O!==null),m.push(O)}}if(k!==null&&!T){if(!o.includes(k))throw new Error(`Invalid M3U8 file; variant stream references audio group "${k}" which is not defined in any #EXT-X-MEDIA tags.`);const _=n.find(E=>{const R=E.attributes.get("group-id"),v=E.attributes.get("type");return R===k&&v.toLowerCase()==="audio"});e:if(_){const E=_.attributes.get("uri");if(E===null)break e;
175const R=de(e,E),W=(await this.getSegmentedInputForPath(R).getTrackBackings()).find(U=>U.getType()==="audio");if(!W||await W.getCodec()===null)break e;const O=await W.getDecoderConfig().then(U=>U?.codec??null);p(O!==null),m.push(O)}}m=[...new Set(m)];let b=null,P=null;const x=u.attributes.getAsNumber("bandwidth");p(x!==null);const I=u.attributes.getAsNumber("average-bandwidth"),C=u.attributes.get("name");for(const _ of m){const E=mi(_);if(E!==null){if(_e.includes(E)){if(b!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=_;const R=u.attributes.get("video");if(R===null){const v=u.attributes.get("resolution");let z=null,W=null;if(v){const O=v.match(/^(\d+)x(\d+)$/);O&&(z=Number(O[1]),W=Number(O[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:le,lineNumber:u.lineNumber,fullPath:u.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(h),peakBitrate:x,averageBitrate:I,name:C,hasOnlyKeyPackets:u.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 v of n){const z=v.attributes.get("group-id"),W=v.attributes.get("type");if(z!==R||W.toLowerCase()!=="video")continue;const O=v.attributes.get("resolution")??u.attributes.get("resolution");let U=null,j=null;if(O){const ae=O.match(/^(\d+)x(\d+)$/);ae&&(U=Number(ae[1]),j=Number(ae[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Ui(v.attributes),autoselect:Ui(v.attributes)||Rn(v.attributes),languageCode:Mn(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??u.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:v.attributes.get("name"),hasOnlyKeyPackets:u.hasOnlyKeyPackets,info:{type:"video",width:U,height:j}})}}}else if(Ne.includes(E)){if(P!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");P=_;const R=u.attributes.get("audio");if(R===null){const v=u.attributes.get("channels"),z=v!==null?Number(v.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:le,lineNumber:u.lineNumber,fullPath:u.fullPath,fullCodecString:P,pairingMask:1n<<BigInt(h),peakBitrate:x,averageBitrate:I,name:C,hasOnlyKeyPackets:u.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 v of n){const z=v.attributes.get("group-id"),W=v.attributes.get("type");if(z!==R||W.toLowerCase()!=="audio")continue;const O=v.attributes.get("channels")??u.attributes.get("channels"),U=O!==null?Number(O.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Ui(v.attributes),autoselect:Ui(v.attributes)||Rn(v.attributes),languageCode:Mn(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??u.fullPath,fullCodecString:P,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:v.attributes.get("name"),hasOnlyKeyPackets:u.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:U!==null&&Number.isInteger(U)&&U>0?U:null}})}}}}}return f})),l=[],d=u=>{const h=l.find(f=>f.fullPath===u.fullPath&&f.info.type===u.info.type);h?(h.pairingMask|=u.pairingMask,h.default||=u.default,h.autoselect||=u.autoselect,h.lineNumber=Math.min(h.lineNumber,u.lineNumber),u.peakBitrate!==null&&(h.peakBitrate=Math.max(h.peakBitrate??-1/0,u.peakBitrate)),u.averageBitrate!==null&&(h.averageBitrate=Math.max(h.averageBitrate??-1/0,u.averageBitrate)),h.languageCode===le&&(h.languageCode=u.languageCode)):(u.id=l.length+1,l.push(u))};for(const u of c)for(const h of u)d(h);l.sort((u,h)=>u.lineNumber-h.lineNumber),this.trackBackings=[];for(const u of l)u.info.type==="video"?this.trackBackings.push(new So(u)):this.trackBackings.push(new Po(u));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),p(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(s=>s.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(n=>n.fullPath===e).map(n=>({id:n.id,type:n.info.type}))),t=new Bn(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Yt}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class bo{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const s=(await e.getTrackBackings()).filter(n=>n.getType()===this.getType());if(s.length===1)t=s[0];else if(this instanceof So){for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}else{p(this instanceof Po);for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;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{...ct,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(){p(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===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)}
vendor: 1,594 bytes, line 175
175async 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 So extends bo{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return mi(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()}
175async 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 Po extends bo{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return mi(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 Ui=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}".`)},Rn=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}".`)},Mn=r=>{if(r===null)return le;const e=r.split("-")[0];return e||le};/*! 176 * Copyright (c) 2026-present, Vanilagy and contributors 177 * 178 * This Source Code Form is subject to the terms of the Mozilla Public 179 * License, v. 2.0. If a copy of the MPL was not distributed with this 180 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 181 */class Xe{constructor(){this._isIsobmff=!1}}class xo extends Xe{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 i=te(t,4);return i!=="ftyp"&&i!=="styp"?null:te(t,4)}_createDemuxer(e){return new Rr(e)}}class Xl extends xo{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let i=e._reader.requestSlice(4,4);if(i instanceof Promise&&(i=await i),!i)return!1;const s=te(i,4);return s==="moof"||s==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class jl extends xo{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class _o extends Xe{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,et);if(i instanceof Promise&&(i=await i),!i)return!1;const s=Ya(i);if(s===null||s<1||s>8||H(i,s)!==S.EBML)return!1;const a=Za(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-Ie;){const l=Ze(o);if(!l)break;const{id:d,size:u}=l,h=o.filePos;if(u===void 0)return!1;switch(d){case S.EBMLVersion:if(H(o,u)!==1)return!1;break;case S.EBMLReadVersion:if(H(o,u)!==1)return!1;break;case S.DocType:if(Vt(o,u)!==t)return!1;break;case S.DocTypeVersion:if(H(o,u)>4)return!1;break}o.filePos=h+u}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new hl(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ql extends _o{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class $l extends Xe{async _canReadInput(e){let t=0;for(;;){let u=e._reader.requestSlice(t,at);if(u instanceof Promise&&(u=await u),!u)break;const h=Bt(u);if(!h)break;t=u.filePos+h.size}const i=await nr(e._reader,t,t+4096);if(!i)return!1;const s=i.header,n=us(s.mpegVersionId,s.channel);let a=e._reader.requestSlice(i.startPos+n,4);if(a instanceof Promise&&(a=await a),!a)return!1;const o=F(a);if(o===ls||o===Cr)return!0;t=i.startPos+i.header.totalSize;const l=await nr(e._reader,t,t+At);if(!l)return!1;const d=l.header;return!(s.channel!==d.channel||s.sampleRate!==d.sampleRate)}_createDemuxer(e){return new pl(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}
181class Yl extends Xe{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=te(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),te(t,4)==="WAVE")}_createDemuxer(e){return new bl(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Zl extends Xe{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?te(t,4)==="OggS":!1}_createDemuxer(e){return new yl(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Jl extends Xe{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?te(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new El(e)}}class eu extends Xe{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,at);if(a instanceof Promise&&(a=await a),!a)break;const o=Bt(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,_i,kt);if(i instanceof Promise&&(i=await i),!i)return!1;const s=nt(i);if(!s||(t+=s.frameLength,i=e._reader.requestSliceRange(t,_i,kt),i instanceof Promise&&(i=await i),!i))return!1;const n=nt(i);return n?s.objectType===n.objectType&&s.samplingFrequencyIndex===n.samplingFrequencyIndex&&s.channelConfiguration===n.channelConfiguration:!1}_createDemuxer(e){return new Pl(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class tu extends Xe{async _canReadInput(e){const t=pe+16+1;let i=e._reader.requestSlice(0,t);if(i instanceof Promise&&(i=await i),!i)return!1;const s=D(i,t);return s[0]===71&&s[pe]===71||s[0]===71&&s[pe+16]===71?!0:s[4]===71&&s[4+pe+4]===71}_createDemuxer(e){return new vl(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Co extends Xe{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(te(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof ri))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 Gl(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Yt}}const Io=new Xl,Eo=new jl,iu=new _o,su=new Ql,Ao=new $l,ru=new Yl,nu=new Zl,vo=new eu,au=new Jl,Fo=new tu,Bo=new Co,vh=[Bo,Io,Eo,iu,su,ru,nu,au,Ao,vo,Fo],Fh=[Bo,Io,Eo,Ao,vo,Fo],ou=(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.`)}};/*! 182 * Copyright (c) 2026-present, Vanilagy and contributors 183 * 184 * This Source Code Form is subject to the terms of the Mozilla Public 185 * License, v. 2.0. If a copy of the MPL was not distributed with this 186 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 187 */const cu=r=>{let i=r,s=4096,n=0,a=12,o=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&s)!==s&&a>=5;)s>>=1,a--;return o=i>>a-4&15,~(n|a-5<<4|o)&255},lu=r=>{let t=0,i=0,s=~r;s&128&&(s&=-129,t=-1),i=((s&240)>>4)+5;const n=(1<<i|(s&15)<<i-4|1<<i-5)-33;return t===0?n:-n},uu=r=>{let t=2048,i=0,s=11,n=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(i|s-4<<4|n)^85},du=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let s=0;return t!==4?s=1<<t|(i&15)<<t-4|1<<t-5:s=i<<1|1,e===0?s:-s};/*! 188 * Copyright (c) 2026-present, Vanilagy and contributors 189 * 190 * This Source Code Form is subject to the terms of the Mozilla Public 191 * License, v. 2.0. If a copy of the MPL was not distributed with this 192 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 193 */const St=r=>{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.")},rt=r=>{if(!ii(r))throw new TypeError("timestamp must be a number.")},Fs=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const s=await r.determinePacketType(i);return s&&(i.type=s),i}):e;class Ci{constructor(e){if(!(e instanceof vi))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(St(e),this._track.input._disposed)throw new be;return Fs(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){St(e);const t=await this.getFirstPacket(e);
193return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(rt(e),St(t),this._track.input._disposed)throw new be;return Fs(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(St(t),this._track.input._disposed)throw new be;return Fs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(rt(e),St(t),this._track.input._disposed)throw new be;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);return i&&(p(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i)}async getNextKeyPacket(e,t={}){if(!(e instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(St(t),this._track.input._disposed)throw new be;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return i&&(p(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof ee))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof ee))throw new TypeError("endPacket must be an EncodedPacket.");if(St(i),this._track.input._disposed)throw new be;const s=[];let{promise:n,resolve:a}=J(),{promise:o,resolve:c}=J(),l=!1,d=!1,u=null;const h=[],f=()=>Math.max(2,h.length);(async()=>{let m=e??await this.getFirstPacket(i);for(;m&&!d&&!this._track.input._disposed&&!(t&&m.sequenceNumber>=t?.sequenceNumber);){if(s.length>f()){({promise:o,resolve:c}=J()),await o;continue}s.push(m),a(),{promise:n,resolve:a}=J(),m=await this.getNextPacket(m,i)}l=!0,a()})().catch(m=>{u||(u=m,a())});const g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new be;if(d)return{value:void 0,done:!0};if(u)throw u;if(s.length>0){const m=s.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:m,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return d=!0,c(),a(),{value:void 0,done:!0}},async throw(m){throw m},[Symbol.asyncIterator](){return this}}}}class Nr{constructor(e,t){this.onSample=e,this.onError=t}}class Ro{mediaSamplesInRange(e=-1/0,t=1/0,i){rt(e),rt(t);const s=[];let n=!1,a=null,{promise:o,resolve:c}=J(),{promise:l,resolve:d}=J(),u=!1,h=!1,f=!1,g=null;const m={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const y=await this._createDecoder(C=>{if(d(),C.timestamp>=t&&(h=!0),h){C.close();return}a&&(C.timestamp>e?(s.push(a),n=!0):a.close()),C.timestamp>=e&&(s.push(C),n=!0),a=n?null:C,s.length>0&&(c(),{promise:o,resolve:c}=J())},C=>{g||(g=C,c())}),T=this._createPacketSink(),b=await T.getKeyPacket(e,m)??await T.getFirstKeyPacket(m);let P=b;const I=T.packets(b??void 0,void 0,m);for(await I.next();P&&!h&&!this._track.input._disposed;){const C=zn(s.length);if(s.length+y.getDecodeQueueSize()>C){({promise:l,resolve:d}=J()),await l;continue}y.decode(P);const _=await I.next();if(_.done)break;P=_.value}await I.return(),!f&&!this._track.input._disposed&&await y.flush(),y.close(),!n&&a&&s.push(a),u=!0,c()})().catch(y=>{g||(g=y,c())});const w=this._track,k=()=>{a?.close();for(const y of s)y.close()};return{async next(){for(;;){if(w.input._disposed)throw k(),new be;if(f)return{value:void 0,done:!0};if(g)throw k(),g;if(s.length>0){const y=s.shift();return d(),{value:y,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,h=!0,d(),c(),k(),{value:void 0,done:!0}},async throw(y){throw y},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){mc(e);const i=pc(e),s=[],n=[];let{promise:a,resolve:o}=J(),{promise:c,resolve:l}=J(),d=!1,u=!1,h=null;const f=k=>{n.push(k),o(),{promise:a,resolve:o}=J()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const k=await this._createDecoder(C=>{if(l(),u){C.close();return}let _=0;for(;s.length>0&&C.timestamp-s[0]>-1e-10;)_++,s.shift();if(_>0)for(let E=0;E<_;E++)f(E<_-1?C.clone():C);else C.close()},C=>{h||(h=C,o())}),y=this._createPacketSink();let T=null,b=null,P=-1;const x=async()=>{p(b);let C=b;for(k.decode(C);C.sequenceNumber<P;){const _=zn(n.length);for(;n.length+k.getDecodeQueueSize()>_&&!u;)({promise:c,resolve:l}=J()),await c;if(u)break;const E=await y.getNextPacket(C,g);p(E),k.decode(E),C=E}P=-1},I=async()=>{await k.flush();for(let C=0;C<s.length;C++)f(null);s.length=0};for await(const C of i){if(rt(C),u||this._track.input._disposed)break;const _=await y.getPacket(C,g),E=_&&await y.getKeyPacket(C,g);
193if(!E){P!==-1&&(await x(),await I()),f(null),T=null;continue}T&&(E.sequenceNumber!==b.sequenceNumber||_.timestamp<T.timestamp)&&(await x(),await I()),s.push(_.timestamp),P=Math.max(_.sequenceNumber,P),T=_,b=E}!u&&!this._track.input._disposed&&(P!==-1&&await x(),await I()),k.close(),d=!0,o()})().catch(k=>{h||(h=k,o())});const m=this._track,w=()=>{for(const k of n)k?.close()};return{async next(){for(;;){if(m.input._disposed)throw w(),new be;if(u)return{value:void 0,done:!0};if(h)throw w(),h;if(n.length>0){const k=n.shift();return p(k!==void 0),l(),{value:k,done:!1}}else if(!d)await a;else return{value:void 0,done:!0}}},async return(){return u=!0,l(),o(),w(),{value:void 0,done:!0}},async throw(k){throw k},[Symbol.asyncIterator](){return this}}}}const zn=r=>r===0?40:8;class hu extends Nr{constructor(e,t,i,s,n,a){super(e,t),this.codec=i,this.decoderConfig=s,this.rotation=n,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new bi,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 bi;const o=wa.find(c=>c.supports(i,s));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof Ee))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const c=d=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){const u=this.alphaQueue.shift();p(u!==void 0),await this.mergeAlpha(d,u)}else this.colorQueue.push(d)}).catch(u=>this.onError(u))};if(i==="avc"&&this.decoderConfig.description&&Ks()){const d=Aa(ie(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){const u=vr(d.sequenceParameterSets[0]);u&&u.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const l=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{c(d)}catch(u){this.onError(u)}},error:d=>{d.stack=l,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>
1930&&!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(p(this.decoder),Hi()||Yr(this.inputTimestamps,e.timestamp,t=>t),Ks()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];for(const s of Ea(e.data,this.decoderConfig)){const n=Jt(e.data[s.offset]);n===Pe.AUD&&(t.length=0),n>=20&&n<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}const i=Dc(t,this.decoderConfig);e=new ee(i,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Xc(e.data,this.decoderConfig);t&&(e=new ee(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 ks),!this.alphaDecoder){const i=n=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();p(a!==void 0),await this.mergeAlpha(a,n)}else this.alphaQueue.push(n);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();p(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},s=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:n=>{try{i(n)}catch(a){this.onError(a)}},error:n=>{n.stack=s,this.onError(n)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ps(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>
1930&&!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 es(e,this.decoderConfig)){const i=yt(e[t.offset]);if(i===ne.RASL_N||i===ne.RASL_R)return!0}return!1}sampleHandler(e){if(Hi()){if(this.sampleQueue.length>0&&e.timestamp>=ce(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Yr(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();p(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 n=new Ee(e);this.sampleHandler(n);return}p(this.merger);const i=await this.merger.update(e,t),s=new Ee(i);this.sampleHandler(s)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Hi()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Dn=!1;class ks{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(!ks.forceCpu&&e&&!Dn)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,Dn=!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(){p(this.gl);const e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es 194 in vec2 a_position; 195 in vec2 a_texCoord; 196 out vec2 v_texCoord; 197 198 void main() { 199 gl_Position = vec4(a_position, 0.0, 1.0); 200 v_texCoord = a_texCoord; 201 } 202 `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es 203 precision highp float; 204 205 uniform sampler2D u_colorTexture; 206 uniform sampler2D u_alphaTexture; 207 in vec2 v_texCoord; 208 out vec4 fragColor; 209 210 void main() { 211 vec3 color = texture(u_colorTexture, v_texCoord).rgb; 212 float alpha = texture(u_alphaTexture, v_texCoord).r; 213 fragColor = vec4(color, alpha); 214 } 215 `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){p(this.gl);const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){p(this.gl),p(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]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){p(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}
215updateGpu(e,t){p(this.gl),p(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 i=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),i}updateCpu(e,t){if(!this.worker){const n=new Blob([`(${fu.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(n);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 i=this.nextRequestId++,s=J();return this.pendingRequests.set(i,s),this.worker.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),s.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}ks.forceCpu=!0;const fu=()=>{let r=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:l,color:d,alpha:u}=c.data;t=t.then(async()=>{try{const h=await i(d,u);self.postMessage({id:l,frame:h},{transfer:[h]})}catch(h){self.postMessage({id:l,error:h.message})}finally{d.close(),u.close()}})});const i=async(c,l)=>{const d=c.format,u=l.format;if(!d||!u)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const h=d.includes("P10"),f=d.includes("P12"),g=u.includes("P10"),m=u.includes("P12");if(g!==h||m!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${d}', alpha: '${u}').`);const w=c.codedWidth,k=c.codedHeight;if(d==="RGBX"||d==="RGBA"||d==="BGRX"||d==="BGRA")return await s(c,l,w,k,d);if(d==="I420"||d==="I420P10"||d==="I420P12"||d==="I422"||d==="I422P10"||d==="I422P12"||d==="I444"||d==="I444P10"||d==="I444P12")return await n(c,l,w,k,d);if(d==="NV12")return await a(c,l,w,k);throw new Error(`CPU color/alpha merging does not support format '${d}'.`)},s=async(c,l,d,u,h)=>{const f=d*u,g=new Uint8Array(f*4);await c.copyTo(g);const m=await o(l,d,u,1);for(let y=0,T=3;y<f;y++,T+=4)g[T]=m[y];const k={format:h==="RGBX"||h==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:u,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,k)},n=async(c,l,d,u,h)=>{const f=h.includes("P10"),g=h.includes("P12"),m=f||g?2:1;let w,k;h.startsWith("I420")?(w=Math.ceil(d/2),k=Math.ceil(u/2)):h.startsWith("I422")?(w=Math.ceil(d/2),k=u):(w=d,k=u);const y=d*u,T=w*k,b=y*m,P=T*m,x=y*m,I=b+2*P+x,C=new Uint8Array(I);await c.copyTo(C);const _=await o(l,d,u,m),E=b+2*P;C.set(_,E);const v={format:h.slice(0,4)+"A"+h.slice(4),codedWidth:d,codedHeight:u,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,v)},a=async(c,l,d,u)=>{const h=d*u,f=Math.ceil(d/2),g=Math.ceil(u/2),m=f*g,w=c.allocationSize();(!e||e.byteLength!==w)&&(e=new Uint8Array(w)),await c.copyTo(e);const k=new Uint8Array(h+2*m+h);k.set(e.subarray(0,h),0);const y=h,T=h+m,b=h;for(let I=0;I<m;I++)k[y+I]=e[b+I*2],k[T+I]=e[b+I*2+1];const P=await o(l,d,u,1);k.set(P,h+2*m);const x={format:"I420A",codedWidth:d,codedHeight:u,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[k.buffer]};return new VideoFrame(k,x)},o=async(c,l,d,u)=>{const h=c.allocationSize();(!r||r.byteLength!==h)&&(r=new Uint8Array(h)),await c.copyTo(r);const f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){const g=f==="RGBA"||f==="RGBX"?0:2,m=l*d;for(let w=0;w<m;w++)r[w]=r[w*4+g];return r.subarray(0,m)}else return r.subarray(0,l*d*u)}};class lr extends Ro{constructor(e){if(!(e instanceof ws))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 i=await this._track.getCodec(),s=await this._track.getRotation(),n=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return p(i&&n),new hu(e,t,i,n,s,a)}_createPacketSink(){return new Ci(this._track)}async getSample(e,t={}){rt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Bh{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof ws))throw new TypeError("videoTrack must be an InputVideoTrack.");
215if(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&&pa(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 lr(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),s=await t.getSquarePixelWidth(),n=await t.getSquarePixelHeight(),[a,o]=i%180===0?[s,n]:[n,s];let c=e.crop;c&&(c=ga(c,a,o));let[l,d]=c?[c.width,c.height]:[a,o];const u=l/d;e.width!==void 0&&e.height===void 0?(l=e.width,d=Math.round(l/u)):e.width===void 0&&e.height!==void 0?(d=e.height,l=Math.round(d*u)):e.width!==void 0&&e.height!==void 0&&(l=e.width,d=e.height),this._width=l,this._height=d,this._rotation=i,this._crop=c})()}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let s=this._canvasPool[this._nextCanvasIndex],n=!1;s||(typeof document<"u"?(s=document.createElement("canvas"),s.width=t,s.height=i):s=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=s),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=s.getContext("2d",{alpha:this._alpha||$r()});p(a),a.resetTransform(),n||(!this._alpha&&$r()?(a.fillStyle="black",a.fillRect(0,0,t,i)):a.clearRect(0,0,t,i)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:s,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){rt(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*$i(this._videoSampleSink.samples(e,t,i),s=>this._videoSampleToWrappedCanvas(s))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*$i(this._videoSampleSink.samplesAtTimestamps(e,t),i=>i&&this._videoSampleToWrappedCanvas(i))}}class mu extends Nr{constructor(e,t,i,s){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new bi,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=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 d=s.sampleRate;o.setTimestamp(Math.round(l*d)/d),e(o)},a=ka.find(o=>o.supports(i,s));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=o=>{if(!(o instanceof Le))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{n(new Le(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(s)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(p(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.close())}}class pu extends Nr{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,p(ot.includes(i.codec)),this.codec=i.codec;const{dataType:s,sampleSize:n,littleEndian:a}=Ue(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>lu(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>du(o.getUint8(c)):p(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):p(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>gr(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>gc(o,c,a):p(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):p(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):p(!1);break;default:ge(n),p(!1)}switch(n){case 1:s==="ulaw"||s==="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)=>
215o.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,s==="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:ge(n),p(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=q(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,s=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let d=0;d<i*this.decoderConfig.numberOfChannels;d++){const u=d*this.inputSampleSize,h=d*this.outputSampleSize,f=this.readInputValue(t,u);this.writeOutputValue(a,h,f)}const o=i/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 Le({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class ur extends Ro{constructor(e){if(!(e instanceof ys))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 i=await this._track.getCodec(),s=await this._track.getDecoderConfig();return p(i&&s),ot.includes(s.codec)?new pu(e,t,s):new mu(e,t,i,s)}_createPacketSink(){return new Ci(this._track)}async getSample(e,t={}){rt(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Rh{constructor(e){if(!(e instanceof ys))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new ur(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){rt(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return $i(this._audioSampleSink.samples(e,t,i),s=>this._audioSampleToWrappedArrayBuffer(s))}buffersAtTimestamps(e,t){return $i(this._audioSampleSink.samplesAtTimestamps(e,t),i=>i&&this._audioSampleToWrappedArrayBuffer(i))}}/*! 216 * Copyright (c) 2026-present, Vanilagy and contributors 217 * 218 * This Source Code Form is subject to the terms of the Mozilla Public 219 * License, v. 2.0. If a copy of the MPL was not distributed with this 220 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 221 */class vi{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof ws}isAudioTrack(){return this instanceof ys}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Y(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Y(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Y(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Y(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Y(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}
221),i=(t?.timestamp??0)+(t?.duration??0);return Zt(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new Ci(this);let s=1/0,n=-1/0,a=0,o=0;for await(const c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=n)break;s=Math.min(s,c.timestamp),n=Math.max(n,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(n-s)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(n-s)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof vi))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(_t({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(_t({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(_t({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(_t({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(_t({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Bs(e);const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Bs(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Bs(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Y=(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},Bs=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return s},i=r(e);return i instanceof Promise?i.then(t):t(i)}:void 0};class ws extends vi{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 Y(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Y(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Y(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Y(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Y(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Y(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Yi({num:await this.get
221SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Yi({num:Y(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Y(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Y(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Y(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){const s=Y(e,"displayWidth","getDisplayWidth");if(s!==null)return s}const i=Y(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Y(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){const s=Y(e,"displayHeight","getDisplayHeight");if(s!==null)return s}const i=Y(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Y(i,"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==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}
221async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return p(t!==null),wa.some(s=>s.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 ee))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 i=await this.getDecoderConfig();return p(i),ps(t,i,e.data)}}class ys extends vi{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Y(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Y(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Y(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return p(t!==null),ka.some(i=>i.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 ee))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Mh=r=>r??1/0,Un=r=>-(r??-1/0),ai=r=>-r,oi=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=s=>{if(typeof s!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return s},i=r.filter(e);return i instanceof Promise?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{const t=s=>{if(typeof s!="number"&&(!Array.isArray(s)||!s.every(n=>typeof n=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return s},i=r.sortBy(e);return i instanceof Promise?i.then(t):t(i)}:void 0}},_t=(r,e)=>({filter:r?.filter||e?.filter?t=>{const i=r?.filter?.(t)??!0,s=n=>n===!1?!1:e?.filter?.(t)??!0;return i instanceof Promise?i.then(s):s(i)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{const i=r?.sortBy?.(t)??[],s=e?.sortBy?.(t)??[],n=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([a,o])=>n(a,o)):n(i,s)}:void 0}),Rs=async(r,e)=>{let t=r;if(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,d)=>c[d])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;const i=t.map(a=>e.sortBy(a)),n=i.some(a=>a instanceof Promise)?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:n[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],d=Math.max(c.length,l.length);for(let u=0;u<d;u++){const h=c[u]??0,f=l[u]??0;if(h!==f)return h-f}return 0}).map(a=>a.track)};/*! 222 * Copyright (c) 2026-present, Vanilagy and contributors 223 * 224 * This Source Code Form is subject to the terms of the Mozilla Public 225 * License, v. 2.0. If a copy of the MPL was not distributed with this 226 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 227 */fa();const gu=1,ku=2;class Ts extends os{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 Xe)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ae||e.source instanceof Dr))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ae&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Ts))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&ou(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Ae?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){p(this._rootSource instanceof ri);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=gu){const i=this._sourceCache.find(a=>a.cacheGroup===t&&En(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const s=this._sourceCachePromises.find(a=>a.cacheGroup===t&&En(a.request,e));if(s)return s.promise.then(a=>a.sourceRef.source.ref());const n=(async()=>{const a=await this._getSourceUncached(e);if(di(this._sourceCache,u=>
227u.cacheGroup===t&&u.sourceRef.source._refCount===1)>=4){const u=ma(this._sourceCache,f=>f.cacheGroup===t&&f.sourceRef.source._refCount===1?f.age:1/0);p(u!==-1);const h=this._sourceCache[u];this._sourceCache.splice(u,1),h.sourceRef.free(),kc(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(u=>u.request===e);return p(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:n}),n.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Ki(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new On})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),p(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof On)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const t=e.filter(s=>s!==null);if(t.length===0)return 0;const i=await Promise.all(t.map(s=>s.getFirstTimestamp()));return Math.min(...i)}async computeDuration(e,t){e??=await this.getTracks();const i=e.filter(n=>n!==null);if(i.length===0)return 0;const s=await Promise.all(i.map(n=>n.computeDuration(t)));return Math.max(...s)}async getDurationFromMetadata(e,t){e??=await this.getTracks();const i=e.filter(a=>a!==null),n=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return n.length===0?null:Math.max(...n)}async getTracks(e){e&&=oi(e);const i=(await this._getTrackBackings()).map(s=>this._wrapBackingAsTrack(s));return Rs(i,e)}async getVideoTracks(e){e&&=oi(e);const i=(await this.getTracks()).filter(s=>s.isVideoTrack());return Rs(i,e)}async getAudioTracks(e){e&&=oi(e);const i=(await this.getTracks()).filter(s=>s.isAudioTrack());return Rs(i,e)}async getPrimaryVideoTrack(e){e&&=oi(e);const t=_t(e,{sortBy:async s=>[ai((await s.getDisposition()).default),ai(await s.hasPairableAudioTrack()),ai(!await s.hasOnlyKeyPackets()),Un(await s.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=oi(e);const t=await this.getPrimaryVideoTrack(),i=_t(e,{sortBy:async n=>[ai(!t||n.canBePairedWith(t)),ai((await n.getDisposition()).default),Un(await n.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const s=e.getType()==="video"?new ws(this,e):new ys(this,e);return this._backingToTrack.set(e,s),s}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise?.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class On extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class be extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*! 228 * Copyright (c) 2026-present, Vanilagy and contributors 229 * 230 * This Source Code Form is subject to the terms of the Mozilla Public 231 * License, v. 2.0. If a copy of the MPL was not distributed with this 232 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 233 */class Ki{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 be;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const n=new Uint8Array(0);return new fe(n,q(n),0,e,e)}const i=e+t,s=this.source._read(e,i,go,ko);return s instanceof Promise?s.then(n=>n?new fe(n.bytes,n.view,n.offset,e,i):null):s?new fe(s.bytes,s.view,s.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new be;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,me(this.fileSizeNonStrict-e,t,i));{const s=this.requestSlice(e,i),n=a=>a||(p(this.fileSizeNonStrict!==null),this.requestSlice(e,me(this.fileSizeNonStrict-e,t,i)));return s instanceof Promise?s.then(n):n(s)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(a instanceof Promise&&(a=await a),!a||a.length===0)break;const o=D(a,a.length);t.push(o),i+=a.length}const s=new Uint8Array(i);let n=0;for(const a of t)s.set(a,n),n+=a.length;return new fe(s,q(s),0,0,i)})()}}class fe{constructor(e,t,i,s,n){this.bytes=e,this.view=t,this.offset=i,this.start=s,this.end=n,this.bufferPos=s-i}static tempFromBytes(e){return new fe(e,q(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 fe(this.bytes,this.view,this.offset,e,e+t)}}const we=(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.`)},D=(r,e)=>{we(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},M=r=>(we(r,1),r.view.getUint8(r.bufferPos++)),ci=(r,e)=>{we(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},re=r=>{we(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},$e=r=>{we(r,3);const e=gr(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},dr=r=>{we(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},gt=(r,e)=>{we(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},F=r=>{we(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},qt=r=>
233{we(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},Et=r=>{we(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},wu=r=>{we(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},Nn=(r,e)=>{let t,i;return e?(t=gt(r,!0),i=gt(r,!0)):(i=gt(r,!1),t=gt(r,!1)),i*4294967296+t},Ce=r=>{const e=F(r),t=F(r);return e*4294967296+t},yu=r=>{const e=Et(r),t=F(r);return e*4294967296+t},Tu=r=>{const e=qt(r);return wu(r)*4294967296+e},bu=r=>{we(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},Mo=r=>{we(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},te=(r,e)=>{we(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},zo=(r,e,t)=>xe.decode(D(r,e)).split(` 234`).map(n=>n.trim()).filter(n=>n.length>0&&!t?.ignore?.(n));/*! 235 * Copyright (c) 2026-present, Vanilagy and contributors 236 * 237 * This Source Code Form is subject to the terms of the Mozilla Public 238 * License, v. 2.0. If a copy of the MPL was not distributed with this 239 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 240 */var Kt;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(Kt||(Kt={}));var oe;(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"})(oe||(oe={}));const Gi=128,at=10,Gt=["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
240p-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"],Su=(r,e)=>{const t=r.filePos;e.raw??={},e.raw.TAG??=D(r,Gi-3),r.filePos=t;const i=Dt(r,30);i&&(e.title??=i);const s=Dt(r,30);s&&(e.artist??=s);const n=Dt(r,30);n&&(e.album??=n);const a=Dt(r,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??=new Date(String(o)));const c=D(r,30);let l;if(c[28]===0&&c[29]!==0){const u=c[29];u>0&&(e.trackNumber??=u),r.skip(-30),l=Dt(r,28),r.skip(2)}else r.skip(-30),l=Dt(r,30);l&&(e.comment??=l);const d=M(r);d<Gt.length&&(e.genre??=Gt[d])},Dt=(r,e)=>{const t=D(r,e),i=Ut(t.indexOf(0),t.length),s=t.subarray(0,i);let n="";for(let a=0;a<s.length;a++)n+=String.fromCharCode(s[a]);return n.trimEnd()},Bt=r=>{const e=r.filePos,t=te(r,3),i=M(r),s=M(r),n=M(r),a=F(r);if(t!=="ID3"||i===255||s===255||(a&2155905152)!==0)return r.filePos=e,null;const o=Ys(a);return{majorVersion:i,revision:s,flags:n,size:o}},Lr=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=D(r,e.size),s=new Pu(e,i);if(e.flags&Kt.Footer&&s.removeFooter(),e.flags&Kt.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Kt.ExtendedHeader){const n=s.readU32();e.majorVersion===3?s.pos+=n:s.pos+=n-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const n=s.readId3V2Frame();if(!n)break;const a=s.pos,o=s.pos+n.size;let c=!1,l=!1,d=!1;if(e.majorVersion===3?(c=!!(n.flags&64),l=!!(n.flags&128)):e.majorVersion===4&&(c=!!(n.flags&4),l=!!(n.flags&8),d=!!(n.flags&2)||!!(e.flags&Kt.Unsynchronisation)),c){console.warn(`Skipping encrypted ID3v2 frame ${n.id}`),s.pos=o;continue}if(l){console.warn(`Skipping compressed ID3v2 frame ${n.id}`),s.pos=o;continue}if(d&&s.ununsynchronizeRegion(s.pos,o),t.raw??={},n.id==="TXXX"){const u=t.raw.TXXX??={},h=s.readId3V2TextEncoding(),f=s.readId3V2Text(h,o),g=s.readId3V2Text(h,o);u[f]??=g}else n.id[0]==="T"?t.raw[n.id]??=s.readId3V2EncodingAndText(o):t.raw[n.id]??=s.readBytes(n.size);switch(s.pos=a,n.id){case"TIT2":case"TT2":t.title??=s.readId3V2EncodingAndText(o);break;case"TIT3":case"TT3":t.description??=s.readId3V2EncodingAndText(o);break;case"TPE1":case"TP1":t.artist??=s.readId3V2EncodingAndText(o);break;case"TALB":case"TAL":t.album??=s.readId3V2EncodingAndText(o);break;case"TPE2":case"TP2":t.albumArtist??=s.readId3V2EncodingAndText(o);break;case"TRCK":case"TRK":{const h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),g=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(t.trackNumber??=f),g&&Number.isInteger(g)&&g>0&&(t.tracksTotal??=g)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(o).split("/"),f=Number.parseInt(h[0],10),g=h[1]&&Number.parseInt(h[1],10);Number.isInteger(f)&&f>0&&(t.discNumber??=f),g&&Number.isInteger(g)&&g>0&&(t.discsTotal??=g)}break;case"TCON":case"TCO":{const u=s.readId3V2EncodingAndText(o);let h=/^\((\d+)\)/.exec(u);if(h){const f=Number.parseInt(h[1]);if(Gt[f]!==void 0){t.genre??=Gt[f];break}}if(h=/^\d+$/.exec(u),h){const f=Number.parseInt(h[0]);if(Gt[f]!==void 0){t.genre??=Gt[f];break}}t.genre??=u}break;case"TDRC":case"TDAT":{const u=s.readId3V2EncodingAndText(o),h=new Date(u);Number.isNaN(h.getTime())||(t.date??=h)}break;case"TYER":case"TYE":{const u=s.readId3V2EncodingAndText(o),h=Number.parseInt(u,10);Number.isInteger(h)&&(t.date??=new Date(String(h)))}break;case"USLT":case"ULT":{const u=s.readU8();s.pos+=3,s.readId3V2Text(u,o),t.lyrics??=s.readId3V2Text(u,o)}break;case"COMM":case"COM":{const u=s.readU8();s.pos+=3,s.readId3V2Text(u,o),t.comment??=s.readId3V2Text(u,o)}break;case"APIC":case"PIC":{const u=s.readId3V2TextEncoding();let h;if(e.majorVersion===2){const w=s.readAscii(3);
240h=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else h=s.readId3V2Text(u,o);const f=s.readU8(),g=s.readId3V2Text(u,o).trimEnd(),m=o-s.pos;if(m>=0){const w=s.readBytes(m);t.images||(t.images=[]),t.images.push({data:w,mimeType:h,kind:f===3?"coverFront":f===4?"coverBack":"unknown",description:g})}}break;default:s.pos+=n.size;break}s.pos=o}};class Pu{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 i=this.bytes[t];e.push(i),i===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 i=[];for(let a=e;a<t;a++){const o=this.bytes[a];i.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}const s=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(s.length+i.length+n.length),this.bytes.set(s,0),this.bytes.set(i,s.length),this.bytes.set(n,s.length+i.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-at),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 i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));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 i=this.header.majorVersion===4?Ys(t):t;const s=this.readU16(),n=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(i)){const o=this.header.majorVersion===4?t:Ys(t);a(o)&&(i=o)}return this.pos=n,{id:e,size:i,flags:s}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,s=this.readBytes(t-this.pos);switch(e){case oe.ISO_8859_1:{let n="";for(let a=0;a<s.length;a++){const o=s[a];if(o===0){this.pos=i+a+1;break}n+=String.fromCharCode(o)}return n}case oe.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){const n=new TextDecoder("utf-16le"),a=Ut(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){const n=new TextDecoder("utf-16be"),a=Ut(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{const n=Ut(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),xe.decode(s.subarray(0,n))}case oe.UTF_16_BE_NO_BOM:{const n=new TextDecoder("utf-16be"),a=Ut(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=i+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case oe.UTF_8:{const n=Ut(s.findIndex(a=>a===0),s.length);return this.pos=i+Math.min(n+1,s.length),xe.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Wr{constructor(e){this.helper=new Uint8Array(8),this.helperView=q(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 i=this.writer.getPos(),s=new Set;for(const{key:o,value:c}of ei(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),s.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),s.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),s.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),s.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),s.add("TPE2");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),s.add("TRCK")}break;case"discNumber":{const l=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),s.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),s.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),s.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(c),s.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),s.add("COMM");break;case"images":{const l={coverFront:3,coverBack:4,unknown:0};for(const d of c){const u=l[d.kind]??0,h=d.description??"";this.writeId3V2ApicFrame(d.mimeType,u,h,d.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ge(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||s.has(o))continue;let l;if(typeof c=="string")if(je(c)){l=new Uint8Array(c.length+2),l[0]=oe.ISO_8859_1;for(let u=0;u<c.length;u++)l[u+1]=c.charCodeAt(u)}else{const u=$.encode(c);l=new Uint8Array(u.byteLength+2),l[0]=oe.UTF_8,l.set(u,1)}else if(c instanceof Uint8Array)l=c;else if(o==="TXXX"&&ca(c)){for(const d in c){const u=c[d],h=je(d)&&je(u),f=h?null:$.encode(d),g=h?null:$.encode(u),m=h?d.length:f.byteLength,w=h?u.length:g.byteLength,k=1+m+1+w+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(k),this.writeU16(0),this.writeU8(h?oe.ISO_8859_1:oe.UTF_8),h?(this.writeIsoString(d),this.writeIsoString(u)):(this.writer.write(f),this.writeU8(0),this.writer.write(g),this.writeU8(0))}continue}else continue;this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}const n=this.writer.getPos(),a=n-i;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(n),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(zc(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);this.writer.write(t)}writeUtf8String(e){const t=$.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const i=je(t),n=1+(i?t.length:$.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(i?oe.ISO_8859_1:oe.UTF_8),i?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=je(e),i="",s=4+i.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?oe.ISO_8859_1:oe.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=je(e),i=t?e.length:$.encode(e).byteLength,s="",n=4+s.length+1+i+1;this.writeAscii("COMM"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?oe.ISO_8859_1:oe.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(s),this.writeIsoString(e)):(this.writeUtf8String(s),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,i,s){const n=je(e)&&je(i),a=n?i.length:$.encode(i).byteLength,o=1+e.length+1+1+a+1+s.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(n?oe.ISO_8859_1:oe.UTF_8),n?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),n?this.writeIsoString(i):this.writeUtf8String(i),this.writer.write(s)}}/*! 241 * Copyright (c) 2026-present, Vanilagy and contributors 242 * 243 * This Source Code Form is subject to the terms of the Mozilla Public 244 * License, v. 2.0. If a copy of the MPL was not distributed with this 245 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 246 */class ut{constructor(e){this.mutex=new Rt,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let s=this.trackTimestampInfo.get(e);if(s){if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),s.maxTimestampBeforeLastKeyPacket!==null&&t<s.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 ${s.maxTimestampBeforeLastKeyPacket}s.`);s.maxTimestamp=Math.max(s.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,s)}}}/*! 247 * Copyright (c) 2026-present, Vanilagy and contributors 248 * 249 * This Source Code Form is subject to the terms of the Mozilla Public 250 * License, v. 2.0. If a copy of the MPL was not distributed with this 251 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 252 */class xu extends ut{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),Si(this.output._metadataTags)||new Wr(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,i){const s=await this.mutex.acquire();
252try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){Tt(i);const n=i?.decoderConfig?.description;if(this.inputIsAdts=!n,!this.inputIsAdts){const a=rs(ie(n)),o=ya(a);this.header=o.header,this.headerBitstream=o.bitstream}}if(this.inputIsAdts){const n=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,n)}else{p(this.header);const n=t.data.byteLength+this.header.byteLength;Ta(this.headerBitstream,n);const a=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const o=new Uint8Array(n);o.set(this.header,0),o.set(t.data,this.header.byteLength),this.format._options.onFrame(o,a)}}await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){(await this.mutex.acquire())()}}/*! 253 * Copyright (c) 2026-present, Vanilagy and contributors 254 * 255 * This Source Code Form is subject to the terms of the Mozilla Public 256 * License, v. 2.0. If a copy of the MPL was not distributed with this 257 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 258 */const Ln=new Uint8Array([102,76,97,67]),_u=38,Cu=34;class Iu extends ut{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(Ln),e()}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:s,maximumFrameSize:n,sampleRate:a,channels:o,totalSamples:c}){p(this.writer.getPos()===4);const l=!Si(this.output._metadataTags),d=new K(new Uint8Array(4));d.writeBits(1,+!l),d.writeBits(7,st.STREAMINFO),d.writeBits(24,Cu),this.writer.write(d.bytes);const u=new K(new Uint8Array(18));if(u.writeBits(16,t),u.writeBits(16,i),u.writeBits(24,s),u.writeBits(24,n),u.writeBits(20,a),u.writeBits(3,o-1),u.writeBits(5,e-1),c>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");u.writeBits(4,0),u.writeBits(32,c),this.writer.write(u.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){const t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,i=new Uint8Array(t);let s=0;const n=q(i);n.setUint32(s,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),s+=4,n.setUint32(s,e.mimeType.length),s+=4,i.set($.encode(e.mimeType),8),s+=e.mimeType.length,n.setUint32(s,e.description?.length??0),s+=4,i.set($.encode(e.description??""),s),s+=e.description?.length??0,s+=16,n.setUint32(s,e.data.length),s+=4,i.set(e.data,s),s+=e.data.length,p(s===t);const a=new K(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,st.PICTURE),a.writeBits(24,t),this.writer.write(a.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(_u+Ln.byteLength),Si(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const s of e)this.writePictureBlock(s);const t=Js(new Uint8Array(0),this.output._metadataTags,!1),i=new K(new Uint8Array(4));i.writeBits(1,1),i.writeBits(7,st.VORBIS_COMMENT),i.writeBits(24,t.length),this.writer.write(i.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,i){const s=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null){Tt(i),p(i),p(i.decoderConfig),p(i.decoderConfig.description),this.sampleRate=i.decoderConfig.sampleRate,this.channels=i.decoderConfig.numberOfChannels;const u=new K(ie(i.decoderConfig.description));u.skipBits(167);const h=u.readBits(5)+1;this.bitsPerSample=h,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 n=fe.tempFromBytes(t.data);n.skip(2);const a=D(n,2),o=new K(a),c=co(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");lo(n);const l=uo(n,c);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(t.data.length));const d=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,d),await this.writer.flush()}finally{s()}}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,i=0,s=1/0,n=0,a=0;for(let o=0;o<this.blockSizes.length;o++)s=Math.min(s,this.frameSizes[o]),n=Math.max(n,this.frameSizes[o]),i=Math.max(i,this.blockSizes[o]),a+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));p(this.sampleRate!==null),p(this.channels!==null),p(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:s,maximumFrameSize:n,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}/*! 259 * Copyright (c) 2026-present, Vanilagy and contributors 260 * 261 * This Source Code Form is subject to the terms of the Mozilla Public 262 * License, v. 2.0. If a copy of the MPL was not distributed with this 263 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 264 */const li=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Eu=/^WEBVTT(.|\n)*?\n{2}/,ss=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class Au{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r 265`,` 266`).replaceAll("\r",` 267`),li.lastIndex=0;let t;if(!this.preambleText){if(!Eu.test(e))throw new Error("WebVTT preamble incorrect.");t=li.exec(e);const i=e.slice(0,t?.index??e.length).trimEnd();if(!i)throw new Error("No WebVTT preamble provided.");this.preambleText=i,t&&(e=e.slice(t.index),li.lastIndex=0)}for(;t=li.exec(e);){const i=e.slice(0,t.index),s=t[1],n=t.index+t[0].length,a=e.indexOf(` 268`,n)+1,o=e.slice(n,a).trim();let c=e.indexOf(` 269 270`,n);c===-1&&(c=e.length);const l=hr(t[2]),u=hr(t[3])-l,h=e.slice(a,c).trim();e=e.slice(c).trimStart(),li.lastIndex=0;const f={timestamp:l/1e3,duration:u/1e3,text:h,identifier:s,settings:o,notes:i},g={};this.preambleEmitted||(g.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,g)}}}const vu=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,hr=r=>{const e=vu.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])},Do=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),s=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};/*! 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 Oi{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 n of e.children)n&&this.writeBox(n);const i=this.writer.getPos(),s=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,s),this.writer.seek(i)}}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);p(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}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 i of e.children)i&&(t+=this.measureBox(i));return t}}}const V=new Uint8Array(8),Fe=new DataView(V.buffer),se=r=>[(r%256+256)%256],L=r=>(Fe.setUint16(0,r,!1),[V[0],V[1]]),Vr=r=>(Fe.setInt16(0,r,!1),[V[0],V[1]]),Uo=r=>(Fe.setUint32(0,r,!1),[V[1],V[2],V[3]]),A=r=>(Fe.setUint32(0,r,!1),[V[0],V[1],V[2],V[3]]),tt=r=>(Fe.setInt32(0,r,!1),[V[0],V[1],V[2],V[3]]),Ge=r=>(Fe.setUint32(0,Math.floor(r/2**32),!1),Fe.setUint32(4,r,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Fu=r=>(Fe.setInt32(0,Math.floor(r/2**32),!1),Fe.setUint32(4,r,!1),[V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7]]),Oo=r=>(Fe.setInt16(0,2**8*r,!1),[V[0],V[1]]),Re=r=>(Fe.setInt32(0,2**16*r,!1),[V[0],V[1],V[2],V[3]]),Ms=r=>(Fe.setInt32(0,2**30*r,!1),[V[0],V[1],V[2],V[3]]),zs=(r,e)=>{const t=[];let i=r;do{let s=i&127;i>>=7,t.length>0&&(s|=128),t.push(s)}while(i>0||e);return t.reverse()},Q=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,s)=>r.charCodeAt(s));return e&&t.push(0),t},No=r=>{const e=r*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Lo=No(0),Wo=r=>[Re(r[0]),Re(r[1]),Ms(r[2]),Re(r[3]),Re(r[4]),Ms(r[5]),Re(r[6]),Re(r[7]),Ms(r[8])],N=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),X=(r,e,t,i,s)=>N(r,[se(e),Uo(t),i??[]],s),Bu=r=>r.isQuickTime?N("ftyp",[Q("qt "),A(512),Q("qt ")]):r.fragmented?r.cmaf?N("ftyp",[Q("iso5"),A(512),Q("iso5"),Q("iso6"),Q("mp41"),Q("cmfc"),Q("dash")]):N("ftyp",[Q("iso5"),A(512),Q("iso5"),Q("iso6"),Q("mp41")]):N("ftyp",[Q("isom"),A(512),Q("isom"),r.holdsAvc?Q("avc1"):[],Q("mp41")]),Wn=()=>N("styp",[Q("iso5"),A(0),Q("iso5"),Q("iso6"),Q("mp41"),Q("cmfc"),Q("dash")]),Vn=(r,e)=>{let t=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(t)||(t=0),X("sidx",1,0,[A(1),A(De),Ge(Z(r.minWrittenTimestamp,De)),Ge(0),L(0),L(1),A(e&2147483647),A(Z(t,De)),A(0)])},Ni=r=>({type:"mdat",largeSize:r}),Ru=r=>({type:"free",size:r}),ui=r=>N("moov",void 0,[Mu(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>zu(e,r.creationTime)),r.isFragmented?Td(r.trackDatas):null,Rd(r)]),Mu=(r,e)=>{const t=Math.max(0,...e.map(a=>Z(bs(a),De)+Z(a.startTimestampOffset??0,De))),i=Math.max(0,...e.map(a=>a.track.id))+1,s=!wt(r)||!wt(t),n=s?Ge:A;return X("mvhd",+s,0,[n(r),n(r),A(De),n(t),Re(1),Oo(1),Array(10).fill(0),Wo(Lo),Array(24).fill(0),A(i)])},bs=r=>
276{if(r.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<r.samples.length;i++){const s=r.samples[i];s.timestamp<e&&(e=s.timestamp),s.timestamp+s.duration>t&&(t=s.timestamp+s.duration)}return e===1/0?0:t-e},zu=(r,e)=>{const t=Gd(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return N("trak",void 0,[Du(r,e),i?Uu(r,r.startTimestampOffset):null,Ou(r,e),t.name!==void 0?N("udta",void 0,[N("name",[...$.encode(t.name)])]):null])},Du=(r,e)=>{const t=Z(bs(r),De)+Z(r.startTimestampOffset??0,De),i=!wt(e)||!wt(t),s=i?Ge:A;let n;if(r.type==="video"){const o=r.track.metadata.rotation;n=No(o??0)}else n=Lo;let a=2;return r.track.metadata.disposition?.default!==!1&&(a|=1),X("tkhd",+i,a,[s(e),s(e),A(r.track.id),A(0),s(t),Array(8).fill(0),L(0),L(r.track.id),Oo(r.type==="audio"?1:0),L(0),Wo(n),Re(r.type==="video"?r.info.width:0),Re(r.type==="video"?r.info.height:0)])},Uu=(r,e)=>{const t=Z(e,De),i=Z(bs(r),De),s=!wt(t)||!wt(i),n=s?Ge:A,a=s?Fu:tt;return N("edts",void 0,[X("elst",s?1:0,0,[A(2),n(t),a(-1),Re(1),n(i),a(0),Re(1)])])},Ou=(r,e)=>N("mdia",void 0,[Nu(r,e),Hr(!0,Lu[r.type],Wu[r.type]),Vu(r)]),Nu=(r,e)=>{const t=Z(bs(r),r.timescale),i=!wt(e)||!wt(t),s=i?Ge:A;return X("mdhd",+i,0,[s(e),s(e),A(r.timescale),s(t),L(Ko(r.track.metadata.languageCode??le)),L(0)])},Lu={video:"vide",audio:"soun",subtitle:"text"},Wu={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Hr=(r,e,t,i="\0\0\0\0")=>X("hdlr",0,0,[r?Q("mhlr"):A(0),Q(e),Q(i),A(0),A(0),Q(t,!0)]),Vu=r=>N("minf",void 0,[Gu[r.type](),Xu(),$u(r)]),Hu=()=>X("vmhd",0,1,[L(0),L(0),L(0),L(0)]),qu=()=>X("smhd",0,0,[L(0),L(0)]),Ku=()=>X("nmhd",0,0),Gu={video:Hu,audio:qu,subtitle:Ku},Xu=()=>N("dinf",void 0,[ju()]),ju=()=>X("dref",0,0,[A(1)],[Qu()]),Qu=()=>X("url ",0,1),$u=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return N("stbl",void 0,[Yu(r),fd(r),e?wd(r):null,e?yd(r):null,pd(r),gd(r),kd(r),md(r)])},Yu=r=>{let e;if(r.type==="video")e=Zu(Ud(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=qo(r.track.source._codec,r.muxer.isQuickTime);p(t),e=rd(t,r)}else r.type==="subtitle"&&(e=dd(Ld[r.track.source._codec],r));return p(e),X("stsd",0,0,[A(1)],[e])},Zu=(r,e)=>N(r,[Array(6).fill(0),L(1),L(0),L(0),Array(12).fill(0),L(e.info.width),L(e.info.height),A(4718592),A(4718592),A(0),L(1),Array(32).fill(0),L(24),Vr(65535)],[Od[e.track.source._codec](e),Ju(e),ba(e.info.decoderConfig.colorSpace)?ed(e):null]),Ju=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:N("pasp",[A(r.info.pixelAspectRatio.num),A(r.info.pixelAspectRatio.den)]),ed=r=>N("colr",[Q(r.muxer.isQuickTime?"nclc":"nclx"),L(yr[r.info.decoderConfig.colorSpace.primaries]),L(Tr[r.info.decoderConfig.colorSpace.transfer]),L(br[r.info.decoderConfig.colorSpace.matrix]),r.muxer.isQuickTime?[]:se((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),td=r=>r.info.decoderConfig&&N("avcC",[...ie(r.info.decoderConfig.description)]),id=r=>r.info.decoderConfig&&N("hvcC",[...ie(r.info.decoderConfig.description)]),Hn=r=>{if(!r.info.decoderConfig)return null;const e=r.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),s=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),c=(n<<4)+(a<<1)+o,l=t[5]?Number(t[5]):e.colorSpace?.primaries?yr[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?Tr[e.colorSpace.transfer]:2,u=t[7]?Number(t[7]):e.colorSpace?.matrix?br[e.colorSpace.matrix]:2;return X("vpcC",1,0,[se(i),se(s),se(c),se(l),se(d),se(u),L(0)])},sd=r=>N("av1C",Sa(r.info.decoderConfig.codec)),rd=(r,e)=>{let t=0,i,s=16;const n=ot.includes(e.track.source._codec);if(n){const a=e.track.source._codec,{sampleSize:o}=Ue(a);s=8*o,s>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),L(1),L(t),L(0),A(0),L(e.info.numberOfChannels),L(s),L(0),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0)];else{const a=n?0:-2;i=[Array(6).fill(0),L(1),L(t),L(0),A(0),L(e.info.numberOfChannels),L(Math.min(s,16)),Vr(a),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0),n?[A(1),A(s/8),A(e.info.numberOfChannels*s/8)]:[A(0),A(0),A(0)],A(2)]}return N(r,i,[Nd(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},Ds=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=[...se(e),...se(21),...Uo(0),...A(0),...A(0)];if(r.info.decoderConfig.description){const i=ie(r.info.decoderConfig.description);t=[...t,...se(5),...zs(i.byteLength),...i]}return t=[...L(1),...se(0),...se(4),...zs(t.length),...t,...se(6),...se(1),...se(2)],t=[...se(3),...zs(t.length),...t],X("esds",0,0,t)},dt=r=>N("wave",void 0,[nd(r),ad(r),N("\0\0\0\0")]),nd=r=>N("frma",[Q(qo(r.track.source._codec,r.muxer.isQuickTime))]),ad=r=>{const{littleEndian:e}=Ue(r.track.source._codec);return N("enda",[L(+e)])},od=r=>{let e=r.info.numberOfChannels,t=3840,i=r.info.sampleRate,s=0,n=0,a=new Uint8Array(0);const o=r.info.decoderConfig?.description;if(o){p(o.byteLength>=18);const c=ie(o),l=ms(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return N("dOps",[se(0),se(e),L(t),A(i),Vr(s),se(n),...a])},cd=r=>{const e=r.info.decoderConfig?.description;p(e);const t=ie(e);return X("dfLa",0,0,[...t.subarray(4)])},He=r=>{const{littleEndian:e,sampleSize:t}=Ue(r.track.source._codec),i=+e;return X("pcmC",0,0,[se(i),se(8*t)])},ld=r=>{const e=Da(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),i=new K(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.b
276smod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),N("dac3",[...t])},ud=r=>{const e=Oa(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 i=Math.ceil(t/8),s=new Uint8Array(i),n=new K(s);n.writeBits(13,e.dataRate),n.writeBits(3,e.substreams.length-1);for(const a of e.substreams)n.writeBits(2,a.fscod),n.writeBits(5,a.bsid),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(3,a.bsmod),n.writeBits(3,a.acmod),n.writeBits(1,a.lfeon),n.writeBits(3,0),n.writeBits(4,a.numDepSub),a.numDepSub>0?n.writeBits(9,a.chanLoc):n.writeBits(1,0);return N("dec3",[...s])},dd=(r,e)=>N(r,[Array(6).fill(0),L(1)],[Wd[e.track.source._codec](e)]),hd=r=>N("vttC",[...$.encode(r.info.config.description)]),fd=r=>X("stts",0,0,[A(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[A(e.sampleCount),A(e.sampleDelta)])]),md=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return X("stss",0,0,[A(e.length),e.map(([t])=>A(t+1))])},pd=r=>X("stsc",0,0,[A(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[A(e.firstChunk),A(e.samplesPerChunk),A(1)])]),gd=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=Ue(r.track.source._codec);return X("stsz",0,0,[A(e*r.info.numberOfChannels),A(r.samples.reduce((t,i)=>t+Z(i.duration,r.timescale),0))])}return X("stsz",0,0,[A(0),A(r.samples.length),r.samples.map(e=>A(e.size))])},kd=r=>r.finalizedChunks.length>0&&ce(r.finalizedChunks).offset>=2**32?X("co64",0,0,[A(r.finalizedChunks.length),r.finalizedChunks.map(e=>Ge(e.offset))]):X("stco",0,0,[A(r.finalizedChunks.length),r.finalizedChunks.map(e=>A(e.offset))]),wd=r=>X("ctts",1,0,[A(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[A(e.sampleCount),tt(e.sampleCompositionTimeOffset)])]),yd=r=>{let e=1/0,t=-1/0,i=1/0,s=-1/0;p(r.compositionTimeOffsetTable.length>0),p(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];i=Math.min(i,Z(o.timestamp,r.timescale)),s=Math.max(s,Z(o.timestamp+o.duration,r.timescale))}const n=Math.max(-e,0);return s>=2**31?null:X("cslg",0,0,[tt(n),tt(e),tt(t),tt(i),tt(s)])},Td=r=>N("mvex",void 0,r.map(bd)),bd=r=>X("trex",0,0,[A(r.track.id),A(1),A(0),A(0),A(0)]),qn=(r,e)=>N("moof",void 0,[Sd(r),...e.map(Pd)]),Sd=r=>X("mfhd",0,0,[A(r)]),Vo=r=>{let e=0,t=0;const i=0,s=0,n=r.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|i<<8|s},Pd=r=>N("traf",void 0,[xd(r),_d(r),Cd(r)]),xd=r=>{p(r.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Vo(t)};return X("tfhd",0,e,[A(r.track.id),A(i.duration),A(i.size),A(i.flags)])},_d=r=>(p(r.currentChunk),X("tfdt",1,0,[Ge(Z(r.currentChunk.startTimestamp,r.timescale))])),Cd=r=>{p(r.currentChunk);const e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),i=r.currentChunk.samples.map(Vo),s=r.currentChunk.samples.map(m=>Z(m.timestamp-m.decodeTimestamp,r.timescale)),n=new Set(e),a=new Set(t),o=new Set(i),c=new Set(s),l=o.size===2&&i[0]!==i[1],d=n.size>1,u=a.size>1,h=!l&&o.size>1,f=c.size>1||[...c].some(m=>m!==0);let g=0;return g|=1,g|=4*+l,g|=256*+d,g|=512*+u,g|=1024*+h,g|=2048*+f,X("trun",1,g,[A(r.currentChunk.samples.length),A(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?A(i[0]):[],r.currentChunk.samples.map((m,w)=>[d?A(e[w]):[],u?A(t[w]):[],h?A(i[w]):[],f?tt(s[w]):[]])])},Id=r=>N("mfra",void 0,[...r.map(Ed),Ad()]),Ed=(r,e)=>X("tfra",1,0,[A(r.track.id),A(63),A(r.finalizedChunks.length),r.finalizedChunks.map(i=>
276[Ge(Z(i.samples[0].timestamp,r.timescale)),Ge(i.moofOffset),A(e+1),A(1),A(1)])]),Ad=()=>X("mfro",0,0,[A(0)]),vd=()=>N("vtte"),Fd=(r,e,t,i,s)=>N("vttc",void 0,[s!==null?N("vsid",[tt(s)]):null,t!==null?N("iden",[...$.encode(t)]):null,e!==null?N("ctim",[...$.encode(Do(e))]):null,i!==null?N("sttg",[...$.encode(i)]):null,N("payl",[...$.encode(r)])]),Bd=r=>N("vtta",[...$.encode(r)]),Rd=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const s=zd(i);s&&e.push(s)}else if(t==="mdta"){const s=Dd(i);s&&e.push(s)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&Md(e,r.output._metadataTags);return e.length===0?null:N("udta",void 0,e)},Md=(r,e)=>{for(const{key:t,value:i}of ei(e))switch(t){case"title":r.push(qe("©nam",i));break;case"description":r.push(qe("©des",i));break;case"artist":r.push(qe("©ART",i));break;case"album":r.push(qe("©alb",i));break;case"albumArtist":r.push(qe("albr",i));break;case"genre":r.push(qe("©gen",i));break;case"date":r.push(qe("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(qe("©cmt",i));break;case"lyrics":r.push(qe("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ge(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||r.some(s=>s.type===t)||(typeof i=="string"?r.push(qe(t,i)):i instanceof Uint8Array&&r.push(N(t,Array.from(i))))}},qe=(r,e)=>{const t=$.encode(e);return N(r,[L(t.length),L(Ko("und")),Array.from(t)])},Kn={"image/jpeg":13,"image/png":14,"image/bmp":27},Ho=(r,e)=>{const t=[];for(const{key:i,value:s}of ei(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:Be(s)});break;case"description":t.push({key:e?"description":"©des",value:Be(s)});break;case"artist":t.push({key:e?"artist":"©ART",value:Be(s)});break;case"album":t.push({key:e?"album":"©alb",value:Be(s)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Be(s)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Be(s)});break;case"genre":t.push({key:e?"genre":"©gen",value:Be(s)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Be(s)});break;case"date":t.push({key:e?"date":"©day",value:Be(s.toISOString().slice(0,10))});break;case"images":for(const n of s)n.kind==="coverFront"&&t.push({key:"covr",value:N("data",[A(Kn[n.mimeType]??0),A(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=r.tracksTotal!==void 0?`${s}/${r.tracksTotal}`:s.toString();t.push({key:"track",value:Be(n)})}else t.push({key:"trkn",value:N("data",[A(0),A(0),L(0),L(s),L(r.tracksTotal??0),L(0)])});break;case"discNumber":e||t.push({key:"disc",value:N("data",[A(0),A(0),L(0),L(s),L(r.discsTotal??0),L(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ge(i)}if(r.raw)for(const i in r.raw){const s=r.raw[i];s==null||!e&&i.length!==4||t.some(n=>n.key===i)||(typeof s=="string"?t.push({key:i,value:Be(s)}):s instanceof Uint8Array?t.push({key:i,value:N("data",[A(0),A(0),Array.from(s)])}):s instanceof Qt&&t.push({key:i,value:N("data",[A(Kn[s.mimeType]??0),A(0),Array.from(s.data)])}))}return t},zd=r=>{const e=Ho(r,!1);return e.length===0?null:X("meta",0,0,void 0,[Hr(!1,"mdir","","appl"),N("ilst",void 0,e.map(t=>N(t.key,void 0,[t.value])))])},Dd=r=>{const e=Ho(r,!0);return e.length===0?null:N("meta",void 0,[Hr(!1,"mdta",""),X("keys",0,0,[A(e.length)],e.map(t=>N("mdta",[...$.encode(t.key)]))),N("ilst",void 0,e.map((t,i)=>{const s=String.fromCharCode(...A(i+1));return N(s,void 0,[t.value])}))])},Be=r=>N("data",[A(1),A(0),...$.encode(r)]),Ud=(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"}},Od={avc:td,hevc:id,vp8:Hn,vp9:Hn,av1:sd},qo=(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"}},Nd=(r,e)=>{switch(r){case"aac":return Ds;case"mp3":return Ds;case"opus":return od;case"vorbis":return Ds;case"flac":return cd;case"ac3":return ld;case"eac3":return ud}if(e)switch(r){case"pcm-s24":return dt;case"pcm-s24be":return dt;case"pcm-s32":return dt;case"pcm-s32be":return dt;case"pcm-f32":return dt;case"pcm-f32be":return dt;case"pcm-f64":return dt;case"pcm-f64be":return dt}else switch(r){case"pcm-s16":return He;case"pcm-s16be":return He;case"pcm-s24":return He;case"pcm-s24be":return He;case"pcm-s32":return He;case"pcm-s32be":return He;case"pcm-f32":return He;case"pcm-f32be":return He;case"pcm-f64":return He;case"pcm-f64be":return He}return null},Ld={webvtt:"wvtt"},Wd={webvtt:hd},Ko=r=>{p(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};/*! 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 */class Ii{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(){p(!this.started),this.target._start(),this.started=!0}write(e){p(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 p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(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 i=t+e.byteLength-this.trackedStart;let s=this.trackedWrites.byteLength;for(;s<i;)s*=2;if(s!==this.trackedWrites.byteLength){const n=new Uint8Array(s);
282n.set(this.trackedWrites,0),this.trackedWrites=n}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}}/*! 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 */const Gn=typeof Zi<"u"?Zi:void 0;class Se extends os{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(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 qd(this,e)}}const Us=2**16,Os=2**32;class Ns extends Se{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(Us,{maxByteLength:Os})}catch{this._buffer=new ArrayBuffer(Us),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Us);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>Os)throw new Error(`ArrayBuffer exceeded maximum size of ${Os} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),s=new Uint8Array(i);s.set(this._bytes,0),this._buffer=i,this._bytes=s}}}_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 Vd=2**24,Hd=2;class Go extends Se{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??Vd}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){const i=t-this._lastWriteEnd;this._write(new Uint8Array(i),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(p(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((i,s)=>i.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){const s=e[e.length-1],n=t[i];n.start<=s.start+s.size?s.size=Math.max(s.size,n.start+n.data.byteLength-s.start):e.push({start:n.start,size:n.data.byteLength})}for(const i of e){i.data=new Uint8Array(i.size);for(const s of this._sections)i.start<=s.start&&s.start<i.start+i.size&&i.data.set(s.data,s.start-i.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(i.data,i.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&i.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data,position:i.start}).catch(s=>{this._writeError??=s}),this._lastFlushEnd=i.start+i.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let i=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);i===-1&&(i=this._createChunk(t));const s=this._chunks[i],n=t-s.start,a=e.subarray(0,Math.min(this._chunkSize-n,e.byteLength));s.data.set(a,n);const o={start:n,end:n+a.byteLength};if(this._insertSectionIntoChunk(s,o),s.written[0].start===0&&s.written[0].end===this._chunkSize&&(s.shouldFlush=!0),this._chunks.length>Hd){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 i=0,s=e.written.length-1,n=-1;for(;i<=s;){const a=Math.floor(i+(s-i+1)/2);e.written[a].start<=t.start?(i=a+1,n=a):s=a-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}_createChunk(e){const i={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(i),this._chunks.sort((s,n)=>s.start-n.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){p(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const i=this._chunks[t];if(!(!i.shouldFlush&&!e)){for(const s of i.written){const n=i.start+s.start;if(this._monotonicity===!0&&n!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data.subarray(s.start,s.end),position:n}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=i.start+s.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;p(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}}class zh extends Se{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new Go(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>
288{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 p(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,p(this._writer),this._writer.write(t.data)},close:()=>this._writer?.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 Dh extends Se{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(!Gn.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;const i=new WritableStream({start:async()=>{this._fileHandle=await Gn.fs.open(e,"w")},write:async s=>{p(this._fileHandle),await this._fileHandle.write(s.data,0,s.data.byteLength,s.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new Go(i,{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 Xo extends Se{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class qd extends Se{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 pt{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.")}}/*! 289 * Copyright (c) 2026-present, Vanilagy and contributors 290 * 291 * This Source Code Form is subject to the terms of the Mozilla Public 292 * License, v. 2.0. If a copy of the MPL was not distributed with this 293 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 294 */const De=57600,Kd=2082844800,Gd=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},Z=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i};class Xd extends ut{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Ns,this.auxWriter=new Ii(this.auxTarget,!1),this.auxBoxWriter=new Oi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=J(),this.creationTime=Math.floor(Date.now()/1e3)+Kd,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 ic,this.isCmaf=t instanceof ra,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof ra?1/0:1)}async start(){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 Ns),this.boxWriter=new Oi(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Ns?"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 Ii(i,!0);
294s.start(),this.initWriter=s,this.initBoxWriter=new Oi(s)}const t=this.output._tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(p(i),this.format._options.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Bu({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:s,start:n}=i.writer.stopTrackingWrites();this.format._options.onFtyp(s,n)}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||(p(this.writer),p(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ni(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.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 Wa({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const s=this.trackDatas.find(h=>h.track===e);if(s)return s;cs(i),p(i),p(i.decoderConfig);const n={...i.decoderConfig};p(n.codedWidth!==void 0),p(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){const h=Ar(t.data);if(!h)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.");n.description=Uc(h),a=!0}else if(e.source._codec==="hevc"&&!n.description){const h=Fr(t.data);if(!h)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.");n.description=Kc(h),a=!0}const o=wc(1/(e.metadata.frameRate??De),1e6).den,c=n.displayAspectWidth,l=n.displayAspectHeight,d=c===void 0||l===void 0?{num:1,den:1}:Yi({num:c*n.codedHeight,den:l*n.codedWidth}),u={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:d,decoderConfig:n,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(u),this.trackDatas.sort((h,f)=>h.track.id-f.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,i){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;Tt(i),p(i),p(i.decoderConfig);const n={...i.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){const c=nt(fe.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=Ai[c.samplingFrequencyIndex],d=as[c.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");n.description=Sr({objectType:c.objectType,sampleRate:l,numberOfChannels:d}),a=!0}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&ot.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1}
294;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 i=this.trackDatas.find(n=>n.track===e);if(i)return i;Pa(t),p(t),p(t.config);const s={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(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i);let a=t.data;if(n.info.requiresAnnexBTransformation){const c=[...si(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=Er(c,4)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(n,a,t.timestamp,t.duration,t.type);await this.registerSample(n,o)}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,i);let a=t.data;if(n.info.requiresAdtsStripping){const d=nt(fe.tempFromBytes(a));if(!d)throw new Error("Expected ADTS frame, didn't get one.");const u=d.crcCheck===null?_i:kt;a=a.subarray(u)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(n.info.requiresPcmTransformation){const u=Ue(n.info.decoderConfig.codec).sampleSize*n.info.numberOfChannels;if(c=a.byteLength/u/n.info.sampleRate,n.info.expectedNextPcmPacketTimestamp!==null){const h=o-n.info.expectedNextPcmPacketTimestamp;if(h<.01)o=n.info.expectedNextPcmPacketTimestamp;else{const f=await this.padWithSilence(n,n.info.expectedNextPcmPacketTimestamp,h);o=n.info.expectedNextPcmPacketTimestamp+f}}n.info.expectedNextPcmPacketTimestamp=o+c}const l=this.createSampleForTrack(n,a,o,c,t.type);await this.registerSample(n,l)}finally{s()}}async padWithSilence(e,t,i){const s=Z(i,e.timescale);if(i=s/e.timescale,s>0){const{sampleSize:n,silentValue:a}=Ue(e.info.decoderConfig.codec),o=s*e.info.numberOfChannels,c=new Uint8Array(n*o).fill(a),l=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,i,"key");await this.registerSample(e,l)}return i}async addSubtitleCue(e,t,i){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(t),await this.processWebVTTCues(n,t.timestamp))}finally{s()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const l of e.cueQueue)p(l.timestamp<=t),p(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);const s=[...i].sort((l,d)=>l-d),n=s[0],a=s[1]??n;if(t<a)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const l=vd();this.auxBoxWriter.writeBox(l);const d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){const d=e.cueQueue[l];if(d.timestamp>=a)break;ss.lastIndex=0;const u=ss.test(d.text),h=d.timestamp+d.duration;let f=e.cueToSourceId.get(d);if(f===void 0&&a<h&&(f=e.nextSourceId++,e.cueToSourceId.set(d,f)),d.notes){const m=Bd(d.notes);this.auxBoxWriter.writeBox(m)}const g=Fd(d.text,u?n:null,d.identifier??null,d.settings??null,f??null);this.auxBoxWriter.writeBox(g),h===a&&e.cueQueue.splice(l--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,n,a-n,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,s,n){return{timestamp:i,decodeTimestamp:i,duration:s,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:Z(s,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let s=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const a=e.timestampProcessingQueue[n],o=Z(a.duration,e.timescale);s+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleC
294ount:s,sampleDelta:1});else{const n=ce(e.timeToSampleTable);n.sampleCount+=s}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,n)=>s-n);this.isFragmented||(e.startTimestampOffset??=i[0]);for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];n.decodeTimestamp=i[s];const a=Z(n.timestamp-n.decodeTimestamp,e.timescale),o=Z(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const c=Z(n.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(p(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=ce(e.timeToSampleTable);if(p(d),d.sampleCount===1){d.sampleDelta=l;const h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===l&&(h.sampleCount++,e.timeToSampleTable.pop(),d=h)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===o?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const u=ce(e.compositionTimeOffsetTable);
294p(u),u.sampleCompositionTimeOffset===a?u.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=Z(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(t.type==="key");const s=Z(t.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}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 s=e.track.metadata.maximumPacketCount;if(p(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const s=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.closed});s>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=s>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),p(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(p(!this.isFragmented),p(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((i,s)=>i+Z(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ce(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 i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(t=n,i=n.sampleQueue[0].timestamp)}if(!t)break;const s=t.sampleQueue.shift();await this.addSampleToTrack(t,s)}}async finalizeFragment(e=!this.isCmaf){p(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){const f=this.initBoxWriter??this.boxWriter;p(f),this.format._options.onMoov&&f.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const g=ui(this);if(f.writeBox(g),this.format._options.onMoov){const{data:m,start:w}=f.writer.stopTrackingWrites();this.format._options.onMoov(m,w)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Oi(this.writer);const m=this.boxWriter.measureBox(Wn()),w=this.boxWriter.measureBox(Vn(this,0));this.segmentHeaderSize=m+w,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(this.boxWriter);const i=this.trackDatas.filter(f=>f.currentChunk),s=qn(t,i),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s);let o=a+Je,c=1/0;for(const f of i){f.currentChunk.offset=o,f.currentChunk.moofOff
294set=n;for(const g of f.currentChunk.samples)o+=g.size;c=Math.min(c,f.currentChunk.startTimestamp)}const l=o-a,d=l>=2**32;if(d)for(const f of i)f.currentChunk.offset+=Ct-Je;this.format._options.onMoof&&this.writer.startTrackingWrites();const u=qn(t,i);if(this.boxWriter.writeBox(u),this.format._options.onMoof){const{data:f,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(f,g,c)}p(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=Ni(d);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(a+(d?Ct:Je));for(const f of i)for(const g of f.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){const{data:f,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(f,g)}for(const f of i)f.finalizedChunks.push(f.currentChunk),this.finalizedChunks.push(f.currentChunk),f.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(p(this.writer),p(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();const i=ui(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ni(!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(){p(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(s=>s.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(s=>s.type===e);if(t.length===0)continue;if(!t.some(s=>s.track.metadata.disposition?.default!==!1)){const s=t[0];s.track.metadata.disposition={...s.track.metadata.disposition,default:!0}}}}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();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),p(t.startTimestampOffset!==null);for(let i=0;i<t.samples.length;i++){const s=t.samples[i];s.timestamp-=t.startTimestampOffset,s.decodeTimestamp-=t.startTimestampOffset}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Ni(!1);let t;for(let s=0;s<2;s++){const n=ui(this),a=this.boxWriter.measureBox(n);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)p(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 i=ui(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const s of this.finalizedChunks)for(const n of s.samples)p(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,n)}}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(Wn()),this.boxWriter.writeBox(Vn(this,t))}else{const t=this.writer.getPos(),i=Id(this.trackDatas);this.boxWriter.writeBox(i);const s=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{p(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);p(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,a)}const s=ui(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Ru(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,a)}}e()}}/*! 295 * Copyright (c) 2026-present, Vanilagy and contributors 296 * 297 * This Source Code Form is subject to the terms of the Mozilla Public 298 * License, v. 2.0. If a copy of the MPL was not distributed with this 299 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 300 */const jd=-32768,Qd=2**15-1,Xn="Mediabunny",jn=6,Qn=5,$d={video:1,audio:2,subtitle:17};class Yd extends ut{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=J(),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
300xMsTimestamp=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 ul(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:S.EBML,data:[{id:S.EBMLVersion,data:1},{id:S.EBMLReadVersion,data:1},{id:S.EBMLMaxIDLength,data:4},{id:S.EBMLMaxSizeLength,data:8},{id:S.DocType,data:this.format instanceof aa?"webm":"matroska"},{id:S.DocTypeVersion,data:2},{id:S.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:S.SeekHead,data:[{id:S.Seek,data:[{id:S.SeekID,data:t},{id:S.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:S.Seek,data:[{id:S.SeekID,data:i},{id:S.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:S.Seek,data:[{id:S.SeekID,data:s},{id:S.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:S.Seek,data:[{id:S.SeekID,data:n},{id:S.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:S.Seek,data:[{id:S.SeekID,data:a},{id:S.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:S.Duration,data:new ir(0)};this.segmentDuration=e;const t={id:S.Info,data:[{id:S.TimestampScale,data:1e6},{id:S.MuxingApp,data:Xn},{id:S.WritingApp,data:Xn},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:S.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){const i=ye[t.track.source._codec];p(i);let s=0;if(t.type==="audio"&&t.track.source._codec==="opus"){s=1e6*80;const n=t.info.decoderConfig.description;if(n){const a=ie(n),o=ms(a);s=Math.round(1e9*(o.preSkip/ti))}}e.data.push({id:S.TrackEntry,data:[{id:S.TrackNumber,data:t.track.id},{id:S.TrackUID,data:t.track.id},{id:S.TrackType,data:$d[t.type]},t.track.metadata.disposition?.default===!1?{id:S.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:S.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:S.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:S.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:S.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:S.FlagCommentary,data:1}:null,{id:S.FlagLacing,data:0},{id:S.Language,data:t.track.metadata.languageCode??le},{id:S.CodecID,data:i},{id:S.CodecDelay,data:0},{id:S.SeekPreRoll,data:s},t.track.metadata.name!==void 0?{id:S.Name,data:new ht(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,s=[e.info.decoderConfig.description?{id:S.CodecPr
300ivate,data:ie(e.info.decoderConfig.description)}:null,t?{id:S.DefaultDuration,data:1e9/t}:null],n=i?yi(-i):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:S.Video,data:[{id:S.PixelWidth,data:e.info.width},{id:S.PixelHeight,data:e.info.height},a?{id:S.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:S.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:S.DisplayUnit,data:3}:null,e.info.alphaMode?{id:S.AlphaMode,data:1}:null,ba(o)?{id:S.Colour,data:[{id:S.MatrixCoefficients,data:br[o.matrix]},{id:S.TransferCharacteristics,data:Tr[o.transfer]},{id:S.Primaries,data:yr[o.primaries]},{id:S.Range,data:o.fullRange?2:1}]}:null,n?{id:S.Projection,data:[{id:S.ProjectionType,data:0},{id:S.ProjectionPoseRoll,data:new tr((n+180)%360-180)}]}:null]};return s.push(c),s}audioSpecificTrackInfo(e){const t=ot.includes(e.track.source._codec)?Ue(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:S.CodecPrivate,data:ie(e.info.decoderConfig.description)}:null,{id:S.Audio,data:[{id:S.SamplingFrequency,data:new tr(e.info.sampleRate)},{id:S.Channels,data:e.info.numberOfChannels},t?{id:S.BitDepth,data:8*t.sampleSize}:null]}]}
300subtitleSpecificTrackInfo(e){return[{id:S.CodecPrivate,data:$.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(n,a)=>{e.push({id:S.SimpleTag,data:[{id:S.TagName,data:new ht(n)},typeof a=="string"?{id:S.TagString,data:new ht(a)}:{id:S.TagBinary,data:a}]})},i=this.output._metadataTags,s=new Set;for(const{key:n,value:a}of ei(i))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{const o=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{const o=i.discsTotal!==void 0?`${a}/${i.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ge(n)}if(i.raw)for(const n in i.raw){const a=i.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:S.Tags,data:[{id:S.Tag,data:[{id:S.Targets,data:[{id:S.TargetTypeValue,data:50},{id:S.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,s=e.images??[];for(const n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(yc(n.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&&!i.has(o))break}i.add(o),t.push({id:S.AttachedFile,data:[n.description!==void 0?{id:S.FileDescription,data:new ht(n.description)}:null,{id:S.FileName,data:new ht(a)},{id:S.FileMediaType,data:n.mimeType},{id:S.FileData,data:n.data},{id:S.FileUID,data:o}]})}for(const[n,a]of Object.entries(e.raw??{}))!(a instanceof _r)||!/^\d+$/.test(n)||s.find(c=>
300c.mimeType===a.mimeType&&ua(c.data,a.data))||t.push({id:S.AttachedFile,data:[a.description!==void 0?{id:S.FileDescription,data:new ht(a.description)}:null,{id:S.FileName,data:new ht(a.name??"")},{id:S.FileMediaType,data:a.mimeType??""},{id:S.FileData,data:a.data},{id:S.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:S.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:S.Segment,size:this.format._options.appendOnly?-1:jn,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:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:S.Cues,data:[]}}get segmentDataOffset(){return p(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 eo({isWebM:this.format instanceof aa,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const s=this.trackDatas.find(l=>l.track===e);if(s)return s;cs(i),p(i),p(i.decoderConfig),p(i.decoderConfig.codedWidth!==void 0),p(i.decoderConfig.codedHeight!==void 0);const n=i.decoderConfig.displayAspectWidth,a=i.decoderConfig.displayAspectHeight,o=n===void 0||a===void 0?null:Yi({num:n,den:a}),c={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec==="vp9"?c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(Tc(c.info.decoderConfig.codec))}:e.source._codec==="av1"&&(c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(Sa(c.info.decoderConfig.codec))}),this.trackDatas.push(c),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,i){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;Tt(i),p(i),p(i.decoderConfig);const n={...i.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){const c=nt(fe.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=Ai[c.samplingFrequencyIndex],d=as[c.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");n.description=Sr({objectType:c.objectType,sampleRate:l,numberOfChannels:d}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,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 i=this.trackDatas.find(n=>n.track===e);if(i)return i;Pa(t),p(t),p(t.config);const s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i),a=t.type==="key";this.validateTimestamp(n.track,t.timestamp,a);let o=t.timestamp,c=t.duration;e.metadata.frameRate!==void 0&&(o=Zt(o,e.metadata.frameRate),c=Zt(c,e.metadata.frameRate));const l=n.info.alphaMode?t.sideData.alpha??null:null,d=this.createInternalChunk(t.data,o,c,t.type,l);
300e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,d),n.chunkQueue.push(d),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,i);let a=t.data;if(n.info.requiresAdtsStripping){const l=nt(fe.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const d=l.crcCheck===null?_i:kt;a=a.subarray(d)}const o=t.type==="key";this.validateTimestamp(n.track,t.timestamp,o);const c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,i){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,!0);let a=t.text;const o=Math.round(t.timestamp*1e3);ss.lastIndex=0,a=a.replace(ss,u=>{const f=hr(u.slice(1,-1))-o;return`<${Do(f)}>`});const c=$.encode(a),l=`${t.settings??""} 301${t.identifier??""} 302${t.notes??""}`,d=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?$.encode(l):null);n.chunkQueue.push(d),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!n.closed)break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(t=n,i=n.chunkQueue[0].timestamp)}if(!t)break;const s=t.chunkQueue.shift();this.writeBlock(t,s)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const i=new K(t.data);i.skipBits(2);const s=i.readBits(1),a=(i.readBits(1)<<1)+s;if(a===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;a>=2&&i.skipBits(1);const d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];bc(t.data,i.pos,i.pos+3,d)}createInternalChunk(e,t,i,s,n=null){return{data:e,type:s,timestamp:t,duration:i,additions:n}}writeBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),s=this.trackDatas.every(d=>{if(e===d)return t.type==="key";const u=d.chunkQueue[0];return u?u.type==="key":d.closed});let n=!1;if(!this.currentCluster)n=!0;else{p(this.currentClusterStartMsTimestamp!==null),p(this.currentClusterMaxMsTimestamp!==null);const d=i-this.currentClusterStartMsTimestamp;n=s&&i>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>Qd}n&&this.createNewCluster(i);const a=i-this.currentClusterStartMsTimestamp;if(a<jd)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 d={id:S.BlockGroup,data:[{id:S.Block,data:[o,t.data]},t.type==="delta"?{id:S.ReferenceBlock,data:new $a(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:S.BlockAdditions,data:[{id:S.BlockMore,data:[{id:S.BlockAddID,data:1},{id:S.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:S.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(d)}else{c.setUint8(3,+(t.type==="key")<<7);const d={id:S.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(d)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:S.Cluster,size:this.format._options.appendOnly?-1:Qn,data:[{id:S.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(p(this.currentCluster),!this.format._options.appendOnly){const s=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),n=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(s,Qn),this.writer.seek(n)}if(this.format._options.onCluster){p(this.currentClusterStartMsTimestamp!==null);const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(s,n,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[s,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(s);const i=[...t.entries()].sort((s,n)=>s[0]-n[0]);for(const[s,n]of i)p(this.cues),this.cues.data.push({id:S.CuePoint,data:[{id:S.CueTime,data:s},...n.map(a=>({id:S.CueTrackPositions,data:[{id:S.CueTrack,data:a.track.id},{id:S.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(s=>s.track===e);i&&(i.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(),p(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,jn);const i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new ir(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),p(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}/*! 303 * Copyright (c) 2026-present, Vanilagy and contributors 304 * 305 * This Source Code Form is subject to the terms of the Mozilla Public 306 * License, v. 2.0. If a copy of the MPL was not distributed with this 307 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 308 */class Zd{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(),i=255,s=224|e.mpegVersionId<<3|e.layer<<1;let n;e.mpegVersionId&2?n=e.mpegVersionId&1?0:1:n=1;const a=0,o=155;let c=-1;const l=n*16*4+e.layer*16;for(let w=0;w<16;w++){const k=Qs[l+w];if($s(n,e.layer,1e3*k,e.sampleRate,a)>=o){c=w;break}}if(c===-1)throw new Error("No suitable bitrate found.");const d=c<<4|e.frequencyIndex<<2|a<<1,u=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=i,this.helper[1]=s,this.helper[2]=d,this.helper[3]=u,this.writer.write(this.helper.subarray(0,4));const h=us(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(ls);let f=0;e.frameCount!==null&&(f|=vt.FrameCount),e.fileSize!==null&&(f|=vt.FileSize),e.toc!==null&&(f|=vt.Toc),this.writeU32(f),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const g=Qs[l+c],m=$s(n,e.layer,1e3*g,e.sampleRate,a);this.writer.seek(t+m)}}/*! 309 * Copyright (c) 2026-present, Vanilagy and contributors 310 * 311 * This Source Code Form is subject to the terms of the Mozilla Public 312 * License, v. 2.0. If a copy of the MPL was not distributed with this 313 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 314 */class Jd extends ut{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 Zd(this.writer),Si(this.output._metadataTags)||new Wr(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 i=await this.mutex.acquire();try{const s=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&s){const n=q(t.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=n.getUint32(0,!1),o=ds(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");const c=us(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){const l=n.getUint32(c,!1);if(l===ls||l===Cr)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++}
314this.validateTimestamp(e,t.timestamp,t.type==="key"),s&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{i()}}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(),i=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);const s=new Uint8Array(100);for(let n=0;n<100;n++){const a=Math.floor(this.framePositions.length*(n/100)),o=this.framePositions[a]-this.xingFramePos;s[n]=256*(o/i)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=i,this.xingFrameData.toc=s,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,a)}e()}}/*! 315 * Copyright (c) 2026-present, Vanilagy and contributors 316 * 317 * This Source Code Form is subject to the terms of the Mozilla Public 318 * License, v. 2.0. If a copy of the MPL was not distributed with this 319 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 320 */const eh=8192;class th extends ut{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=J(),this.pageBytes=new Uint8Array(oo),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,ao({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const i=this.trackDatas.find(a=>a.track===e);if(i)return i;let s;do s=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===s));p(e.source._codec==="vorbis"||e.source._codec==="opus"),Tt(t),p(t),p(t.decoderConfig);const n={track:e,serialNumber:s,internalSampleRate:e.source._codec==="opus"?ti:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,
320currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(n,t),this.trackDatas.push(n),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}queueHeaderPackets(e,t){if(p(t.decoderConfig),e.track.source._codec==="vorbis"){p(t.decoderConfig.description);const i=ie(t.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let s=1;const n=()=>{let m=0;for(;;){const w=i[s++];if(w===void 0)throw new TypeError("Vorbis decoder description is too short.");if(m+=w,w<255)return m}},a=n(),o=n();if(i.length-s<=0)throw new TypeError("Vorbis decoder description is too short.");const l=i.subarray(s,s+=a);s+=o;const d=i.subarray(s),u=new Uint8Array(7);u[0]=3,u[1]=118,u[2]=111,u[3]=114,u[4]=98,u[5]=105,u[6]=115;const h=Js(u,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:h,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});const g=q(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(g&15),1<<(g>>4)],modeBlockflags:za(d).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const i=ie(t.decoderConfig.description),s=new Uint8Array(8),n=q(s);n.setUint32(0,1332770163,!1),n.setUint32(4,1415669619,!1);const a=Js(s,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:ms(i).preSkip}}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=n.currentTimestampInSamples,{durationInSamples:o,vorbisBlockSize:c}=no(t.data,n.codecInfo,n.vorbisLastBlocksize);n.currentTimestampInSamples+=o,n.vorbisLastBlocksize=c,n.packetQueue.push({data:t.data,timestampInSamples:a,durationInSamples:o,forcePageFlush:!1}),await this.interleavePages()}finally{s()}}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 i=t.packetQueue.shift();if(this.writePacket(t,i,!1),i.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,i=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<i&&(t=a,i=a.packetQueue[0].timestampInSamples)}if(!t)break;const s=t.packetQueue.shift(),n=t.packetQueue.length===0;this.writePacket(t,s,n)}e||await this.writer.flush()}writePacket(e,t,i){const s=t.timestampInSamples+t.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){const l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&s-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let n=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const l=Math.min(255,n);e.currentLacingValues.push(l),e.currentPageSize++,o+=l;const d=n<255;if(e.currentLacingValues.length===255){const u=t.data.subarray(a,o);if(a=o,e.currentPageData.push(u),e.currentPageSize+=u.length,this.writePage(e,i&&d),d)return}if(d)break;n-=255}const c=t.data.subarray(a);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=s,(e.currentPageSize>=eh||t.forcePageFlush)&&this.writePage(e,i)}writePage(e,t){this.pageView.setUint32(0,zr,!0),this.pageView.setUint8(4,0);let i=0;e.currentPageStartsWithFreshPacket||(i|=1),e.pagesWritten===0&&(i|=2),t&&(i|=4),this.pageView.setUint8(5,i);const s=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;Sc(this.pageView,6,s),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 n=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,n),n+=c.length;const a=this.pageBytes.subarray(0,n),o=ro(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(),i=this.trackDatas.find(s=>s.track===e);i&&(i.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()}}/*! 321 * Copyright (c) 2026-present, Vanilagy and contributors 322 * 323 * This Source Code Form is subject to the terms of the Mozilla Public 324 * License, v. 2.0. If a copy of the MPL was not distributed with this 325 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 326 */const ih=0,jo=4096,$n=256,sh=224,Yn=192,Zn=new Uint8Array([9,240]),Jn=new Uint8Array([70,1]);class rh extends ut{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(pe),this.packetView=q(this.packetBuffer),this.allTracksKnown=J(),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,ho(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const i=this.trackDatas.find(l=>l.track===e);if(i)return i;cs(t),p(t?.decoderConfig);const s=e.source._codec;p(s==="avc"||s==="hevc");const n=s==="avc"?27:36,a=$n+this.trackDatas.length,o=sh+this.videoTrackIndex++,c={track:e,pid:a,streamType:n,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1}
326;return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const i=this.trackDatas.find(l=>l.track===e);if(i)return i;Tt(t),p(t?.decoderConfig);const s=e.source._codec;p(s==="aac"||s==="mp3"||s==="ac3"||s==="eac3");let n,a;switch(s){case"aac":n=15,a=Yn+this.audioTrackIndex++;break;case"mp3":n=3,a=Yn+this.audioTrackIndex++;break;case"ac3":n=129,a=189;break;case"eac3":n=135,a=189;break}const o=$n+this.trackDatas.length,c={track:e,pid:o,streamType:n,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,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareVideoPacket(n,t,i);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareAudioPacket(n,t,i);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,i){const s=e.track.source._codec;if(e.inputIsAnnexB===null){const n=i?.decoderConfig?.description;if(e.inputIsAnnexB=!n,!e.inputIsAnnexB){const a=ie(n);s==="avc"?e.avcDecoderConfig=Aa(a):e.hevcDecoderConfig=Gc(a)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,s):this.prepareLengthPrefixedVideoPacket(e,t,s)}prepareAnnexBVideoPacket(e,t){const i=[];for(const n of si(e)){const a=e.subarray(n.offset,n.offset+n.length);(t==="avc"?Jt(a[0])===Pe.AUD:yt(a[0])===ne.AUD_NUT)||i.push(a)}const s=t==="avc"?Zn:Jn;return i.unshift(s),Ji(i)}prepareLengthPrefixedVideoPacket(e,t,i){const s=t.data,n=i==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(const c of Ir(s,n)){const l=s.subarray(c.offset,c.offset+c.length);(i==="avc"?Jt(l[0])===Pe.AUD:yt(l[0])===ne.AUD_NUT)||a.push(l)}if(t.type==="key")if(i==="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===ne.PPS_NUT)for(const d of l.nalUnits)a.unshift(d);for(const l of c.arrays)if(l.nalUnitType===ne.SPS_NUT)for(const d of l.nalUnits)a.unshift(d);for(const l of c.arrays)if(l.nalUnitType===ne.VPS_NUT)for(const d of l.nalUnits)a.unshift(d)}const o=i==="avc"?Zn:Jn;return a.unshift(o),Ji(a)}prepareAudioPacket(e,t,i){const s=e.track.source._codec;if(s==="mp3"||s==="ac3"||s==="eac3")return t.data;if(e.inputIsAdts===null){const c=i?.decoderConfig?.description;if(e.inputIsAdts=!c,!e.inputIsAdts){const l=rs(ie(c)),d=ya(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return t.data;p(e.adtsHeader),p(e.adtsHeaderBitstream);const n=e.adtsHeader,a=t.data.byteLength+n.byteLength;Ta(e.adtsHeaderBitstream,a);const o=new Uint8Array(a);return o.set(n,0),o.set(t.data,n.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 i=e.timestampProcessingQueue.map(s=>s.presentationTimestamp).sort((s,n)=>s-n);for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];n.decodeTimestamp=i[s],e.packetQueue.push(n)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}
326async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.packetQueue.length===0&&!n.closed)break e;n.packetQueue.length>0&&n.packetQueue[0].presentationTimestamp<i&&(t=n,i=n.packetQueue[0].presentationTimestamp)}if(!t)break;const s=t.packetQueue.shift();this.writePesPacket(t,s)}e||await this.writer.flush()}writeTables(){p(!this.tablesWritten),this.writePsiSection(ih,xt),this.writePsiSection(jo,ah(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let i=0,s=!0;for(;i<t.length;){const a=184-(s?1:0),o=t.length-i,c=Math.min(a,o);let l;s?(l=this.payloadBuffer.subarray(0,1+c),l[0]=0,l.set(t.subarray(i,i+c),1)):l=t.subarray(i,i+c),this.writeTsPacket(e,s,null,l),i+=c,s=!1}}writePesPacket(e,t){const i=e.track.type==="video",s=i?10:5,n=new Uint8Array(9+s),a=q(n),o=new K(n.subarray(9));pr(a,0,1,!1),n[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,i?192:128),a.setUint8(8,s);const l=Math.round(t.presentationTimestamp*Me);if(o.pos=0,o.writeBits(4,i?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),i){p(t.decodeTimestamp!==null);const f=Math.round(t.decodeTimestamp*Me);o.writeBits(4,1),o.writeBits(3,f>>>30&7),o.writeBits(1,1),o.writeBits(15,f>>>15&32767),o.writeBits(1,1),o.writeBits(15,f&32767),o.writeBits(1,1)}const d=n.length+t.data.length;let u=0,h=!0;for(;u<d;){const f=h,g=d-u,m=h&&t.isKeyframe,w=h&&!e.firstPacketWritten,k=Math.max(0,184-g);let y;m||w?y=Math.max(2,k):y=k;let T=null;if(y>0){const _=this.adaptationFieldBuffer;y===1?_[0]=0:(_[0]=y-1,_[1]=Number(w)<<7|Number(m)<<6,_.fill(255,2,y)),T=_.subarray(0,y)}const b=Math.min(184-y,g),P=this.payloadBuffer.subarray(0,b);let x=0;if(u<n.length){const _=Math.min(n.length-u,b);P.set(n.subarray(u,u+_),0),x=_}const I=Math.max(0,u-n.length),C=I+(b-x);x<b&&P.set(t.data.subarray(I,C),x),this.writeTsPacket(e.pid,f,T,P),u+=b,h=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,i,s){const n=this.continuityCounters.get(e)??0,a=s.length>0,o=i?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|n&15,a&&this.continuityCounters.set(e,n+1&15);let c=4;i&&(this.packetBuffer.set(i,c),c+=i.length),this.packetBuffer.set(s,c),c+=s.length,c<pe&&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(),i=this.trackDatas.find(s=>s.track===e);i&&(i.closed=!0,await this.flushTimestampQueue(i,!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 nh=79764919,Qo=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^nh:e<<1;Qo[r]=e>>>0&4294967295}const $o=r=>{let e=4294967295;for(let t=0;t<r.length;t++){const i=r[t];e=(e<<8^Qo[e>>>24^i])>>>0}return e},xt=new Uint8Array(16);{const r=q(xt);xt[0]=0,r.setUint16(1,45069,!1),r.setUint16(3,1,!1),xt[5]=193,xt[6]=0,xt[7]=0,r.setUint16(8,1,!1),r.setUint16(10,57344|jo&8191,!1),r.setUint32(12,$o(xt.subarray(0,12)),!1)}const ah=r=>{let e=0;for(const c of r)e+=5,c.streamType===129?e+=zi.length:c.streamType===135&&(e+=Di.length);const t=9+e+4,i=new Uint8Array(3+t-4),s=q(i);i[0]=2,s.setUint16(1,45056|t&4095,!1),s.setUint16(3,1,!1),i[5]=193,i[6]=0,i[7]=0,s.setUint16(8,65535,!1),s.setUint16(10,61440,!1);let n=12;for(const c of r)i[n++]=c.streamType,s.setUint16(n,57344|c.pid&8191,!1),n+=2,c.streamType===129?(s.setUint16(n,61440|zi.length,!1),n+=2,i.set(zi,n),n+=zi.length):c.streamType===135?(s.setUint16(n,61440|Di.length,!1),n+=2,i.set(Di,n),n+=Di.length):(s.setUint16(n,61440,!1),n+=2);const a=$o(i),o=new Uint8Array(i.length+4);return o.set(i,0),q(o).setUint32(i.length,a,!1),o};/*! 327 * Copyright (c) 2026-present, Vanilagy and contributors 328 * 329 * This Source Code Form is subject to the terms of the Mozilla Public 330 * License, v. 2.0. If a copy of the MPL was not distributed with this 331 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 332 */class oh{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))}}/*! 333 * Copyright (c) 2026-present, Vanilagy and contributors 334 * 335 * This Source Code Form is subject to the terms of the Mozilla Public 336 * License, v. 2.0. If a copy of the MPL was not distributed with this 337 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 338 */class ch extends ut{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 oh(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{if(this.headerWritten||(Tt(i),p(i),p(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="
338key"),!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{s()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let i;const s=e.source._codec,n=Ue(s);n.dataType==="ulaw"?i=Te.MULAW:n.dataType==="alaw"?i=Te.ALAW:n.dataType==="float"?i=Te.IEEE_FLOAT:i=Te.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=n.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(i),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*n.sampleSize),!Si(this.output._metadataTags)){const l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ge(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:d}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,d)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const i=new Set,s=(o,c)=>{if(!je(c)){console.warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const l=c.length+1,d=new Uint8Array(l);for(let u=0;u<c.length;u++)d[u]=c.charCodeAt(u);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(l),this.writer.write(d),l&1&&this.writer.write(new Uint8Array(1)),i.add(o)};for(const{key:o,value:c}of ei(e))switch(o){case"title":s("INAM",c),i.add("INAM");break;case"artist":s("IART",c),i.add("IART");break;case"album":s("IPRD",c),i.add("IPRD");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();s("ITRK",l),i.add("ITRK")}break;case"genre":s("IGNR",c),i.add("IGNR");break;case"date":s("ICRD",c.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":s("ICMT",c),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:ge(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];c==null||o.length!==4||i.has(o)||typeof c=="string"&&s(o,c)}const n=this.writer.getPos(),a=n-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(n),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const s=new Wr(this.writer).writeId3V2Tag(e),n=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(n),s&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire(),t=this.writer.getPos();this.isRf64?(p(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),p(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),p(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(p(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),p(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}/*! 339 * Copyright (c) 2026-present, Vanilagy and contributors 340 * 341 * This Source Code Form is subject to the terms of the Mozilla Public 342 * License, v. 2.0. If a copy of the MPL was not distributed with this 343 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 344 */class Yo{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(){p(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,s)=>i[s*e]:e===1&&t===4?this.channelMixer=(i,s,n)=>i[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(i,s,n)=>i[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .5*(i[n]+i[n+1])}:e===2&&t===4?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(i,s,n)=>i[s*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .25*(i[n]+i[n+1]+i[n+2]+i[n+3])}:e===4&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return .5*(i[a+n]+i[a+n+2])}:e===4&&t===6?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]:n===2||n===3?0:i[a+n-2]}:e===6&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return Math.SQRT1_2*(i[n]+i[n+1])+i[n+2]+.5*(i[n+4]+i[n+5])}:e===6&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return i[a+n]+Math.SQRT1_2*(i[a+2]+i[a+n+4])}:e===6&&t===4?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]+Math.SQRT1_2*i[a+2]:i[a+n+2]}:this.channelMixer=(i,s,n)=>n<e?i[s*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}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 i=e.allocationSize({planeIndex:0,format:"f32"}),s=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(s,{planeIndex:0,format:"f32"});const n=e.timestamp,a=Math.min(e.timestamp+e.duration,this.endTime),o=Math.floor(n*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 d=l-this.bufferStartFrame;p(d<this.bufferSizeInFrames);const f=(l/this.targetSampleRate-n)*this.sourceSampleRate,g=Math.floor(f),m=Math.ceil(f),w=f-g;for(let k=0;k<this.targetNumberOfChannels;k++){let y=0,T=0;g>=0&&g<e.numberOfFrames&&(y=this.channelMixer(s,g,k)),m>=0&&m<e.numberOfFrames&&(T=this.channelMixer(s,m,k));const b=y+w*(T-y),P=d*this.targetNumberOfChannels+k;this.outputBuffer[P]+=b}this.maxWrittenFrame===null?this.maxWrittenFrame=d:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,d)}}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 i=this.bufferStartFrame/this.targetSampleRate,s=new Le({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:i+this.timestampOffset,data:t});await this.onSample(s),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}/*! 345 * Copyright (c) 2026-present, Vanilagy and contributors 346 * 347 * This Source Code Form is subject to the terms of the Mozilla Public 348 * License, v. 2.0. If a copy of the MPL was not distributed with this 349 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 350 */class qr{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}
350_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??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class Fi extends qr{constructor(e){if(super(),this._connectedTrack=null,!_e.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${_e.join(", ")}.`);this._codec=e}}const fr=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Zo extends Fi{constructor(e){super(e)}add(e,t){if(!(e instanceof ee))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(),fr(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Kr{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
350dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new bi,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,i){const s=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const n=this.encodingConfig,a=n.sizeChangeBehavior??"deny";let o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="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(n.transform?.width!==void 0||n.transform?.height!==void 0||n.transform?.rotate!==void 0||n.transform?.crop!==void 0||n.transform?.force===!0||o&&a!=="passThrough"){let u=n.transform?.width,h=n.transform?.height,f=n.transform?.fit??"fill";o&&a!=="passThrough"&&(p(this.outputWidth),p(this.outputHeight),p(a!=="deny"),u=this.outputWidth,h=this.outputHeight,f=a);const g=await e.transform({width:u,height:h,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:f,alpha:n.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=g.displayWidth,this.outputHeight=g.displayHeight),t&&e.close(),e=g,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const d=n.transform?.frameRate;if(d!==void 0){const u=e.timestamp+e.duration,h=Zr(e.timestamp,d);if(this.frameRateLastSample!==null)if(h<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=u;return}else await this.padFrameRate(h,i);e===s&&(e=e.clone(),t=!0),e.setTimestamp(h),e.setDuration(1/d),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=h,this.frameRateLastEndTimestamp=u}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;let s;if(i.transform?.process){let n=i.transform.process(e);if(n instanceof Promise&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]),s=n.map(a=>a instanceof Ee?a:typeof VideoFrame<"u"&&a instanceof VideoFrame?new Ee(a):new Ee(a,{timestamp:e.timestamp,duration:e.duration}))}else s=[e];try{for(const n of s){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(n),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized);const a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(n.timestamp/a),c={...n.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.customEncoder){this.customEncoderQueueSize++;const d=n.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(d,l)).then(()=>this.customEncoderQueueSize--).catch(h=>this.error??=h).finally(()=>{d.close()});this.customEncoderQueueSize>=4&&await u}else{p(this.encoder);const d=n.toVideoFrame(),u=G(this.preciseTimings,d.timestamp,f=>f.microsecondTimestamp),h=u!==-1?this.preciseTimings[u]:null;if(h&&h.microsecondTimestamp===d.timestamp?(h.timestamp!==n.timestamp&&(h.timestampIsValid=!1),h.duration!==n.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(u+1,0,{microsecondTimestamp:d.timestamp,timestamp:n.timestamp,duration:n.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(d,l),d.close();else if(!!d.format&&!d.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(d,l),d.close();else{const g=d.displayWidth,m=d.displayHeight;this.splitter||(this.splitter=new Ss(g,m));const{colorFrame:w,alphaFrame:k}=await this.splitter.update(d);this.alphaFrameQueue.push(k),this.encoder.encode(w,l),w.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(const n of s)n!==e&&n.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);const s=Math.round((e-this.frameRateLastTimestamp)*i);for(let n=1;n<s;n++){const a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+n/i),a.setDuration(1/i),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=Ec({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);const i=Ac.find(s=>s.supports(this.encodingConfig.codec,t));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(s,n)=>{if(!(s instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(n!==void 0&&(!n||typeof n!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");fr(this.source._connectedTrack,s),this.encodingConfig.onEncodedPacket?.(s,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,s,n).catch(a=>{this.error??=a})},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 a=[],o=[];let c=0,l=0;const d=(h,f,g)=>{const m={};if(f){const b=new Uint8Array(f.byteLength);f.copyTo(b),m.alpha=b}let w=ee.fromEncodedChunk(h,m);const k=G(this.preciseTimings,h.timestamp,b=>b.microsecondTimestamp),y=k!==-1?this.preciseTimings[k]:null;let T=null;this.emittedEncoderPackets===0&&w.type==="delta"&&g?.decoderConfig&&(T=ps(this.encodingConfig.codec,g.decoderConfig,w.data)),(y&&y.microsecondTimestamp===h.timestamp||T!==null)&&(w=w.clone({t
350imestamp:y?.timestampIsValid?y.timestamp:void 0,duration:y?.durationIsValid?y.duration:void 0,type:T??void 0})),fr(this.source._connectedTrack,w),this.encodingConfig.onEncodedPacket?.(w,g),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,w,g).catch(b=>{this.error??=b}),this.emittedEncoderPackets++},u=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,f)=>{if(!this.alphaEncoder){d(h,null,f);return}const g=this.alphaFrameQueue.shift();p(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:h.type==="key"}),l++,g.close(),a.push({chunk:h,meta:f})):l===0?d(h,null,f):(o.push(c+l),a.push({chunk:h,meta:f}))},error:h=>{h.stack=u,this.error??=h}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){const h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,g)=>{l--;const m=a.shift();for(p(m!==void 0),d(m.chunk,f,m.meta),c++;o.length>0&&o[0]===c;){o.shift();const w=a.shift();p(w!==void 0),d(w.chunk,null,w.meta)}},error:f=>{f.stack=h,this.error??=f}}),this.alphaEncoder.configure(t)}}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){const t=this.encodingConfig.transform.frameRate,i=Zr(this.frameRateLastEndTimestamp,t);await this.padFrameRate(i)}this.frameRateLastSample?.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 this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}}let ea=!1;class Ss{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 i=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!Ss.forceCpu&&i&&!ea)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const s=this.canvas.getContext("webgl2",{alpha:!0});if(!s)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=s,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(s){this.gl=null,this.canvas=null,ea=!0,console.warn("Falling back to CPU for color/alpha splitting.",s)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){p(this.gl),p(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),i=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:i}}createVertexShader(){return p(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es 351 in vec2 a_position; 352 in vec2 a_texCoord; 353 out vec2 v_texCoord; 354 355 void main() { 356 gl_Position = vec4(a_position, 0.0, 1.0); 357 v_texCoord = a_texCoord; 358 } 359 `)}createColorProgram(){p(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es 360 precision highp float; 361 362 uniform sampler2D u_sourceTexture; 363 in vec2 v_texCoord; 364 out vec4 fragColor; 365 366 void main() { 367 vec4 source = texture(u_sourceTexture, v_texCoord); 368 fragColor = vec4(source.rgb, 1.0); 369 } 370 `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createAlphaProgram(){p(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es 371 precision highp float; 372 373 uniform sampler2D u_sourceTexture; 374 uniform vec2 u_resolution; // The width and height of the canvas 375 in vec2 v_texCoord; 376 out vec4 fragColor; 377 378 // This function determines the value for a single byte in the YUV stream 379 float getByteValue(float byteOffset) { 380 float width = u_resolution.x; 381 float height = u_resolution.y; 382 383 float yPlaneSize = width * height; 384 385 if (byteOffset < yPlaneSize) { 386 // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from 387 float y = floor(byteOffset / width); 388 float x = mod(byteOffset, width); 389 390 // Add 0.5 to sample the center of the texel 391 vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution; 392 393 // The luma value is the alpha from the source texture 394 return texture(u_sourceTexture, sampleCoord).a; 395 } else { 396 // Write a fixed value for chroma and beyond
397 return 128.0 / 255.0; 398 } 399 } 400 401 void main() { 402 // Each fragment writes 4 bytes (R, G, B, A) 403 float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x); 404 float baseByteOffset = pixelIndex * 4.0; 405 406 vec4 result; 407 for (int i = 0; i < 4; i++) { 408 float currentByteOffset = baseByteOffset + float(i); 409 result[i] = getByteValue(currentByteOffset); 410 } 411 412 fragColor = result; 413 } 414 `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){p(this.gl);const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){p(this.gl),p(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]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){p(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 p(this.gl),p(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){p(this.gl),p(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:i}=this.canvas,s=Math.ceil(t/2)*Math.ceil(i/2),n=t*i+s*2,a=Math.ceil(n/(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,n),p(o[t*i]===128),p(o[o.length-1]===128);const c={format:"I420",codedWidth:t,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){const s=new Blob([`(${lh.toString()})()`],{type:"application/javascript"}),n=URL.createObjectURL(s);this.worker=new Worker(n),URL.revokeObjectURL(n),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++,i=J();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}Ss.forceCpu=!0;const lh=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",n=>{const{id:a,sourceFrame:o}=n.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 n=>{const a=n.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");
414const o=n.codedWidth,c=n.codedHeight,l=n.allocationSize();if((!r||r.byteLength!==l)&&(r=new Uint8Array(l)),await n.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,o,c,a,n);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return s(r,o,c,a,n);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(n,a,o,c,l)=>{const d=a*o,u=Math.ceil(a/2),h=Math.ceil(o/2),f=d+u*h*2,g=new Uint8Array(f);for(let y=0,T=3;y<d;y++,T+=4)g[y]=n[T];g.fill(128,d);const m=new VideoFrame(n,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),w={format:"I420",codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[g.buffer]},k=new VideoFrame(g,w);return{colorFrame:m,alphaFrame:k}},s=(n,a,o,c,l)=>{const d=c.includes("P10"),u=c.includes("P12"),h=d||u?2:1;let f,g;c.startsWith("I420")?(f=Math.ceil(a/2),g=Math.ceil(o/2)):c.startsWith("I422")?(f=Math.ceil(a/2),g=o):(f=a,g=o);const m=a*o,w=f*g,k=m*h,y=w*h,T=m*h,b=k+y*2,P=c.replace("A",""),x=Math.ceil(a/2),I=Math.ceil(o/2),C=x*I,_=C*h,E=T+2*_,R=new Uint8Array(E),v=b;R.set(n.subarray(v,v+T),0);const z=T,W=d?512:u?2048:128;h===1?R.fill(W,z):new Uint16Array(R.buffer,z,2*C).fill(W);const O=d?"I420P10":u?"I420P12":"I420",U=new VideoFrame(n.subarray(0,b),{format:P,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0}),j={format:O,codedWidth:a,codedHeight:o,timestamp:l.timestamp,duration:l.duration??void 0,transfer:[R.buffer]},ae=new VideoFrame(R,j);return{colorFrame:U,alphaFrame:ae}}};class ta extends Fi{constructor(e){xr(e),super(e.codec),this._encoder=new Kr(this,e)}add(e,t){if(!(e instanceof Ee))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Uh extends Fi{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.");xr(t),super(t.codec),this._encoder=new Kr(this,t),this._canvas=e}add(e,t=0,i){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 s=new Ee(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Oh extends Fi{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(xr(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.frameRate!=null&&(typeof i.frameRate!="number"||i.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.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=J(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=i,this._encoder=new Kr(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,i=null,s=0,n=!1,a=null,o=0;const c=()=>{if(p(e!==null),!this._lastVideoFrame)return;p(i!==null),p(t!==null);const u=performance.now();for(;u-i>1e3/e;){i+=1e3/e;const h=t+s/e,f=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*h,duration:1e6/e});d(f,u)}};e!==null&&(this._timerHandle=Pc(c,4));const l=u=>{if(e===null)d(u);else{const h=performance.now();this._lastVideoFrame?(c(),this._lastVideoFrame?.close(),this._lastVideoFrame=u):(d(u.clone(),h),i=h,this._lastVideoFrame=u)}},d=(u,h=performance.now())=>{if(n){u.close();return}s++;const f=u.timestamp/1e6;if(this._paused){if(t!==null){if(a!==null&&this._options.timestampBase!=="unix"){const w=f-a;o-=w}a=f}u.close();return}if(t===null){t=f;let m;const w=this._options.timestampBase??"synced-zero";if(w==="unix")m=Date.now()/1e3;else if(w==="zero")m=0;
414else{const k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=h/1e3,m=0):m=h/1e3-k._firstMediaStreamTimestamp}o=m-t}if(a=f,this._encoder.getQueueSize()>=8){u.close();return}const g=new Ee(u,{timestamp:f+o});this._encoder.add(g,!0).catch(m=>{n=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(m),this._workerTrackId!==null&&Ws({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const u=new MediaStreamTrackProcessor({track:this._track}),h=new WritableStream({write:l});u.readable.pipeTo(h,{signal:this._abortController.signal}).catch(f=>{f instanceof DOMException&&f.name==="AbortError"||this._promiseWithResolvers.reject(f)})}else if(await fh())this._workerTrackId=dh++,Ws({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=h=>{const f=h.data;f.type==="videoFrame"&&f.trackId===this._workerTrackId?l(f.videoFrame):f.type==="error"&&f.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(f.error)},ze.addEventListener("message",this._workerListener);else if(e!==null){const h=document.createElement("video");h.style.position="fixed",h.style.left="-10000px",h.style.top="-10000px",h.style.width="1px",h.style.height="1px",h.style.opacity="0",h.style.pointerEvents="none",h.muted=!0,h.srcObject=new MediaStream([this._track]),document.body.appendChild(h),this._videoElement=h,h.addEventListener("loadeddata",()=>{if(n||!this._videoElement)return;const f=new VideoFrame(h,{timestamp:1e3*performance.now()});l(f),f.close()},{once:!0}),h.play().catch(f=>{n=!0,this._promiseWithResolvers.reject(f)})}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){this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&xc(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(p(this._workerListener),Ws({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(t=>{const i=s=>{const n=s.data;n.type==="trackStopped"&&n.trackId===this._workerTrackId&&(p(this._workerListener),ze.removeEventListener("message",this._workerListener),ze.removeEventListener("message",i),t())};ze.addEventListener("message",i)})),await this._encoder.flushAndClose(e)}}class Bi extends qr{constructor(e){if(super(),this._connectedTrack=null,!Ne.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ne.join(", ")}.`);this._codec=e}}class Jo extends Bi{constructor(e){super(e)}add(e,t){if(!(e instanceof ee))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 Gr{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 bi,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t){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 i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Yo({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,startTime:e.timestamp,endTime:1/0,onSample:async n=>{await this.processAndEncode(n,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&xa(e.format)!==i.transform.sampleFormat){const s=_a(e,i.transform.sampleFormat);t&&e.close(),e=s,t=!0}if(i.transform?.process){let s=i.transform.process(e);if(s instanceof Promise&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);for(const n of s){if(!(n instanceof Le))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(n,!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),p(this.encoderInitialized);
414{const i=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=s;else{const n=i-this.lastEndSampleIndex;if(n>=64){const a=new Le({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??=n).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await s,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{p(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){p(this.outputSampleSize),p(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let h=0;h<s;h+=o){const f=Math.min(o,e.numberOfFrames-h),g=f*i*this.outputSampleSize,m=new ArrayBuffer(g),w=new DataView(m);c.push({frameCount:f,view:w})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<i;h++){e.copyTo(d,{planeIndex:h,format:"f32-planar"});for(let f=0;f<c.length;f++){const{frameCount:g,view:m}=c[f];for(let w=0;w<g;w++)this.writeOutputValue(m,(w*i+h)*this.outputSampleSize,d[f*o+w])}}t&&e.close();const u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:n}};for(let h=0;h<c.length;h++){const{frameCount:f,view:g}=c[h],m=g.buffer,w=h*o,k=new ee(new Uint8Array(m),"key",a+w/n,f/n);this.encodingConfig.onEncodedPacket?.(k,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,k,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,s=_c({numberOfChannels:t,sampleRate:i,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(s);const n=Cc.find(a=>a.supports(this.encodingConfig.codec,s));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o).catch(c=>{this.error??=c})},await this.customEncoder.init();else if(ot.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(s)).supported)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);const o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let u=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?u=!0:u=rs(ie(l.decoderConfig.description)).objectType===0,u){const h=Number(ce(s.codec.split(".")));l.decoderConfig.description=Sr({objectType:h,numberOfChannels:l.decoderConfig.numberOfChannels,sampleRate:l.decoderConfig.sampleRate})}}let d=ee.fromEncodedChunk(c);d=d.clone({timestamp:Zt(d.timestamp,s.sampleRate),duration:c.duration!=null?Zt(d.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).cat
414ch(u=>{this.error??=u})},error:c=>{c.stack=o,this.error??=c}}),this.encoder.configure(s)}p(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:i,littleEndian:s}=Ue(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,me((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,me(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{const c=me(Math.floor(o*32767),-32768,32767);n.setUint8(a,cu(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{const c=me(Math.floor(o*32767),-32768,32767);n.setUint8(a,uu(c))}:p(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,me((o+1)*32767.5,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,me(Math.round(o*32767),-32768,32767),s):p(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>pr(n,a,me((o+1)*83886075e-1,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>Ic(n,a,me(Math.round(o*8388607),-8388608,8388607),s):p(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,me((o+1)*21474836475e-1,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,me(Math.round(o*2147483647),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):p(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):p(!1);break;default:ge(i),p(!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(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}}class ia extends Bi{constructor(e){Pr(e),super(e.codec),this._encoder=new Gr(this,e)}add(e){if(!(e instanceof Le))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Nh extends Bi{constructor(e){Pr(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Gr(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=Le._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Lh extends Bi{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Pr(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.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=J(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=i,this._encoder=new Gr(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,i=null,s=0;const n=a=>{if(t){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(i!==null&&this._options.timestampBase!=="unix"){const l=o-i;s-=l}i=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 d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,c=0):c=performance.now()/1e3-d._firstMediaStreamTimestamp}s=c-e}if(i=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+s),this._encoder.add(a,!0).catch(c=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(c),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>n(new Le(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 d=Le._fromAudioBuffer(l.inputBuffer,c);c+=l.inputBuffer.duration;for(const u of d)n(u)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(p(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}const uh=()=>{const r=(i,s)=>{s?self.postMessage(i,{transfer:s}):self.postMessage(i)};r({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",i=>{const s=i.data;switch(s.type){case"videoTrack":{t.set(s.trackId,s.track);const n=new MediaStreamTrackProcessor({track:s.track}),a=new WritableStream({write:c=>{if(!t.has(s.trackId)){c.close();return}r({type:"videoFrame",trackId:s.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(s.trackId,o),n.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||r({type:"error",trackId:s.trackId,error:c})})}break;case"stopTrack":{const n=e.get(s.trackId);n&&(n.abort(),e.delete(s.trackId)),t.get(s.trackId)?.stop(),t.delete(s.trackId),r({type:"trackStopped",trackId:s.trackId})}break;default:ge(s)}})};let dh=0,ze=null;
414const hh=()=>{const r=new Blob([`(${uh.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(r);ze=new Worker(e)};let Ls=null;const fh=async()=>Ls!==null?Ls:(ze||hh(),new Promise(r=>{p(ze);const e=t=>{const i=t.data;i.type==="support"&&(Ls=i.supported,ze.removeEventListener("message",e),r(i.supported))};ze.addEventListener("message",e)})),Ws=(r,e)=>{p(ze),ze.postMessage(r)};class ec extends qr{constructor(e){if(super(),this._connectedTrack=null,!Ft.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ft.join(", ")}.`);this._codec=e}}class Wh extends ec{constructor(e){super(e),this._error=null,this._lastMuxerPromise=Promise.resolve(),this._parser=new Au({codec:e,output:(t,i)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,i).catch(s=>{this._error??=s})}})}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()}}/*! 415 * Copyright (c) 2026-present, Vanilagy and contributors 416 * 417 * This Source Code Form is subject to the terms of the Mozilla Public 418 * License, v. 2.0. If a copy of the MPL was not distributed with this 419 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 420 */class mh extends ut{constructor(e,t){if(!(e._target instanceof pt))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:i})=>`playlist-${i}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(i=>i.isSingleFile?`segments-${i.playlist.n}${i.format.fileExtension}`:`segment-${i.playlist.n}-${i.n}${i.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(i=>`init-${i.n}${i.segmentFormat.fileExtension}`)}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(w=>w.metadata.isRelativeToUnixEpoch),i=this.output._tracks.some(w=>!w.metadata.isRelativeToUnixEpoch);if(t&&i)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 s=new Map,n=[];let a=!1,o=!1,c=!1;for(const w of this.output._tracks){w.type==="video"&&(a=!0);const k=new Map;for(const y of this.output._tracks){if(w===y||!w.canBePairedWith(y))continue;if(w.type===y.type){o||(console.warn(`Illegal pairing of two ${w.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(w.isVideoTrack()&&w.metadata.hasOnlyKeyPackets||y.isVideoTrack()&&y.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 T=k.get(y.source._codec);T||k.set(y.source._codec,T=[]),T.push(y)}for(const[,y]of k){const T=y.map(x=>x.id).join("-");n.find(x=>x.key===T)||n.push({name:y[0].type+"-"+(n.length+1),key:T,tracks:y,needsEmit:!1,firstNoUri:!1});let P=s.get(w);P||s.set(w,P=[]),P.push(T)}}const l=a?"video":"audio",d=[],u=[],h=[];for(const w of this.output._tracks){const k=s.get(w);if(k){if(p(k.length>0),w.type!==l)continue;for(const y of k){const T=n.find(b=>b.key===y);if(p(T),k.length===1&&T.tracks.length===1){const b=s.get(T.tracks[0]);if(p(b!==void 0),b.length===1){const P=n.find(x=>x.key===b[0]);if(P.tracks.length===1){p(P.tracks[0]===w),d.push({tracks:[w,T.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[w],linkedGroup:T}),T.needsEmit=!0}}else w.type==="video"?u.push(w):w.type==="audio"&&h.push(w)}const f=({metadata:w})=>{let k="";return k+=`${w.languageCode??le}-`,k+=`${w.name??""}-`,k+=`${w.disposition?.default??!0}-`,k+=`${w.disposition?.primary??!1}-`,k+=`${w.disposition?.forced??!1}-`,k};if(u.length>0)if(new Set(u.map(f)).size>1){const k={key:u.map(y=>y.id).join("-"),name:"video-"+(n.length+1),tracks:u,needsEmit:!0,firstNoUri:!0};n.push(k),d.push({tracks:[u[0]],linkedGroup:k})}else for(const k of u)d.push({tracks:[k],linkedGroup:null});if(h.length>0)if(new Set(h.map(f)).size>1){const k={key:h.map(y=>y.id).join("-"),name:"audio-"+(n.length+1),tracks:h,needsEmit:!0,firstNoUri:!0};n.push(k),d.push({tracks:[h[0]],linkedGroup:k})}else for(const k of h)d.push({tracks:[k],linkedGroup:null});const g=w=>{const k=[];let y=0,T=0,b=!1,P=null,x=-1/0;for(const I of w)I.isVideoTrack()?(y++,b||=(I.metadata.rotation??0)!==0):I.isAudioTrack()&&T++,k.push(I.source._codec);for(const I of Xt(this.format._options.segmentFormat)){const C=I.getSupportedCodecs(),_=I.getSupportedTrackCounts();if(k.some(R=>!C.includes(R))||y<_.video.min||y>_.video.max||T<_.audio.min||T>_.audio.max)continue;let E=0;b&&I.supportsVideoRotationMetadata&&E++,E>x&&(P=I,x=E)}return p(P),P},m=async w=>{if(w.some(P=>this.playlists.some(x=>x.tracks.includes(P))))throw new Error("Internal error: track is already registered in a playlist.");const k=g(w),y=this.playlists.length+1,T=await this.getPlaylistPath({n:y,tracks:w,segmentFormat:k});ph(T);const b={id:this.playlists.length+1,path:T,tracks:w,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Rt};return this.playlists.push(b),b};for(const w of n)if(w.needsEmit)for(let k=0;k<w.tracks.length;k++){const y=w.tracks[k];let T=this.playlists.find(b=>b.tracks[0].id===y.id);T??=await m([y]),this.playlistDeclarations.push({playlist:T,groupId:w.name,noUri:w.firstNoUri&&k===0,references:[]})}for(const w of d){let k=this.playlists.find(y=>y.tracks[0].id===w.tracks[0].id);k??=await m(w.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:w.linkedGroup?this.playlistDeclarations.filter(y=>y.groupId===w.linkedGroup.name):[]})}e()}async getMimeType(){return Yt}allTracksAreKnown(e){for(const t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(i=>i.track===t))return!1;return!0}async onTrackClose(e){const t=this.trackDatas.find(n=>n.track===e);t&&(t.closed=!0);const i=this.playlists.find(n=>n.tracks.includes(e));p(i);const s=await i.mutex.acquire();try{await this.advancePlaylist(i)}finally{s()}}getVideoTrackData(e,t){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;cs(t),p(t),p(t?.decoderConfig);const s=this.playlists.filter(n=>n.tracks.includes(e));return p(s.length===1),i={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:t.decoderConfig}},this.trackDatas.push(i),i}getAudioTrackData(e,t){let i=this.trackDatas.find(n=>n.track===e);if(i)return i;Tt(t),p(t),p(t?.decoderConfig);const s=this.playlists.filter(n=>n.tracks.includes(e));return p(s.length===1),i={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:t.decoderConfig}},this.trackDatas.push(i),i}async addEncodedVideoPacket(e,t,i){const s=this.getVideoTrackData(e,i),n=s.playlist,a=await n.mutex.acquire();
420try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addEncodedAudioPacket(e,t,i){const s=this.getAudioTrackData(e,i),n=s.playlist,a=await n.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addSubtitleCue(e,t,i){throw new Error("Unreachable.")}async advancePlaylist(e){if(p(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}const t=this.trackDatas.filter(n=>e.tracks.includes(n.track)),i=t.find(n=>n.info.type==="video"),s=t.find(n=>n.info.type==="audio");for(;;){const n=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let a=0,o=0;if(i&&(!i.closed||i.packets.length>0)){const T=i.packets.every(x=>x.timestamp<n);let b=null,P=null;if(T){if(!i.closed)return}else for(let x=0;x<i.packets.length;x++){const I=i.packets[x];if(b!==null&&I.timestamp>n)break;x>0&&I.type==="key"&&(b=I,P=x)}if(P!==null){if(a=P,s){const x=s.packets.findIndex(I=>I.timestamp>=b.timestamp);if(x!==-1)o=x;else if(s.closed)o=s.packets.length;else return}}else{if(!i.closed)return;a=i.packets.length;const x=vc(i.packets,C=>C.timestamp),I=i.packets[x];if(p(I),s)if(I.timestamp<n){const C=s.packets.findIndex(_=>_.timestamp>=n);if(C!==-1)o=C;else if(s.closed)o=s.packets.length;else return}else{const C=s.packets.findIndex(_=>_.timestamp>I.timestamp);if(C!==-1)o=C;else if(s.closed)o=s.packets.length;else return}}}else if(s&&(!s.closed||s.packets.length>0))if(s.packets.every(b=>b.timestamp<n))if(s.closed)o=s.packets.length;else return;else{const b=ns(s.packets,P=>P.timestamp<=n);o=Math.max(b,1)}if(a===0&&o===0){t.every(b=>b.closed)&&await this.onPlaylistDone(e);return}let c=null,l,d;p(this.output._target instanceof pt);const u=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const T={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Li(e)};
420l=await this.getSegmentPath(T),sa(l),d=de(de(u.rootPath,e.path),l);const b=await this.output._getTarget({path:d,isRoot:!1,mimeType:e.segmentFormat.mimeType});b._start(),e.singleFile={target:b,path:l,nextOffset:0,info:T}}else l=e.singleFile.path,d=de(de(u.rootPath,e.path),l);else c={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Li(e)},l=await this.getSegmentPath(c),sa(l),d=de(de(u.rootPath,e.path),l),e.nextSegmentId++;let h=0,f=null;const g=new mr({format:e.segmentFormat,target:new pt(d,async T=>{const b={...T,isRoot:!1};if(T.isRoot)if(e.singleFile){const P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:x})=>h=Math.max(h,x)),P}else{const P=await this.output._getTarget(b);return f=P,P.on("write",({end:x})=>h=Math.max(h,x)),P}return this.output._getTarget(b)}),initTarget:async()=>{if(e.initSegment)return new Xo;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const T=e.singleFile.target.slice(e.singleFile.nextOffset);return T.on("write",({end:b})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,b)}),T.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),T}else{const T=Li(e),b=await this.getInitPath(T);gh(b),e.initSegment={path:b,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const P=de(de(u.rootPath,e.path),b),x=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return x.on("write",({end:I})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,I)}),x.on("finalized",()=>{this.format._options.onInit?.(x,T)}),x}}});let m=-1/0;try{let T=null,b=null;if(i&&(T=new Zo(i.track.source._codec),g.addVideoTrack(T,i.track.metadata)),s&&(b=new Jo(s.track.source._codec),g.addAudioTrack(b,s.track.metadata)),await g.start(),i){p(T);const P={decoderConfig:i.info.decoderConfig};for(let x=0;x<a;x++){const I=i.packets[x];await T.add(I,P),m=Math.max(m,I.timestamp+I.duration)}}if(s){p(b);const P={decoderConfig:s.info.decoderConfig};for(let x=0;x<o;x++){const I=s.packets[x];await b.add(I,P),m=Math.max(m,I.timestamp+I.duration)}}await g.finalize()}catch(T){throw await g.cancel(),T}c&&(p(f),this.format._options.onSegment?.(f,c)),a>0&&(p(i),i.packets.splice(0,a)),o>0&&(p(s),s.packets.splice(0,o));let w=1/0;i&&i.packets.length>0&&(w=i.packets[0].timestamp),s&&s.packets.length>0&&(w=Math.min(w,s.packets[0].timestamp));const k=w<1/0?w:m;p(Number.isFinite(k));const y=k-e.currentSegmentStartTimestamp;if(p(y>=0),e.writtenSegments.push({path:l,duration:y,timestamp:e.currentSegmentStartTimestamp,byteSize:h,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:c??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,y),e.currentSegmentStartTimestamp=k,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=h),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const T=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(p(T.info),this.format._options.onSegmentPopped?.(T.path,T.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){p(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),this.format._options.onSegment?.(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 i=0,s=0,n=0;for(let a=0;a<t.length;a++){n+=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&&(i=Math.max(i,8*o/c)),!(c>1.5*this.globalTargetDuration));l++);}if(i===0)for(const a of t){const o=a.duration||1;i=Math.max(i,8*a.byteSize/o)}for(const a of t)s+=8*a.byteSize;e.peakBitrate=i,e.averageBitrate=s/(n||1)}async writePlaylist(e){p(this.output._target instanceof pt);const t=this.output._target;this.updatePlaylistBitrates(e);let i=!1;for(const u of e.writtenSegments)i||=u.byteOffset!==null;const s=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let n=3;(s||i)&&(n=4),e.initSegment&&(n=5),e.initSegment&&!s&&(n=6);const a=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=de(t.rootPath,e.path),c=`#EXTM3U 421#EXT-X-VERSION:${n} 422`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD 423`)+`#EXT-X-TARGETDURATION:${Math.ceil(a)} 424`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence} 425`:"")+`#EXT-X-INDEPENDENT-SEGMENTS 426`+(s?`#EXT-X-I-FRAMES-ONLY 427`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}
427"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+` 428`:"")+` 429`+e.writtenSegments.map(u=>`#EXTINF:${+u.duration.toFixed(12)}, 430`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*u.timestamp).toISOString()} 431`:"")+(u.byteOffset!==null?`#EXT-X-BYTERANGE:${u.byteSize}@${u.byteOffset} 432`:"")+`${u.path} 433`).join("")+(e.done?(e.writtenSegments.length>0?` 434`:"")+`#EXT-X-ENDLIST 435`:"");this.format._options.onPlaylist?.(c,Li(e));const l=await this.output._getTarget({path:o,isRoot:!1,mimeType:Yt}),d=new Ii(l,!0);d.start(),d.write($.encode(c)),await d.flush(),await d.finalize()}async writeMasterPlaylist(){p(this.output._target instanceof pt);const e=this.output._target;let t=`#EXTM3U 436`,i=!1,s=null,n=0,a=!1;for(const c of this.playlistDeclarations)if(c.groupId===null){const l=c.playlist.tracks[0].isVideoTrack()&&c.playlist.tracks[0].metadata.hasOnlyKeyPackets,d=[];for(const w of c.playlist.tracks){const y=this.trackDatas.find(T=>T.track===w)?.info.decoderConfig.codec??w.source._codec;d.push(y)}let u=0,h=0;if(c.references.length>0){const k=c.references[0].playlist.tracks[0],T=this.trackDatas.find(b=>b.track===k)?.info.decoderConfig.codec??k.source._codec;d.push(T);for(const b of c.references)p(b.playlist.peakBitrate!==null),u=Math.max(u,b.playlist.peakBitrate),h=Math.max(h,b.playlist.averageBitrate??0)}p(c.playlist.peakBitrate!==null);const f=c.playlist.peakBitrate+u,g=(c.playlist.averageBitrate??0)+h;
436i||(t+=` 437`,i=!0),l?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(f)}`,g>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(g)}`),t+=`,CODECS="${d.join(",")}"`;const m=c.playlist.tracks.find(w=>w.isVideoTrack());if(m?.isVideoTrack()){const k=this.trackDatas.find(y=>y.track===m)?.info.decoderConfig;if(k){let y=k.displayAspectWidth??k.codedWidth,T=k.displayAspectHeight??k.codedHeight;y!==void 0&&T!==void 0&&(m.metadata.rotation!==void 0&&m.metadata.rotation%180===90&&([y,T]=[T,y]),t+=`,RESOLUTION=${y}x${T}`)}!l&&m.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+m.metadata.frameRate.toFixed(3)}`)}if(!l){const w=new Map;for(const k of c.references){p(k.groupId!==null);const y=k.playlist.tracks[0].type;w.set(y,k.groupId)}for(const[k,y]of w)t+=`,${k.toUpperCase()}="${y}"`}l?(t+=`,URI="${c.playlist.path}"`,t+=` 438`):(t+=` 439`,t+=`${c.playlist.path} 440`)}else{p(c.playlist.tracks.length===1);const l=c.playlist.tracks[0],d=l.type;let u=l.metadata.name??null;const h=l.metadata.languageCode,f=l.metadata.disposition;(s===null||c.groupId!==s)&&(n=0,t+=` 441`,a=!1),s=c.groupId,n++,t+=`#EXT-X-MEDIA:TYPE=${d.toUpperCase()},GROUP-ID="${c.groupId}"`,u!==null&&/[\n\r"]/.test(u)&&(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."),u=null),u??=`${h??c.groupId}-${n}`,t+=`,NAME="${u}"`,h!==void 0&&(t+=`,LANGUAGE="${h}"`);const g=f?.primary??!1,m=f?.default??!0,w=f?.forced??!1;if(g&&!a&&(t+=",DEFAULT=YES",a=!0),(g||m)&&(t+=",AUTOSELECT=YES"),w&&(t+=",FORCED=YES"),d==="audio"){const y=this.trackDatas.find(T=>T.track===l)?.info.decoderConfig;y&&(t+=`,CHANNELS="${y.numberOfChannels}"`)}c.noUri||(t+=`,URI="${c.playlist.path}"`),t+=` 442`}this.format._options.onMaster?.(t);const o=await this.mutex.acquire();try{let c;if(this.numWrittenMasterPlaylists===0)c=await this.output._getRootWriter(!0);else{const l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Yt});c=new Ii(l,!0),c.start()}c.write($.encode(t)),await c.flush(),await c.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){p(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 ph=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.")},sa=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.")},gh=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.")},Li=r=>({n:r.id,tracks:r.tracks,segmentFormat:r.segmentFormat});/*! 443 * Copyright (c) 2026-present, Vanilagy and contributors 444 * 445 * This Source Code Form is subject to the terms of the Mozilla Public 446 * License, v. 2.0. If a copy of the MPL was not distributed with this 447 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 448 */class ve{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>_e.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ne.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ft.includes(e))}_codecUnsupportedHint(e){return""}}class Xr extends ve{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.");
vendor: 9,674 bytes, line 448
448if(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 Xd(e,this)}}class tc extends Xr{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ft]}_codecUnsupportedHint(e){return new ic().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class ra extends Xr{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[..._e,...jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ft]}}class ic extends Xr{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[..._e,...Ne]}_codecUnsupportedHint(e){return new tc().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class na extends ve{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.");if(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 Yd(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[..._e,...jt,...ot.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Ft]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class aa extends na{constructor(e){super(e)}getSupportedCodecs(){return[..._e.filter(e=>["vp8","vp9","av1"].includes(e)),...Ne.filter(e=>["opus","vorbis"].includes(e)),...Ft]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new na().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class Vh extends ve{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 Jd(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 Hh extends ve{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 ch(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[...ot.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 qh extends ve{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 th(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[...Ne.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class Kh extends ve{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 xu(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 Gh extends ve{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 Iu(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 Xh extends ve{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 rh(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[..._e.filter(e=>["avc","hevc"].includes(e)),...Ne.filter(e=>["aac","mp3","ac3","eac3"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class jh extends ve{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof ve)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof ve)))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.");
448if(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 mh(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Yt}getSupportedCodecs(){return[...new Set(Xt(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,i=!1;for(const s of Xt(this._options.segmentFormat)){const n=s.getSupportedTrackCounts();e||=n.video.max>0,t||=n.audio.max>0,i||=n.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 Xt(this._options.segmentFormat).some(e=>e.supportsVideoRotationMetadata)}get supportsTimestampedMediaData(){return!0}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}/*! 449 * Copyright (c) 2026-present, Vanilagy and contributors 450 * 451 * This Source Code Form is subject to the terms of the Mozilla Public 452 * License, v. 2.0. If a copy of the MPL was not distributed with this 453 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 454 */const kh=["video","audio","subtitle"];class Ri{constructor(e,t,i,s,n){this.id=e,this.output=t,this.type=i,this.source=s,this.metadata=n}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Ri))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Xt(this.metadata.group),i=Xt(e.metadata.group);for(const s of t)if(this.type!==e.type&&i.some(o=>s===o)||i.some(o=>s._pairedGroups.has(o)))return!0;return!1}}class wh extends Ri{constructor(e,t,i,s){super(e,t,"video",i,s)}}class yh extends Ri{constructor(e,t,i,s){super(e,t,"audio",i,s)}}class Th extends Ri{constructor(e,t,i,s){super(e,t,"subtitle",i,s)}}class We{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof We))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 Vs=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!wi(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&&Bc(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 We)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof We))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class mr extends os{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 We,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Rt,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 ve))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Se||e.target instanceof pt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Se&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Se)&&t
454ypeof 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 Se&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){p(this._target instanceof pt);const t=this._target.getTarget(e),i=s=>{if(!(s instanceof Se))throw new TypeError("getTarget must return a Target.");return s};return t instanceof Promise?t.then(i):i(t)}async _getTarget(e){p(this._target instanceof pt);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})}async _getInitTarget(){if(p(this._initTarget!==null),this._initTarget instanceof Se)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 Se)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),i=s=>(this.state==="canceled"?s._close():this._rememberTarget(s),this._emit("target",{target:s,request:e,isRoot:!0}),this._rootTarget=s,s);return t instanceof Promise?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new Ii(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Fi))throw new TypeError("source must be a VideoSource.");if(Vs(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 i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new wh(this._tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Bi))throw new TypeError("source must be an AudioSource.");Vs(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new yh(this._tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof ec))throw new TypeError("source must be a SubtitleSource.");Vs(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Th(this._tracks.length+1,this,e,i))}setMetadataTags(e){if(js(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(),i=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),s=t[e.type].max;if(i===s)throw new Error(s===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${s} ${e.type} track${s===1?"":"s"}.`);const n=t.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks${n===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))}
454else 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}async start(){const e=this.format.getSupportedTrackCounts();for(const i of kh){const s=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s<n)throw new Error(n===e[i].max?`${this.format._name} requires exactly ${n} ${i} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${i} track${n===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 i=await this._mutex.acquire();try{await this._muxer.start();const s=this._tracks.map(n=>n.source._start());await Promise.all(s)}finally{i()}})()}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(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._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(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}}/*! 455 * Copyright (c) 2026-present, Vanilagy and contributors 456 * 457 * This Source Code Form is subject to the terms of the Mozilla Public 458 * License, v. 2.0. If a copy of the MPL was not distributed with this 459 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 460 */const Wi=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!_e.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${_e.join(", ")}.`);if(r?.bitrate!==void 0&&!(r.bitrate instanceof Ca)&&(!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?.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?.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?.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'.");
460if(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?.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?.allowRotationMetadata!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(r?.crop!==void 0&&pa(r.crop,"options.video."),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?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(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?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(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?.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?.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?.group!==void 0&&!(r.group instanceof We||Array.isArray(r.group)&&r.group.every(e=>e instanceof We)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Vi=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!Ne.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Ne.join(", ")}.`);if(r?.bitrate!==void 0&&!(r.bitrate instanceof Ca)&&(!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?.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?.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?.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?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(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?.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?.group!==void 0&&!(r.group instanceof We||Array.isArray(r.group)&&r.group.every(e=>e instanceof We)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Hs=2,qs=48e3;class sc{static async init(e){const t=new sc(e);return await t._init(),t}constructor(e){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 Sh,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 Ts))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof mr))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.");
460if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const s of e.video)Wi(s);else Wi(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const s of e.audio)Vi(s);else Vi(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(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(e.trim?.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"&&js(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:i}=J();this._started=t,this._start=i}async _init(){const e=await this.input.getFormat();let t,i=this._options.tracks;if(i===void 0&&(i=e.name.includes("(HLS)")?"primary":"all"),i==="all")t=await this.input.getTracks();else if(i==="primary"){const f=await this.input.getPrimaryVideoTrack(),g=await this.input.getPrimaryAudioTrack();t=[f,g].filter(m=>m!==null)}else ge(i),p(!1);const s=this.output.format.getSupportedTrackCounts();let n=1,a=1;const o=[],c=[];for(const f of t){let g;if(f.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const k=await this._options.video(f,
460n)??{};if(Array.isArray(k))for(const y of k)Wi(y);else Wi(k);g=Array.isArray(k)?k:[k],n++}else g=Array.isArray(this._options.video)?this._options.video:[this._options.video];else g=[{}];else if(f.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const k=await this._options.audio(f,a)??{};if(Array.isArray(k))for(const y of k)Vi(y);else Vi(k);g=Array.isArray(k)?k:[k],a++}else g=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else g=[{}];else p(!1);const m=g.filter(k=>k.discard);for(const k of m)this.discardedTracks.push({track:f,reason:"discarded_by_user",trackOptions:k});if(g.length===m.length){g.length===0&&this.discardedTracks.push({track:f,reason:"discarded_by_user",trackOptions:{}});continue}const w=g.filter(k=>!k.discard);o.push(f),c.push(w)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let f=0;f<o.length;f++){const g=o[f],m=c[f];for(const w of m){if(this._totalTrackCount===s.total.max){this.discardedTracks.push({track:g,reason:"max_track_count_reached",trackOptions:w});continue}if(this._addedCounts[g.type]===s[g.type].max){this.discardedTracks.push({track:g,reason:"max_track_count_of_type_reached",trackOptions:w});continue}const k=this._nextOutputTrackId++;g.isVideoTrack()?await this._processVideoTrack(g,w,k):g.isAudioTrack()?await this._processAudioTrack(g,w,k):p(!1)}}for(let f=0;f<this.utilizedTracks.length-1;f++)for(let g=f+1;g<this.utilizedTracks.length;g++){const m=this.utilizedTracks[f],w=this.utilizedTracks[g],k=this._outputOwnTrackGroups[f],y=this._outputOwnTrackGroups[g];p(k!==void 0),p(y!==void 0),k&&y&&m.canBePairedWith(w)&&k.pairWith(y)}const l=await this.input.getMetadataTags();let d;if(this._options.tags){const f=typeof this._options.tags=="function"?await this._options.tags(l):this._options.tags;js(f),d=f}else d=l;const u=e.mimeType===this.output.format.mimeType,h=l.raw===d.raw;if(l.raw&&h&&!u&&delete d.raw,this.output.setMetadataTags(d),this.isValid=this._totalTrackCount>=s.total.min&&this._addedCounts.video>=s.video.min&&this._addedCounts.audio>=s.audio.min&&this._addedCounts.subtitle>=s.subtitle.min,this._options.showWarnings??!0){const f=[],g=this.discardedTracks.filter(m=>m.reason!=="discarded_by_user");g.length>0&&f.push("Some tracks had to be discarded from the conversion:",g),this.isValid||(f.length>0&&f.push(` 461 462`),f.push(this._getInvalidityExplanation().join(""))),f.length>0&&console.warn(...f)}}_getInvalidityExplanation(){const e=[];
462if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(i=>i.reason==="discarded_by_user"||i.reason==="no_encodable_target_codec")&&this.discardedTracks.some(i=>i.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const i=this.discardedTracks.flatMap(n=>n.reason==="discarded_by_user"?[]:n.track.type==="video"?this.output.format.getSupportedVideoCodecs():n.track.type==="audio"?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()),s=[...new Set(i)];s.length===1?e.push(` 463Tracks were discarded because your environment is not able to encode '${s[0]}'.`):e.push(` 464Tracks were discarded because your environment is not able to encode any of the following codecs: ${s.map(n=>`'${n}'`).join(", ")}.`),s.includes("mp3")&&e.push(` 465The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),s.includes("aac")&&e.push(` 466The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(s.includes("ac3")||s.includes("eac3"))&&e.push(` 467The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),s.includes("flac")&&e.push(` 468The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(` 469Check the discardedTracks field for more info.`)}return e}async execute(){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. 470`+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0;for(const e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){const t=[...new Set(this.utilizedTracks)].map(async s=>await s.isLive()?1/0:await s.getDurationFromMetadata()??await s.computeDuration()),i=Math.max(0,...await Promise.all(t));this._computeProgress=!0,this._totalDuration=Math.min(i-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const s of this._outputTrackIds)this._maxTimestamps.set(s,0);this.onProgress?.(0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new bh;if(await this.output.finalize(),this._computeProgress){const e=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,e)}}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,i){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let n;const a=await e.getRotation(),o=yi(a+(t.rotate??0));let c=o;const l=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),d=await e.getSquarePixelWidth(),u=await e.getSquarePixelHeight(),[h,f]=o%180===0?[d,u]:[u,d];let g=t.crop;g&&(g=ga(g,h,f));const[m,w]=g?[g.width,g.height]:[h,f];let k=m,y=w;const T=k/y;t.width!==void 0&&t.height===void 0?(k=Mt(t.width),y=Mt(Math.round(k/T))):t.width===void 0&&t.height!==void 0?(y=Mt(t.height),k=Mt(Math.round(y*T))):t.width!==void 0&&t.height!==void 0&&(k=Mt(t.width),y=Mt(t.height));const b=await e.getFirstTimestamp();let P=this.output.format.getSupportedVideoCodecs();const x=!!t.forceTranscode||b<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!P.includes(s)||t.codec&&t.codec!==s||k!==m||y!==w||o!==0&&!l||!!g,I=t.alpha??"discard";if(x){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(P=P.filter(U=>U===t.codec));const R=t.bitrate??Jr,v=await Fc(P,{width:t.process&&t.processedWidth?t.processedWidth:k,height:t.process&&t.processedHeight?t.processedHeight:y,bitrate:R});if(!v){this.discardedTracks.push({track:e,reason:"no_encodable_target_co
470dec",trackOptions:t});return}const z={codec:v,bitrate:R,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:I,hardwareAcceleration:t.hardwareAcceleration,transform:{}};p(z.transform);let W=k!==m||y!==w||o!==0&&(!l||t.process!==void 0)||!!g||d!==await e.getCodedWidth()||u!==await e.getCodedHeight();if(!W){const U=new mr({format:new tc,target:new Xo}),j=new ta(z);U.addVideoTrack(j),await U.start();const ke=await new lr(e).getSample(b);if(ke)try{await j.add(ke),ke.close(),await U.finalize()}catch(Mi){console.info("Error when probing encoder support. Falling back to rerender path.",Mi),W=!0,U.cancel()}else await U.cancel()}t.frameRate&&(z.transform.frameRate=t.frameRate),W&&(c=0,z.transform.width=k,z.transform.height=y,z.transform.fit=t.fit??"fill",z.transform.rotate=yi(o-a),z.transform.crop=g,z.transform.alpha=I);const O=new ta(z);n=O,this._trackPromises.push((async()=>{await this._started;const U=new lr(e);for await(const j of U.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){j.close();return}const ae=Math.max(j.timestamp-this._startTimestamp,0);
470j.setTimestamp(ae),await this._registerVideoSample(t,i,O,j),j.close()}O.close(),this._synchronizer.closeTrack(i)})())}else{const E=new Zo(s);n=E,this._trackPromises.push((async()=>{await this._started;const R=new Ci(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 O=W.clone({timestamp:W.timestamp-this._startTimestamp,sideData:I==="discard"?{}:W.sideData});p(O.timestamp>=0),this._reportProgress(i,O.timestamp+O.duration),await E.add(O,z),this._synchronizer.shouldWait(i,O.timestamp)&&await this._synchronizer.wait(O.timestamp)}E.close(),this._synchronizer.closeTrack(i)})())}let C=null;t.group||(C=new We);const _=await e.getLanguageCode();this.output.addVideoTrack(n,{frameRate:t.frameRate,languageCode:wi(_)?_:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:c,group:C??t.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(C)}async _registerVideoSample(e,t,i,s){if(this._canceled)return;this._reportProgress(t,s.timestamp+s.duration);let n;if(!e.process)n=[s];else{let a=e.process(s);a instanceof Promise&&(a=await a),Array.isArray(a)||(a=a===null?[]:[a]),n=a.map(o=>o instanceof Ee?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new Ee(o):new Ee(o,{timestamp:s.timestamp,duration:s.duration}))}try{for(const a of n){if(this._canceled)break;await i.add(a),this._synchronizer.shouldWait(t,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}}finally{for(const a of n)a!==s&&a.close()}}async _processAudioTrack(e,t,i){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let n;const a=await e.getNumberOfChannels(),o=await e.getSampleRate(),c=await e.getFirstTimestamp();let l=t.numberOfChannels??a,d=t.sampleRate??o,u=l!==a||d!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,h=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!u&&h.includes(s)&&(!t.codec||t.codec===s)&&!t.process&&t.sampleFormat===void 0){const m=new Jo(s);n=m,this._trackPromises.push((async()=>{await this._started;const w=new Ci(e),y={decoderConfig:await e.getDecoderConfig()??void 0};for await(const T of w.packets()){if(this._canceled)return;if(T.timestamp>=this._endTimestamp)break;const b=T.clone({timestamp:T.timestamp-this._startTimestamp});p(b.timestamp>=0),this._reportProgress(i,b.timestamp+b.duration),await m.add(b,y),this._synchronizer.shouldWait(i,b.timestamp)&&await this._synchronizer.wait(b.timestamp)}m.close(),this._synchronizer.closeTrack(i)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let w=null;t.codec&&(h=h.filter(T=>T===t.codec));const k=t.bitrate??Jr,y=await en(h,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:l,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:d,bitrate:k});if(!y.some(T=>jt.includes(T))&&h.some(T=>jt.includes(T))&&(l!==Hs||d!==qs)){const b=(await en(h,{numberOfChannels:Hs,sampleRate:qs,bitrate:k})).find(P=>jt.includes(P));b&&(u=!0,w=b,l=Hs,d=qs)}else w=y[0]??null;if(w===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}if(u)n=this._resampleAudio(e,t,i,w,l,d,k);else{const T=new ia({codec:w,bitrate:k});n=T,this._trackPromises.push((async()=>{await this._started;const b=new ur(e);for await(const P of b.samples(void 0,this._endTimestamp)){if(this._canceled){P.close();return}P.setTimestamp(P.timestamp-this._startTimestamp),await this._registerAudioSample(t,i,T,P),P.close()}T.close(),this._synchronizer.closeTrack(i)})())}}let f=null;t.group||(f=new We);const g=await e.getLanguageCode();this.output.addAudioTrack(n,{languageCode:wi(g)?g:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:f??t.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(f)}async _registerAudioSample(e,t,i,s){if(this._canceled)return;let n=s;e.sampleFormat!==void 0&&xa(n.format)!==e.sampleFormat&&(n=_a(n,e.sampleFormat)),this._reportProgress(t,n.timestamp+n.duration);let a;if(!e.process)a=[n];else{let o=e.process(n);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(c=>c instanceof Le))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 i.add(o),this._synchronizer.shouldWait(t,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}}finally{n!==s&&n.close();for(const o of a)o!==s&&o.close()}}_resampleAudio(e,t,i,s,n,a,o){const c=new ia({codec:s,bitrate:o});return this._trackPromises.push((async()=>{await this._started;const l=new Yo({targetNumberOfChannels:n,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async h=>{p(h.timestamp>=this._startTimestamp),h.setTimestamp(h.timestamp-this._startTimestamp),await this._registerAudioSample(t,i,c,h),h.close()}}),u=new ur(e).samples(this._startTimestamp,this._endTimestamp);for await(const h of u){if(this._canceled){h.close();return}await l.add(h),h.close()}await l.finalize(),c.close(),this._synchronizer.closeTrack(i)})()),c}_reportProgress(e,t){if(!this._computeProgress)return;p(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),s=me(i/this._totalDuration,0,1);s!==this._lastProgress&&(this._lastProgress=s,this.onProgress?.(s,i))}}
470class bh extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const oa=1;class Sh{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const i=this.maxTimestamps.get(e);p(i!==void 0),this.maxTimestamps.set(e,Math.max(t,i));const s=this.computeMinAndMaybeResolve();return t-s>oa}wait(e){const{promise:t,resolve:i}=J();return this.resolvers.push({timestamp:e,resolve:i}),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 i=this.resolvers[t];i.timestamp-e<oa&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}}/*! 471 * Copyright (c) 2026-present, Vanilagy and contributors 472 * 473 * This Source Code Form is subject to the terms of the Mozilla Public 474 * License, v. 2.0. If a copy of the MPL was not distributed with this 475 * file, You can obtain one at https://mozilla.org/MPL/2.0/. 476 */const rc=Symbol.for("mediabunny loaded");globalThis[rc]&&console.error(`[WARNING] 477Mediabunny 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[rc]=!0;export{vo as ADTS,vh as ALL_FORMATS,kh as ALL_TRACK_TYPES,Ne as AUDIO_CODECS,eu as AdtsInputFormat,Kh as AdtsOutputFormat,zh as AppendOnlyStreamTarget,_r as AttachedFile,Rh as AudioBufferSink,Nh as AudioBufferSource,Le as AudioSample,Yh as AudioSampleResource,ur as AudioSampleSink,ia as AudioSampleSource,Bi as AudioSource,Ro as BaseMediaSampleSink,Eh as BlobSource,Ih as BufferSource,Ns as BufferTarget,Bh as CanvasSink,Uh as CanvasSource,ra as CmafOutputFormat,Zh as ConcurrentRunner,sc as Conversion,bh as ConversionCanceledError,Jh as CustomAudioDecoder,ef as CustomAudioEncoder,Ul as CustomPathedSource,To as CustomSource,tf as CustomVideoDecoder,sf as CustomVideoEncoder,Jo as EncodedAudioPacketSource,ee as EncodedPacket,Ci as EncodedPacketSink,Zo as EncodedVideoPacketSource,os as EventEmitter,au as FLAC,yo as FilePathSource,Dh as FilePathTarget,Jl as FlacInputFormat,Gh as FlacOutputFormat,Bo as HLS,Fh as HLS_FORMATS,Co as HlsInputFormat,jh as HlsOutputFormat,Ts as Input,ys as InputAudioTrack,be as InputDisposedError,Xe as InputFormat,vi as InputTrack,ws as InputVideoTrack,xo as IsobmffInputFormat,Xr as IsobmffOutputFormat,iu as MATROSKA,Ao as MP3,Io as MP4,Fo as MPEG_TS,_o as MatroskaInputFormat,qr as MediaSource,Lh as MediaStreamAudioTrackSource,Oh as MediaStreamVideoTrackSource,na as MkvOutputFormat,ic as MovOutputFormat,$l as Mp3InputFormat,Vh as Mp3OutputFormat,Xl as Mp4InputFormat,tc as Mp4OutputFormat,tu as MpegTsInputFormat,Xh as MpegTsOutputFormat,jt as NON_PCM_AUDIO_CODECS,Xo as NullTarget,nu as OGG,Zl as OggInputFormat,qh as OggOutputFormat,mr as Output,yh as OutputAudioTrack,ve as OutputFormat,Th as OutputSubtitleTrack,Ri as OutputTrack,We as OutputTrackGroup,wh as OutputVideoTrack,ot as PCM_AUDIO_CODECS,ri as PathedSource,pt as PathedTarget,Eo as QTFF,Jr as QUALITY_HIGH,rf as QUALITY_LOW,nf as QUALITY_MEDIUM,af as QUALITY_VERY_HIGH,of as QUALITY_VERY_LOW,Ca as Quality,jl as QuickTimeInputFormat,Hl as RangedSource,qd as RangedTarget,Vl as ReadableStreamSource,Qt as RichImageData,Ft as SUBTITLE_CODECS,Ae as Source,Dr as SourceRef,Ah as StreamSource,Go as StreamTarget,ec as SubtitleSource,Se as Target,Wh as TextSubtitleSource,On as UnsupportedInputFormatError,wo as UrlSource,_e as VIDEO_CODECS,cf as VIDEO_SAMPLE_PIXEL_FORMATS,Ee as VideoSample,lf as VideoSampleColorSpace,uf as VideoSampleResource,lr as VideoSampleSink,ta as VideoSampleSource,Fi as VideoSource,ru as WAVE,su as WEBM,Hh as WavOutputFormat,Yl as WaveInputFormat,Ql as WebMInputFormat,aa as WebMOutputFormat,Mh as asc,df as canDecode,hf as canDecodeAudio,ff as canDecodeVideo,mf as canEncode,xh as canEncodeAudio,pf as canEncodeSubtitles,_h as canEncodeVideo,Un as desc,gf as getDecodableAudioCodecs,kf as getDecodableCodecs,wf as getDecodableVideoCodecs,en as getEncodableAudioCodecs,yf as getEncodableCodecs,Tf as getEncodableSubtitleCodecs,bf as getEncodableVideoCodecs,Sf as getFirstEncodableAudioCodec,Pf as getFirstEncodableSubtitleCodec,Fc as getFirstEncodableVideoCodec,ai as prefer,xf as registerDecoder,_f as registerEncoder,Cf as registerVideoSampleTransformer};
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.