@hyperframes/studio 0.9.45 → 0.9.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/assets/{hyperframes-player-C7JtYIRD.js → hyperframes-player-DTdMXCCs.js} +1 -1
  2. package/dist/assets/{index-C7EGuz1n.js → index-CdtV6F8j.js} +121 -121
  3. package/dist/assets/index-DA5GM2Mj.js +469 -0
  4. package/dist/assets/pausedVideoDecoder-B4OsoiOL.js +1 -0
  5. package/dist/{chunk-FQ3VRKMC.js → chunk-5ZHKYODQ.js} +1 -0
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +569 -534
  9. package/dist/{keys-CaWcxUST.d.ts → keys-B163OjLN.d.ts} +1 -0
  10. package/dist/keys.d.ts +1 -1
  11. package/dist/keys.js +1 -1
  12. package/package.json +9 -9
  13. package/src/captions/hooks/useCaptionSync.test.ts +45 -0
  14. package/src/captions/hooks/useCaptionSync.ts +8 -3
  15. package/src/hooks/gsapMutationClient.ts +6 -2
  16. package/src/hooks/useDomEditCommitsHelpers.test.ts +16 -0
  17. package/src/hooks/useDomEditCommitsHelpers.ts +3 -1
  18. package/src/hooks/useElementLifecycleOps.ts +1 -0
  19. package/src/hooks/useFreezeFrame.test.ts +9 -0
  20. package/src/hooks/useFreezeFrame.ts +3 -1
  21. package/src/hooks/useGroupCommits.ts +3 -0
  22. package/src/hooks/useTimelineDeleteOps.test.tsx +26 -0
  23. package/src/hooks/useTimelineDeleteOps.ts +3 -1
  24. package/src/player/components/ShortcutsPanel.test.tsx +75 -0
  25. package/src/player/components/ShortcutsPanel.tsx +20 -4
  26. package/src/player/components/studioKeyDefaults.ts +1 -0
  27. package/src/player/components/studioShortcuts.ts +1 -0
  28. package/src/player/lib/mediabunnyHevcSps.test.ts +169 -0
  29. package/src/utils/studioSaveDiagnostics.test.ts +10 -0
  30. package/src/utils/studioSaveDiagnostics.ts +10 -0
  31. package/src/utils/timelineCompositionInsert.ts +3 -1
  32. package/dist/assets/codec-DQ7n-U_9.js +0 -314
  33. package/dist/assets/index-CByWY7fK.js +0 -150
  34. package/dist/assets/pausedVideoDecoder-Bnvo9NIs.js +0 -1
@@ -1,150 +0,0 @@
1
- import{A as Ht,m as Ke,I as qt,v as le,p as Di,t as oe,b as Ni,a as m,w as Hi,B as we,F as yt,c as ce,d as K,e as Rt,f as Qe,r as vs,g as As,h as Ms,i as Is,j as qi,k as _e,l as Oi,s as Fs,n as $i,o as Bs,q as Be,u as gt,x as Ki,y as Rs,U as Ot,R as Ws,z as ve,C as Oe,D as Qi,V as $e,P as je,E as Gi,G as $t,T as Kt,M as Qt,H as zs,J as Us,K as Vs,L as Ls,N as Ds,O as ji,Q as Xi,S as Ns,W as Yi,X as Ee,Y as Hs,Z as qs,_ as Xe,$ as Os,a0 as $s,a1 as Ks,a2 as Qs,a3 as Gs,a4 as Zi,a5 as ft,a6 as Ji,a7 as es,a8 as ts,a9 as is,aa as ss,ab as js,ac as rs,ad as as,ae as Xs,af as ns,ag as Ys,ah as ht,ai as Jt,aj as bt,ak as Zs,al as w,am as ei,an as Js,ao as er,ap as tr,aq as Me,ar as ir,as as ti,at as Je,au as sr,av as rr,aw as ar,ax as nr,ay as or,az as ii,aA as cr,aB as ur,aC as Y,aD as dr,aE as si,aF as os,aG as ri,aH as cs,aI as us,aJ as _t,aK as Wt,aL as ai,aM as ni,aN as lr,aO as mr,aP as fr,aQ as hr,aR as pr,aS as lt,aT as gr,aU as wr,aV as Tr,aW as oi,aX as yr,aY as br,aZ as _r,a_ as ci,a$ as ui,b0 as di,b1 as Ne,b2 as li,b3 as kr,b4 as Sr,b5 as zt,b6 as et,b7 as tt,b8 as it,b9 as Cr,ba as mt,bb as xr,bc as be,bd as Ut,be as Vt,bf as st,bg as Re,bh as Fe,bi as ke,bj as Ue,bk as Ye,bl as Pr,bm as Ve,bn as We,bo as kt,bp as Er,bq as mi,br as vr,bs as Ar,bt as Lt,bu as Dt,bv as Mr,bw as Ir,bx as Fr,by as Br,bz as ze,bA as rt,bB as fi,bC as Rr,bD as hi,bE as pi,bF as gi,bG as Wr,bH as zr,bI as Ur,bJ as Vr,bK as Lr,bL as Dr}from"./codec-DQ7n-U_9.js";import{bM as $n,bN as Kn,bO as Qn,bP as Gn,bQ as jn,bR as Xn,bS as Yn,bT as Zn,bU as Jn,bV as eo,bW as to,bX as io,bY as so,bZ as ro,b_ as ao,b$ as no,c0 as oo,c1 as co,c2 as uo,c3 as lo,c4 as mo,c5 as fo,c6 as ho,c7 as po,c8 as go,c9 as wo,ca as To,cb as yo,cc as bo,cd as _o,ce as ko,cf as So,cg as Co,ch as xo,ci as Po,cj as Eo,ck as vo,cl as Ao,cm as Mo,cn as Io,co as Fo,cp as Bo,cq as Ro,cr as Wo,cs as zo,ct as Uo,cu as Vo,cv as Lo,cw as Do,cx as No,cy as Ho,cz as qo,cA as Oo,cB as $o,cC as Ko,cD as Qo,cE as Go,cF as jo,cG as Xo,cH as Yo,cI as Zo,cJ as Jo,cK as ec,cL as tc,cM as ic,cN as sc,cO as rc,cP as ac,cQ as nc,cR as oc,cS as cc,cT as uc,cU as dc,cV as lc,cW as mc,cX as fc,cY as hc,cZ as pc,c_ as gc,c$ as wc,d0 as Tc,d1 as yc,d2 as bc,d3 as _c,d4 as kc,d5 as Sc,d6 as Cc,d7 as xc,d8 as Pc}from"./codec-DQ7n-U_9.js";import{n as wi}from"./index-C7EGuz1n.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 Se{constructor(e){this.mutex=new Ht,this.trackPacketOrderValidators=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){let r=this.trackPacketOrderValidators.get(e);r||(r=new Nt,this.trackPacketOrderValidators.set(e,r));const a=i?"key":"delta";if(r.digest(t,a))return;if(r.maxTimestamp===null)throw new Error("First packet must be a key packet.");const n=a==="key"?r.maxTimestamp:r.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 ${n}s.`)}}class Nt{constructor(){this.maxTimestamp=null,this.maxTimestampBeforeLastKeyPacket=null}check(e,t){if(this.maxTimestamp===null)return t==="key";const i=t==="key"?this.maxTimestamp:this.maxTimestampBeforeLastKeyPacket;return i===null||e>=i}digest(e,t){return this.check(e,t)?(t==="key"&&(this.maxTimestampBeforeLastKeyPacket=this.maxTimestamp),this.maxTimestamp=Math.max(this.maxTimestamp??-1/0,e),!0):!1}}/*!
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
- */class Nr extends Se{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),Ke(this.output._metadataTags)||new qt(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){var a;const r=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){le(i,e.source._codec);const n=(a=i==null?void 0:i.decoderConfig)==null?void 0:a.description;if(this.inputIsAdts=!n,!this.inputIsAdts){const o=Di(oe(n)),c=Ni(o);this.header=c.header,this.headerBitstream=c.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{m(this.header);const n=t.data.byteLength+this.header.byteLength;Hi(this.headerBitstream,n);const o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const c=new Uint8Array(n);c.set(this.header,0),c.set(t.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.inputIsAdts===null)throw new Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}}/*!
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 Ti=new Uint8Array([102,76,97,67]),Hr=38,qr=34;class Or extends Se{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(Ti);const t=this.output.tracks[0];m(t==null?void 0:t.isAudioTrack()),t.metadata.decoderConfig&&(le({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.applyDecoderConfig(t.metadata.decoderConfig)),e()}applyDecoderConfig(e){m(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;const t=new we(oe(e.description));t.skipBits(167),this.bitsPerSample=t.readBits(5)+1,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})}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:r,maximumFrameSize:a,sampleRate:n,channels:o,totalSamples:c}){m(this.writer.getPos()===4);const d=!Ke(this.output._metadataTags),u=new we(new Uint8Array(4));u.writeBits(1,+!d),u.writeBits(7,yt.STREAMINFO),u.writeBits(24,qr),this.writer.write(u.bytes);const l=new we(new Uint8Array(18));if(l.writeBits(16,t),l.writeBits(16,i),l.writeBits(24,r),l.writeBits(24,a),l.writeBits(20,n),l.writeBits(3,o-1),l.writeBits(5,e-1),c>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");l.writeBits(4,0),l.writeBits(32,c),this.writer.write(l.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){var o,c,d;const t=32+e.mimeType.length+(((o=e.description)==null?void 0:o.length)??0)+e.data.length,i=new Uint8Array(t);let r=0;const a=ce(i);a.setUint32(r,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),r+=4,a.setUint32(r,e.mimeType.length),r+=4,i.set(K.encode(e.mimeType),8),r+=e.mimeType.length,a.setUint32(r,((c=e.description)==null?void 0:c.length)??0),r+=4,i.set(K.encode(e.description??""),r),r+=((d=e.description)==null?void 0:d.length)??0,r+=16,a.setUint32(r,e.data.length),r+=4,i.set(e.data,r),r+=e.data.length,m(r===t);const n=new we(new Uint8Array(4));n.writeBits(1,0),n.writeBits(7,yt.PICTURE),n.writeBits(24,t),this.writer.write(n.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Hr+Ti.byteLength),Ke(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const r of e)this.writePictureBlock(r);const t=Rt(new Uint8Array(0),this.output._metadataTags,!1),i=new we(new Uint8Array(4));i.writeBits(1,1),i.writeBits(7,yt.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 r=await this.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null&&(le(i,e.source._codec),m(i),m(i.decoderConfig),this.applyDecoderConfig(i.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const a=Qe.tempFromBytes(t.data);a.skip(2);const n=vs(a,2),o=new we(n),c=As(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");Ms(a);const d=Is(a,c);this.format._options.appendOnly||(this.blockSizes.push(d),this.frameSizes.push(t.data.length));const u=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,u),await this.writer.flush()}finally{r()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let t=1/0,i=0,r=1/0,a=0,n=0;for(let o=0;o<this.blockSizes.length;o++)r=Math.min(r,this.frameSizes[o]),a=Math.max(a,this.frameSizes[o]),i=Math.max(i,this.blockSizes[o]),n+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));this.blockSizes.length===0&&(t=16,i=65535,r=0,a=0),m(this.channels!==null),m(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:r,maximumFrameSize:a,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:n})}e()}}/*!
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
- */class at{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 a of e.children)a&&this.writeBox(a);const i=this.writer.getPos(),r=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,r),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);m(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 I=new Uint8Array(8),ue=new DataView(I.buffer),H=s=>[(s%256+256)%256],v=s=>(ue.setUint16(0,s,!1),[I[0],I[1]]),wt=s=>(ue.setInt16(0,s,!1),[I[0],I[1]]),ds=s=>(ue.setUint32(0,s,!1),[I[1],I[2],I[3]]),g=s=>(ue.setUint32(0,s,!1),[I[0],I[1],I[2],I[3]]),Te=s=>(ue.setInt32(0,s,!1),[I[0],I[1],I[2],I[3]]),me=s=>(ue.setUint32(0,Math.floor(s/2**32),!1),ue.setUint32(4,s,!1),[I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7]]),yi=s=>(ue.setInt32(0,Math.floor(s/2**32),!1),ue.setUint32(4,s,!1),[I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7]]),ls=s=>(ue.setInt16(0,2**8*s,!1),[I[0],I[1]]),ae=s=>(ue.setInt32(0,2**16*s,!1),[I[0],I[1],I[2],I[3]]),St=s=>(ue.setInt32(0,2**30*s,!1),[I[0],I[1],I[2],I[3]]),Ct=(s,e)=>{const t=[];let i=s;do{let r=i&127;i>>=7,t.length>0&&(r|=128),t.push(r)}while(i>0||e);return t.reverse()},V=(s,e=!1)=>{const t=Array(s.length).fill(null).map((i,r)=>s.charCodeAt(r));return e&&t.push(0),t},ms=s=>[ae(s[0]),ae(s[1]),St(s[2]),ae(s[3]),ae(s[4]),St(s[5]),ae(s[6]),ae(s[7]),St(s[8])],x=(s,e,t)=>({type:s,contents:e&&new Uint8Array(e.flat(10)),children:t}),B=(s,e,t,i,r)=>x(s,[H(e),ds(t),i??[]],r),$r=s=>s.isQuickTime?x("ftyp",[V("qt "),g(512),V("qt ")]):s.fragmented?s.cmaf?x("ftyp",[V("iso5"),g(512),V("iso5"),V("iso6"),V("mp41"),V("cmfc"),V("dash")]):x("ftyp",[V("iso5"),g(512),V("iso5"),V("iso6"),V("mp41")]):x("ftyp",[V("isom"),g(512),V("isom"),s.holdsAvc?V("avc1"):[],V("mp41")]),bi=()=>x("styp",[V("iso5"),g(0),V("iso5"),V("iso6"),V("mp41"),V("cmfc"),V("dash")]),_i=(s,e)=>{const t=Math.max(0,s.minWrittenTimestamp);let i=Math.max(0,s.maxWrittenEndTimestamp-t);return Number.isFinite(i)||(i=0),B("sidx",1,0,[g(1),g(se),me(D(t,se)),me(0),v(0),v(1),g(e&2147483647),g(D(i,se)),g(0)])},nt=s=>({type:"mdat",largeSize:s}),Kr=s=>({type:"free",size:s}),He=s=>x("moov",void 0,[Qr(s.creationTime,s.trackDatas),...s.trackDatas.map(e=>Gr(e,s.creationTime)),s.isFragmented?Wa(s.trackDatas):null,Ga(s)]),Qr=(s,e)=>{const t=Math.max(0,...e.map(n=>Math.max(0,D(Le(n),se)+D(n.startTimestampOffset??0,se)))),i=Math.max(0,...e.map(n=>n.track.id))+1,r=!_e(s)||!_e(t),a=r?me:g;return B("mvhd",+r,0,[a(s),a(s),g(se),a(t),ae(1),ls(1),Array(10).fill(0),ms(Xi),Array(24).fill(0),g(i)])},Gr=(s,e)=>{const t=on(s),i=s.startTimestampOffset!==null&&s.startTimestampOffset!==0;return x("trak",void 0,[jr(s,e),i?Xr(s):null,Yr(s,e),t.name!==void 0?x("udta",void 0,[x("name",[...K.encode(t.name)])]):null])},jr=(s,e)=>{var c;const t=Math.max(0,D(Le(s),se)+D(s.startTimestampOffset??0,se)),i=!_e(e)||!_e(t),r=i?me:g;let a;if(s.type==="video"&&s.track.metadata.transformationMatrix)a=s.track.metadata.transformationMatrix;else if(s.type==="video"){const{rotation:d,flip:u}=s.track.metadata,l=Oi($i(d??0),Fs(u?-1:1,1));a=Bs(l,s.info.width,s.info.height)}else a=Xi;let n=2;((c=s.track.metadata.disposition)==null?void 0:c.default)!==!1&&(n|=1);const o=s.type==="video"?0:s.type==="audio"?1:s.type==="subtitle"?2:Be(s);return B("tkhd",+i,n,[r(e),r(e),g(s.track.id),g(0),r(t),Array(8).fill(0),v(0),v(o),ls(s.type==="audio"?1:0),v(0),ms(a),ae(s.type==="video"?s.info.width:0),ae(s.type==="video"?s.info.height:0)])},Xr=s=>{const e=s.startTimestampOffset;if(m(e!==null),e>0){const t=D(e,se),i=D(Le(s),se),r=!_e(t)||!_e(i),a=r?me:g,n=r?yi:Te;return x("edts",void 0,[B("elst",r?1:0,0,[g(2),a(t),n(-1),ae(1),a(i),n(0),ae(1)])])}else{const t=D(-e,s.timescale),i=Math.max(0,D(Le(s),se)+D(e,se)),r=!Rs(t)||!_e(i),a=r?me:g,n=r?yi:Te;return x("edts",void 0,[B("elst",r?1:0,0,[g(1),a(i),n(t),ae(1)])])}},Yr=(s,e)=>x("mdia",void 0,[Zr(s,e),Gt(!0,Jr[s.type],ea[s.type]),ta(s)]),Zr=(s,e)=>{const t=D(Le(s),s.timescale),i=!_e(e)||!_e(t),r=i?me:g;return B("mdhd",+i,0,[r(e),r(e),g(s.timescale),r(t),v(ws(s.track.metadata.languageCode??Ot)),v(0)])},Jr={video:"vide",audio:"soun",subtitle:"text"},ea={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Gt=(s,e,t,i="\0\0\0\0")=>B("hdlr",0,0,[s?V("mhlr"):g(0),V(e),V(i),g(0),g(0),V(t,!0)]),ta=s=>x("minf",void 0,[aa[s.type](),na(),ua(s)]),ia=()=>B("vmhd",0,1,[v(0),v(0),v(0),v(0)]),sa=()=>B("smhd",0,0,[v(0),v(0)]),ra=()=>B("nmhd",0,0),aa={video:ia,audio:sa,subtitle:ra},na=()=>x("dinf",void 0,[oa()]),oa=()=>B("dref",0,0,[g(1)],[ca()]),ca=()=>B("url ",0,1),ua=s=>{const e=s.compositionTimeOffsetTable.length>1||s.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return x("stbl",void 0,[da(s),va(s),e?Ba(s):null,e?Ra(s):null,Ma(s),Ia(s),Fa(s),Aa(s),...fs(s.samples,!1)])},da=s=>{let e;if(s.type==="video")e=la(Ja(s.track.source._codec,s.info.decoderConfig.codec),s);else if(s.type==="audio"){const t=gs(s.track.source._codec,s.info.decoderConfig.codec,s.muxer.isQuickTime);m(t),e=wa(t,s)}else s.type==="subtitle"&&(e=Pa(tn[s.track.source._codec],s));return m(e),B("stsd",0,0,[g(1)],[e])},la=(s,e)=>{var t;return x(s,[Array(6).fill(0),v(1),v(0),v(0),Array(12).fill(0),v(e.info.width),v(e.info.height),g(4718592),g(4718592),g(0),v(1),H($e.length),V($e),Array(31-$e.length).fill(0),v(e.info.hasAlphaChannel?32:24),wt(65535)],[((t=Pt[e.track.source._codec])==null?void 0:t.call(Pt,e))??null,ma(e),Qi(e.info.decoderConfig.colorSpace)?null:fa(e),jt(e)])},jt=s=>s.avgBitrate===0&&s.maxBitrate===0?null:x("btrt",[g(0),g(s.maxBitrate),g(s.avgBitrate)]),ma=s=>s.info.pixelAspectRatio.num===s.info.pixelAspectRatio.den?null:x("pasp",[g(s.info.pixelAspectRatio.num),g(s.info.pixelAspectRatio.den)]),fa=s=>{const e=s.info.decoderConfig.colorSpace;return x("colr",[V(s.muxer.isQuickTime?"nclc":"nclx"),v((e==null?void 0:e.primaries)!=null?$t[e.primaries]:2),v((e==null?void 0:e.transfer)!=null?Kt[e.transfer]:2),v((e==null?void 0:e.matrix)!=null?Qt[e.matrix]:2),s.muxer.isQuickTime?[]:H((e!=null&&e.fullRange?1:0)<<7)])},ha=s=>s.info.decoderConfig&&x("avcC",[...oe(s.info.decoderConfig.description)]),pa=s=>s.info.decoderConfig&&x("hvcC",[...oe(s.info.decoderConfig.description)]),ki=s=>{var f,h,y,T;if(!s.info.decoderConfig)return null;const e=s.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),r=Number(t[2]),a=Number(t[3]),n=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(((f=e.colorSpace)==null?void 0:f.fullRange)??0),c=(a<<4)+(n<<1)+o,d=t[5]?Number(t[5]):(h=e.colorSpace)!=null&&h.primaries?$t[e.colorSpace.primaries]:1,u=t[6]?Number(t[6]):(y=e.colorSpace)!=null&&y.transfer?Kt[e.colorSpace.transfer]:1,l=t[7]?Number(t[7]):(T=e.colorSpace)!=null&&T.matrix?Qt[e.colorSpace.matrix]:1;return B("vpcC",1,0,[H(i),H(r),H(c),H(d),H(u),H(l),v(0)])},ga=s=>x("av1C",Gi(s.info.decoderConfig.codec)),wa=(s,e)=>{var n;let t=0,i,r=16;const a=je.includes(e.track.source._codec);if(a){const o=e.track.source._codec,{sampleSize:c}=ve(o);r=8*c,r>16&&(t=1)}if(e.muxer.isQuickTime&&e.track.source._codec!=="truehd"&&(t=1),t===0)i=[Array(6).fill(0),v(1),v(t),v(0),g(0),v(e.info.numberOfChannels),v(r),v(0),v(0),e.track.source._codec==="truehd"?g(e.info.sampleRate):[v(e.info.sampleRate<2**16?e.info.sampleRate:0),v(0)]];else{const o=a?0:-2;i=[Array(6).fill(0),v(1),v(t),v(0),g(0),v(e.info.numberOfChannels),v(Math.min(r,16)),wt(o),v(0),v(e.info.sampleRate<2**16?e.info.sampleRate:0),v(0),a?[g(1),g(r/8),g(e.info.numberOfChannels*r/8)]:[g(0),g(0),g(0)],g(2)]}return x(s,i,[((n=en(e.track.source._codec,e.muxer.isQuickTime))==null?void 0:n(e))??null,jt(e)])},xt=s=>{let e;switch(s.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: ${s.track.source._codec}`)}let t=[...H(e),...H(21),...ds(0),...g(s.maxBitrate),...g(s.avgBitrate)];if(s.info.decoderConfig.description){const i=oe(s.info.decoderConfig.description);t=[...t,...H(5),...Ct(i.byteLength),...i]}return t=[...v(1),...H(0),...H(4),...Ct(t.length),...t,...H(6),...H(1),...H(2)],t=[...H(3),...Ct(t.length),...t],B("esds",0,0,t)},xe=s=>x("wave",void 0,[Ta(s),ya(s),x("\0\0\0\0")]),Ta=s=>x("frma",[V(gs(s.track.source._codec,s.info.decoderConfig.codec,s.muxer.isQuickTime))]),ya=s=>{const{littleEndian:e}=ve(s.track.source._codec);return x("enda",[v(+e)])},ba=s=>{var c;let e=s.info.numberOfChannels,t=312,i=s.info.sampleRate,r=0,a=0,n=new Uint8Array(0);const o=(c=s.info.decoderConfig)==null?void 0:c.description;if(o){m(o.byteLength>=18);const d=oe(o),u=ji(d);e=u.outputChannelCount,t=u.preSkip,i=u.inputSampleRate,r=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(n=u.channelMappingTable)}return x("dOps",[H(0),H(e),v(t),g(i),wt(r),H(a),...n])},_a=s=>{var i;const e=(i=s.info.decoderConfig)==null?void 0:i.description;m(e);const t=oe(e);return B("dfLa",0,0,[...t.subarray(4)])},pe=s=>{const{littleEndian:e,sampleSize:t}=ve(s.track.source._codec),i=+e;return B("pcmC",0,0,[H(i),H(8*t)])},ka=s=>{m(s.info.primingPacket);const e=Ds(s.info.primingPacket.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 we(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.bsmod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),x("dac3",[...t])},Sa=s=>{m(s.info.primingPacket);const e=Ls(s.info.primingPacket.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 n of e.substreams)t+=23,n.numDepSub>0?t+=9:t+=1;const i=Math.ceil(t/8),r=new Uint8Array(i),a=new we(r);a.writeBits(13,e.dataRate),a.writeBits(3,e.substreams.length-1);for(const n of e.substreams)a.writeBits(2,n.fscod),a.writeBits(5,n.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,n.bsmod),a.writeBits(3,n.acmod),a.writeBits(1,n.lfeon),a.writeBits(3,0),a.writeBits(4,n.numDepSub),n.numDepSub>0?a.writeBits(9,n.chanLoc):a.writeBits(1,0);return x("dec3",[...r])},Ca=s=>{m(s.info.primingPacket);const e=Us(s.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return x("ddts",[...Vs(e)])},xa=s=>{m(s.info.primingPacket);const e=s.info.primingPacket.data;if(zs("truehd",e)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");const t=ce(e),i=t.getUint32(8),r=t.getUint16(18)&32767;return x("dmlp",[g(i),v(r<<1),g(0)])},Pa=(s,e)=>x(s,[Array(6).fill(0),v(1)],[sn[e.track.source._codec](e),jt(e)]),Ea=s=>x("vttC",[...K.encode(s.info.config.description)]),va=s=>B("stts",0,0,[g(s.timeToSampleTable.length),s.timeToSampleTable.map(e=>[g(e.sampleCount),g(e.sampleDelta)])]),Aa=s=>{if(s.samples.every(t=>t.type==="key"))return null;const e=[...s.samples.entries()].filter(([,t])=>t.type==="key");return B("stss",0,0,[g(e.length),e.map(([t])=>g(t+1))])},Ma=s=>B("stsc",0,0,[g(s.compactlyCodedChunkTable.length),s.compactlyCodedChunkTable.map(e=>[g(e.firstChunk),g(e.samplesPerChunk),g(1)])]),Ia=s=>{if(s.type==="audio"&&s.info.requiresPcmTransformation){const{sampleSize:e}=ve(s.track.source._codec);return B("stsz",0,0,[g(e*s.info.numberOfChannels),g(s.samples.reduce((t,i)=>t+D(i.duration,s.timescale),0))])}return B("stsz",0,0,[g(0),g(s.samples.length),s.samples.map(e=>g(e.size))])},Fa=s=>s.finalizedChunks.length>0&&Oe(s.finalizedChunks).offset>=2**32?B("co64",0,0,[g(s.finalizedChunks.length),s.finalizedChunks.map(e=>me(e.offset))]):B("stco",0,0,[g(s.finalizedChunks.length),s.finalizedChunks.map(e=>g(e.offset))]),Ba=s=>B("ctts",1,0,[g(s.compositionTimeOffsetTable.length),s.compositionTimeOffsetTable.map(e=>[g(e.sampleCount),Te(e.sampleCompositionTimeOffset)])]),Ra=s=>{if(m(s.compositionTimeOffsetTable.length>0),s.samples.length===0)return null;let e=1/0,t=-1/0,i=1/0,r=-1/0;for(let n=0;n<s.compositionTimeOffsetTable.length;n++){const o=s.compositionTimeOffsetTable[n];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let n=0;n<s.samples.length;n++){const o=s.samples[n];i=Math.min(i,D(o.timestamp,s.timescale)),r=Math.max(r,D(o.timestamp+o.duration,s.timescale))}const a=Math.max(-e,0);return r>=2**31?null:B("cslg",0,0,[Te(a),Te(e),Te(t),Te(i),Te(r)])},fs=(s,e)=>{const t=[];for(const a of s)if(t.length===0)t.push({sampleCount:1,prerollSamples:a.prerollSamples});else{const n=t[t.length-1];n.prerollSamples===a.prerollSamples?n.sampleCount++:t.push({sampleCount:1,prerollSamples:a.prerollSamples})}const i=t.filter(a=>a.prerollSamples!==0);if(i.length===0)return[];let r=e?65537:1;return[B("sgpd",1,0,[V("roll"),g(2),g(i.length),...i.map(a=>wt(a.prerollSamples))]),B("sbgp",0,0,[V("roll"),g(t.length),...t.map(a=>[g(a.sampleCount),g(a.prerollSamples!==0?r++:0)])])]},Wa=s=>x("mvex",void 0,s.map(za)),za=s=>B("trex",0,0,[g(s.track.id),g(1),g(0),g(0),g(0)]),Si=(s,e)=>x("moof",void 0,[Ua(s),...e.map(Va)]),Ua=s=>B("mfhd",0,0,[g(s)]),hs=s=>{let e=0,t=0;const i=0,r=0,a=s.type==="delta";return t|=+a,a?e|=1:e|=2,e<<24|t<<16|i<<8|r},Va=s=>x("traf",void 0,[La(s),Da(s),Na(s),...fs(s.currentChunk.samples,!0)]),La=s=>{m(s.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=s.currentChunk.samples[1]??s.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:hs(t)};return B("tfhd",0,e,[g(s.track.id),g(i.duration),g(i.size),g(i.flags)])},Da=s=>(m(s.currentChunk),B("tfdt",1,0,[me(D(s.currentChunk.startTimestamp,s.timescale))])),Na=s=>{m(s.currentChunk);const e=s.currentChunk.samples.map(T=>T.timescaleUnitsToNextSample),t=s.currentChunk.samples.map(T=>T.size),i=s.currentChunk.samples.map(hs),r=s.currentChunk.samples.map(T=>D(T.timestamp-T.decodeTimestamp,s.timescale)),a=new Set(e),n=new Set(t),o=new Set(i),c=new Set(r),d=o.size===2&&Ki(i,T=>T===i[0])===0,u=a.size>1,l=n.size>1,f=!d&&o.size>1,h=c.size>1||[...c].some(T=>T!==0);let y=0;return y|=1,y|=4*+d,y|=256*+u,y|=512*+l,y|=1024*+f,y|=2048*+h,B("trun",1,y,[g(s.currentChunk.samples.length),g(s.currentChunk.offset-s.currentChunk.moofOffset||0),d?g(i[0]):[],s.currentChunk.samples.map((T,p)=>[u?g(e[p]):[],l?g(t[p]):[],f?g(i[p]):[],h?Te(r[p]):[]])])},Ha=s=>x("mfra",void 0,[...s.map(qa),Oa()]),qa=s=>{const t=[];for(const i of s.finalizedChunks){const r=i.samples.findIndex(n=>n.type==="key");if(r===-1)continue;const a=i.samples[r];t.push([me(D(a.timestamp,s.timescale)),me(i.moofOffset),g(i.trafIndex+1),g(1),g(r+1)])}return B("tfra",1,0,[g(s.track.id),g(63),g(t.length),t])},Oa=()=>B("mfro",0,0,[g(0)]),$a=()=>x("vtte"),Ka=(s,e,t,i,r)=>x("vttc",void 0,[r!==null?x("vsid",[Te(r)]):null,t!==null?x("iden",[...K.encode(t)]):null,e!==null?x("ctim",[...K.encode(qi(e))]):null,i!==null?x("sttg",[...K.encode(i)]):null,x("payl",[...K.encode(s)])]),Qa=s=>x("vtta",[...K.encode(s)]),Ga=s=>{const e=[],t=s.format._options.metadataFormat??"auto",i=s.output._metadataTags;if(t==="mdir"||t==="auto"&&!s.isQuickTime){const r=Ya(i);r&&e.push(r)}else if(t==="mdta"){const r=Za(i);r&&e.push(r)}else(t==="udta"||t==="auto"&&s.isQuickTime)&&ja(e,s.output._metadataTags);return e.length===0?null:x("udta",void 0,e)},ja=(s,e)=>{for(const{key:t,value:i}of gt(e))switch(t){case"title":s.push(ge("©nam",i));break;case"description":s.push(ge("©des",i));break;case"artist":s.push(ge("©ART",i));break;case"album":s.push(ge("©alb",i));break;case"albumArtist":s.push(ge("albr",i));break;case"genre":s.push(ge("©gen",i));break;case"date":s.push(ge("©day",i.toISOString().slice(0,10)));break;case"comment":s.push(ge("©cmt",i));break;case"lyrics":s.push(ge("©lyr",i));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Be(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||s.some(r=>r.type===t)||(typeof i=="string"?s.push(ge(t,i)):i instanceof Uint8Array&&s.push(x(t,Array.from(i))))}},ge=(s,e)=>{const t=K.encode(e);return x(s,[v(t.length),v(ws("und")),Array.from(t)])},Ci={"image/jpeg":13,"image/png":14,"image/bmp":27},Xa=new Set(["HMMT","loci","chpl"]),ps=(s,e)=>{const t=[];for(const{key:i,value:r}of gt(s))switch(i){case"title":t.push({key:e?"title":"©nam",value:de(r)});break;case"description":t.push({key:e?"description":"©des",value:de(r)});break;case"artist":t.push({key:e?"artist":"©ART",value:de(r)});break;case"album":t.push({key:e?"album":"©alb",value:de(r)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:de(r)});break;case"comment":t.push({key:e?"comment":"©cmt",value:de(r)});break;case"genre":t.push({key:e?"genre":"©gen",value:de(r)});break;case"beatsPerMinute":e||t.push({key:"tmpo",value:x("data",[g(21),g(0),v(r)])});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:de(r)});break;case"date":t.push({key:e?"date":"©day",value:de(r.toISOString().slice(0,10))});break;case"images":for(const a of r)a.kind==="coverFront"&&t.push({key:"covr",value:x("data",[g(Ci[a.mimeType]??0),g(0),Array.from(a.data)])});break;case"trackNumber":if(e){const a=s.tracksTotal!==void 0?`${r}/${s.tracksTotal}`:r.toString();t.push({key:"track",value:de(a)})}else t.push({key:"trkn",value:x("data",[g(0),g(0),v(0),v(r),v(s.tracksTotal??0),v(0)])});break;case"discNumber":e||t.push({key:"disc",value:x("data",[g(0),g(0),v(0),v(r),v(s.discsTotal??0),v(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Be(i)}if(s.raw)for(const i in s.raw){const r=s.raw[i];r==null||!e&&(i.length!==4||Xa.has(i))||t.some(a=>a.key===i)||(typeof r=="string"?t.push({key:i,value:de(r)}):r instanceof Uint8Array?t.push({key:i,value:x("data",[g(0),g(0),Array.from(r)])}):r instanceof Ws&&t.push({key:i,value:x("data",[g(Ci[r.mimeType]??0),g(0),Array.from(r.data)])}))}return t},Ya=s=>{const e=ps(s,!1);return e.length===0?null:B("meta",0,0,void 0,[Gt(!1,"mdir","","appl"),x("ilst",void 0,e.map(t=>x(t.key,void 0,[t.value])))])},Za=s=>{const e=ps(s,!0);return e.length===0?null:x("meta",void 0,[Gt(!1,"mdta",""),B("keys",0,0,[g(e.length)],e.map(t=>x("mdta",[...K.encode(t.key)]))),x("ilst",void 0,e.map((t,i)=>{const r=String.fromCharCode(...g(i+1));return x(r,void 0,[t.value])}))])},de=s=>x("data",[g(1),g(0),...K.encode(s)]),Ja=(s,e)=>{switch(s){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Pt={avc:ha,hevc:pa,vp8:ki,vp9:ki,av1:ga,prores:null},gs=(s,e,t)=>{switch(s){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";case"dts":return e;case"truehd":return"mlpa"}if(t)switch(s){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(s){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"}},en=(s,e)=>{switch(s){case"aac":return xt;case"mp3":return xt;case"opus":return ba;case"vorbis":return xt;case"flac":return _a;case"ac3":return ka;case"eac3":return Sa;case"dts":return Ca;case"truehd":return xa}if(e)switch(s){case"pcm-s24":return xe;case"pcm-s24be":return xe;case"pcm-s32":return xe;case"pcm-s32be":return xe;case"pcm-f32":return xe;case"pcm-f32be":return xe;case"pcm-f64":return xe;case"pcm-f64be":return xe}else switch(s){case"pcm-s16":return pe;case"pcm-s16be":return pe;case"pcm-s24":return pe;case"pcm-s24be":return pe;case"pcm-s32":return pe;case"pcm-s32be":return pe;case"pcm-f32":return pe;case"pcm-f32be":return pe;case"pcm-f64":return pe;case"pcm-f64be":return pe}return null},tn={webvtt:"wvtt"},sn={webvtt:Ea},ws=s=>{m(s.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=s.charCodeAt(t)-96;return e};/*!
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 Ge{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(){m(!this.started),this.target._start(),this.started=!0}write(e){m(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 m(this.started&&!this.finalized),this.target._flush()}async finalize(){m(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 r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const a=new Uint8Array(r);a.set(this.trackedWrites,0),this.trackedWrites=a}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}}/*!
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 xi=typeof wi<"u"?wi:void 0;class ie extends Yi{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){var i;(i=this.onwrite)==null||i.call(this,e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new nn(this,e)}}const Et=2**16,vt=2**32;class At extends ie{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(Et,{maxByteLength:vt})}catch{this._buffer=new ArrayBuffer(Et),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Et);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){m(this._buffer),m(this._bytes);let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>vt)throw new Error(`ArrayBuffer exceeded maximum size of ${vt} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),r=new Uint8Array(i);r.set(this._bytes,0),this._buffer=i,this._bytes=r}}}_start(){}_write(e,t){m(this._bytes),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(){m(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return m(this._bytes),this._bytes.slice(e,t)}}const rn=2**24,an=2;class Ts extends ie{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??rn}_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(m(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((i,r)=>i.start-r.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){const r=e[e.length-1],a=t[i];a.start<=r.start+r.size?r.size=Math.max(r.size,a.start+a.data.byteLength-r.start):e.push({start:a.start,size:a.data.byteLength})}for(const i of e){i.data=new Uint8Array(i.size);for(const r of this._sections)i.start<=r.start&&r.start<i.start+i.size&&i.data.set(r.data,r.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(r=>{this._writeError??(this._writeError=r)}),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 r=this._chunks[i],a=t-r.start,n=e.subarray(0,Math.min(this._chunkSize-a,e.byteLength));r.data.set(n,a);const o={start:a,end:a+n.byteLength};if(this._insertSectionIntoChunk(r,o),r.written[0].start===0&&r.written[0].end===this._chunkSize&&(r.shouldFlush=!0),this._chunks.length>an){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}n.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(n.byteLength),t+n.byteLength)}_insertSectionIntoChunk(e,t){let i=0,r=e.written.length-1,a=-1;for(;i<=r;){const n=Math.floor(i+(r-i+1)/2);e.written[n].start<=t.start?(i=n+1,a=n):r=n-1}for(e.written.splice(a+1,0,t),(a===-1||e.written[a].end<t.start)&&a++;a<e.written.length-1&&e.written[a].end>=e.written[a+1].start;)e.written[a].end=Math.max(e.written[a].end,e.written[a+1].end),e.written.splice(a+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((r,a)=>r.start-a.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){m(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const i=this._chunks[t];if(!(!i.shouldFlush&&!e)){for(const r of i.written){const a=i.start+r.start;if(this._monotonicity===!0&&a!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");const n=r.start!==0||r.end!==i.data.byteLength;let o;n&&Ns()?o=i.data.slice(r.start,r.end):o=i.data.subarray(r.start,r.end),this._streamWriter.write({type:"write",data:o,position:a}).catch(c=>{this._writeError??(this._writeError=c)}),this._lastFlushEnd=i.start+r.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;m(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){var e;return(e=this._streamWriter)==null?void 0:e.close()}}class Rn extends ie{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new Ts(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>{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 m(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,m(this._writer),this._writer.write(t.data)},close:()=>{var t;return(t=this._writer)==null?void 0:t.close()}}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}_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 Wn extends ie{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(!xi.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 xi.fs.open(e,"w")},write:async r=>{m(this._fileHandle),await this._fileHandle.write(r.data,0,r.data.byteLength,r.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new Ts(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 ys extends ie{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class nn extends ie{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 Pe{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.")}}/*!
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 se=57600,Pi=.5,on=s=>{const e={},t=s.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},D=(s,e,t=!0)=>{const i=s*e;return t?Math.round(i):i},Le=s=>{if(s.samples.length===0)return 0;let e=1/0,t=-1/0;for(let i=0;i<s.samples.length;i++){const r=s.samples[i];r.timestamp<e&&(e=r.timestamp),r.timestamp+r.duration>t&&(t=r.timestamp+r.duration)}return e===1/0?0:t-e};class cn extends Se{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new At,this.auxWriter=new Ge(this.auxTarget,!1),this.auxBoxWriter=new at(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ee(),this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Cs,this.isCmaf=t instanceof Ri,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Ri?1/0:1),this.auxWriter.start()}async start(){var r;const e=await this.mutex.acquire(),t=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=t?Math.floor(t.getTime()/1e3)+Hs:0,t&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(a=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":a instanceof At),this.boxWriter=new at(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof At?"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 a=await this.output._getInitTarget(),n=new Ge(a,!0);n.start(),this.initWriter=n,this.initBoxWriter=new at(n)}const i=this.output.tracks.some(a=>a.isVideoTrack()&&a.source._codec==="avc");{const a=this.initBoxWriter??this.boxWriter;if(m(a),this.formatOptions.onFtyp&&a.writer.startTrackingWrites(),a.writeBox($r({isQuickTime:this.isQuickTime,holdsAvc:i,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:n,start:o}=a.writer.stopTrackingWrites();this.formatOptions.onFtyp(n,o)}this.ftypSize=a.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(const a of this.output.tracks){if(a.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(a.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${a.id} has a maximumPacketCount of ${a.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(m(this.writer),m(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nt(!0),this.boxWriter.writeBox(this.mdat));await((r=this.writer)==null?void 0:r.flush());for(const a of this.output.tracks)a.isVideoTrack()&&a.metadata.decoderConfig?this.getVideoTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig}):a.isAudioTrack()&&a.metadata.decoderConfig&&this.getAudioTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig});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 qs({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 r=this.trackDatas.find(h=>h.track===e);if(r)return r;Xe(i,e.source._codec),m(i),m(i.decoderConfig);const a={...i.decoderConfig};m(a.codedWidth!==void 0),m(a.codedHeight!==void 0);let n=!1;if(e.source._codec==="avc"&&!a.description){if(!t)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const h=Os(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.");a.description=$s(h),n=!0}else if(e.source._codec==="hevc"&&!a.description){if(!t)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const h=Ks(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.");a.description=Qs(h),n=!0}const o=Gs(1/(e.metadata.frameRate??se),1e6).den,c=a.displayAspectWidth,d=a.displayAspectHeight,u=c===void 0||d===void 0?{num:1,den:1}:Zi({num:c*a.codedHeight,den:d*a.codedWidth}),l=a.codec==="ap4h"||a.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:n,hasAlphaChannel:l},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((h,y)=>h.track.id-y.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,t,i){const r=this.trackDatas.find(c=>c.track===e);if(r)return r;le(i,e.source._codec),m(i),m(i.decoderConfig);const a={...i.decoderConfig};let n=!1;if(e.source._codec==="aac"&&!a.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=ft(Qe.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 d=Ji[c.samplingFrequencyIndex],u=es[c.channelConfiguration];if(d===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");a.description=ts({objectType:c.objectType,outputSampleRate:d,outputNumberOfChannels:u}),n=!0}if(!t){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&je.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:n,primingPacket:t,preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(o),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const i=this.trackDatas.find(a=>a.track===e);if(i)return i;is(t),m(t),m(t.config);const r={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,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,i){const r=await this.mutex.acquire();try{const a=this.getVideoTrackData(e,t,i);let n=t.data;if(a.info.requiresAnnexBTransformation){const c=[...ss(n)].map(d=>n.subarray(d.offset,d.offset+d.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.");n=js(c,4)}this.validateTimestamp(a.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(a,n,t.timestamp,t.duration,t.type,0);await this.registerSample(a,o)}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const a=this.getAudioTrackData(e,t,i);let n=t.data;if(a.info.requiresAdtsStripping){const f=ft(Qe.tempFromBytes(n));if(!f)throw new Error("Expected ADTS frame, didn't get one.");const h=f.crcCheck===null?rs:as;n=n.subarray(h)}this.validateTimestamp(a.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(a.info.requiresPcmTransformation){const h=ve(a.info.decoderConfig.codec).sampleSize*a.info.numberOfChannels;if(c=n.byteLength/h/a.info.sampleRate,a.info.expectedNextPcmPacketTimestamp!==null){const y=o-a.info.expectedNextPcmPacketTimestamp;if(y<.01)o=a.info.expectedNextPcmPacketTimestamp;else{const T=await this.padWithSilence(a,a.info.expectedNextPcmPacketTimestamp,y);o=a.info.expectedNextPcmPacketTimestamp+T}}a.info.expectedNextPcmPacketTimestamp=o+c}const{preroll:d}=a.info;let u=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")u=-Math.min(1,d.packetCount);else if(e.source._codec==="mp3")u=-Math.min(2,d.packetCount);else if(e.source._codec==="opus"){const f=Math.round(Xs*ns);u=-d.audioSampleDurationHistory.length;const h=Ys(n);for(d.accumulatedAudioSamples+=h.durationInSamples,d.audioSampleDurationHistory.push(h.durationInSamples);d.accumulatedAudioSamples-d.audioSampleDurationHistory[0]>=f;)d.accumulatedAudioSamples-=d.audioSampleDurationHistory.shift(),m(d.audioSampleDurationHistory.length>0)}d.packetCount++;const l=this.createSampleForTrack(a,n,o,c,t.type,u);await this.registerSample(a,l)}finally{r()}}async padWithSilence(e,t,i){const r=D(i,e.timescale);if(i=r/e.timescale,r>0){const{sampleSize:a,silentValue:n}=ve(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,c=new Uint8Array(a*o).fill(n),d=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,i,"key",0);await this.registerSample(e,d)}return i}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const a=this.getSubtitleTrackData(e,i);this.validateTimestamp(a.track,t.timestamp,!0),e.source._codec==="webvtt"&&(a.cueQueue.push(t),await this.processWebVTTCues(a,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??(e.lastCueEndTimestamp=Math.min(0,e.cueQueue[0].timestamp));const i=new Set([]);for(const d of e.cueQueue)m(d.timestamp<=t),m(e.lastCueEndTimestamp<=d.timestamp+d.duration),i.add(Math.max(d.timestamp,e.lastCueEndTimestamp)),i.add(d.timestamp+d.duration);const r=[...i].sort((d,u)=>d-u),a=r[0],n=r[1]??a;if(t<n)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);const d=$a();this.auxBoxWriter.writeBox(d);const u=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,u,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,l),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let d=0;d<e.cueQueue.length;d++){const u=e.cueQueue[d];if(u.timestamp>=n)break;ht.lastIndex=0;const l=ht.test(u.text),f=u.timestamp+u.duration;let h=e.cueToSourceId.get(u);if(h===void 0&&n<f&&(h=e.nextSourceId++,e.cueToSourceId.set(u,h)),u.notes){const T=Qa(u.notes);this.auxBoxWriter.writeBox(T)}const y=Ka(u.text,l?a:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(y),f===n&&e.cueQueue.splice(d--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,a,n-a,"key",0);await this.registerSample(e,c),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,i,r,a,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:D(r,e.timescale),prerollSamples:n}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){m(!this.isFragmented),e.startTimestampOffset??(e.startTimestampOffset=e.timestampProcessingQueue[0].timestamp);let r=0;for(let a=0;a<e.timestampProcessingQueue.length;a++){const n=e.timestampProcessingQueue[a],o=D(n.duration,e.timescale);r+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:r,sampleDelta:1});else{const a=Oe(e.timeToSampleTable);a.sampleCount+=r}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(r=>r.timestamp).sort((r,a)=>r-a);this.isFragmented?e.startTimestampOffset??(e.startTimestampOffset=Math.min(i[0],0)):e.startTimestampOffset??(e.startTimestampOffset=i[0]);for(let r=0;r<e.timestampProcessingQueue.length;r++){const a=e.timestampProcessingQueue[r];a.decodeTimestamp=i[r];const n=D(a.timestamp-a.decodeTimestamp,e.timescale),o=D(a.duration,e.timescale);if(e.lastTimescaleUnits!==null){m(e.lastSample);const c=D(a.decodeTimestamp,e.timescale,!1),d=Math.round(c-e.lastTimescaleUnits);if(m(d>=0),e.lastTimescaleUnits+=d,e.lastSample.timescaleUnitsToNextSample=d,!this.isFragmented){let u=Oe(e.timeToSampleTable);if(m(u),u.sampleCount===1){u.sampleDelta=d;const f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===d&&(f.sampleCount++,e.timeToSampleTable.pop(),u=f)}else u.sampleDelta!==d&&(u.sampleCount--,e.timeToSampleTable.push(u={sampleCount:1,sampleDelta:d}));u.sampleDelta===o?u.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const l=Oe(e.compositionTimeOffsetTable);m(l),l.sampleCompositionTimeOffset===n?l.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=D(a.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=a}if(e.timestampProcessingQueue.length=0,m(e.lastSample),m(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){m(t.type==="key");const r=D(t.timestamp,e.timescale,!1),a=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=a}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),e.sampleQueue.push(t),await this.interleaveSamples()}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const r=e.track.metadata.maximumPacketCount;if(m(r!==void 0),e.samples.length>r)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${r}). 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 r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(n=>{if(e===n)return t.type==="key";const o=n.sampleQueue[0];return o?o.type==="key":n.closed});r>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=Pi}if(i){if(!this.isFragmented){const r=this.trackDatas.filter(a=>a.currentChunk&&t.timestamp-a.currentChunk.startTimestamp>=Pi).sort((a,n)=>a.currentChunk.startTimestamp-n.currentChunk.startTimestamp);for(const a of r)await this.finalizeCurrentChunk(a)}e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}}m(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){m(!this.isFragmented),m(this.writer);const t=e.currentChunk;m(t),e.currentChunk=null,e.finalizedChunks.push(t),this.finalizedChunks.push(t);let i=t.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(i=t.samples.reduce((r,a)=>r+D(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Oe(e.compactlyCodedChunkTable).samplesPerChunk!==i)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:i}),this.fastStart==="in-memory"){t.offset=0;return}t.offset=this.writer.getPos();for(const r of t.samples)m(r.data),this.writer.write(r.data),r.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&a.sampleQueue.length===0&&!a.closed)break e;a.sampleQueue.length>0&&a.sampleQueue[0].timestamp<i&&(t=a,i=a.sampleQueue[0].timestamp)}if(!t)break;const r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}}async finalizeFragment(e=!this.isCmaf){if(m(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const h=this.initBoxWriter??this.boxWriter;m(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const y=He(this);if(h.writeBox(y),this.formatOptions.onMoov){const{data:T,start:p}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(T,p)}if(this.isCmaf){m(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new at(this.writer);const T=this.boxWriter.measureBox(bi()),p=this.boxWriter.measureBox(_i(this,0));this.segmentHeaderSize=T+p,this.writer.seek(this.segmentHeaderSize)}}m(this.writer),m(this.boxWriter);const t=this.trackDatas.filter(h=>h.currentChunk);if(t.length===0){e&&await this.writer.flush();return}const i=this.nextFragmentNumber++,r=Si(i,t),a=this.writer.getPos(),n=a+this.boxWriter.measureBox(r);let o=n+bt,c=1/0;for(let h=0;h<t.length;h++){const y=t[h];m(y.currentChunk),m(y.startTimestampOffset!==null),y.currentChunk.offset=o,y.currentChunk.moofOffset=a,y.currentChunk.trafIndex=h,y.currentChunk.startTimestamp-=y.startTimestampOffset;for(const T of y.currentChunk.samples)o+=T.size,T.timestamp-=y.startTimestampOffset,T.decodeTimestamp-=y.startTimestampOffset;c=Math.min(c,y.currentChunk.startTimestamp)}const d=o-n,u=d>=2**32;if(u)for(const h of t)h.currentChunk.offset+=Jt-bt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const l=Si(i,t);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:h,start:y}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,y,c)}m(this.writer.getPos()===n),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=nt(u);f.size=d,this.boxWriter.writeBox(f),this.writer.seek(n+(u?Jt:bt));for(const h of t)for(const y of h.currentChunk.samples)this.writer.write(y.data),y.data=null;if(this.formatOptions.onMdat){const{data:h,start:y}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,y)}for(const h of t)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async createFastStartReserveMdat(){m(this.writer),m(this.boxWriter),this.ensureOneEnabledTrack();const e=He(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;m(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nt(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){m(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;m(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,t.type==="audio"&&(e+=2*i,e+=8*i)}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(r=>r.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(),await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(const e of["video","audio","subtitle"]){const t=this.trackDatas.filter(r=>r.type===e);if(t.length===0)continue;if(!t.some(r=>{var a;return((a=r.track.metadata.disposition)==null?void 0:a.default)!==!1})){const r=t[0];r.track.metadata.disposition={...r.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){m(this.isFragmented);const e=await this.mutex.acquire();try{for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}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(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{const t=this.trackDatas.filter(i=>i.currentChunk).sort((i,r)=>i.currentChunk.startTimestamp-r.currentChunk.startTimestamp);for(const i of t)await this.finalizeCurrentChunk(i);for(const i of this.trackDatas){const r=Le(i);if(r>0){let c=0;for(const d of i.samples)c+=d.size;i.avgBitrate=Math.round(8*c/r)}else i.avgBitrate=0;let a=0,n=0,o=0;for(let c=0;c<i.samples.length;c++){const d=i.samples[c];for(n+=d.size;d.decodeTimestamp-i.samples[a].decodeTimestamp>=1;)n-=i.samples[a].size,a++;o=Math.max(o,n)}if(i.maxBitrate=8*o,i.startTimestampOffset!==null)for(let c=0;c<i.samples.length;c++){const d=i.samples[c];d.timestamp-=i.startTimestampOffset,d.decodeTimestamp-=i.startTimestampOffset}}}if(m(this.writer),m(this.boxWriter),this.fastStart==="in-memory"){this.mdat=nt(!1);let t;for(let r=0;r<2;r++){const a=He(this),n=this.boxWriter.measureBox(a);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+n+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:d}of c.samples)m(d),o+=d.byteLength,t+=d.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const i=He(this);if(this.boxWriter.writeBox(i),this.formatOptions.onMoov){const{data:r,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(r,a)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const r of this.finalizedChunks)for(const a of r.samples)m(a.data),this.writer.write(a.data),a.data=null;if(this.formatOptions.onMdat){const{data:r,start:a}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(r,a)}}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(bi()),this.boxWriter.writeBox(_i(this,t))}else{const t=this.writer.getPos(),i=Ha(this.trackDatas);this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{m(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);m(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.formatOptions.onMdat){const{data:a,start:n}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(a,n)}const r=He(this);if(this.fastStart==="reserve"){m(this.ftypSize!==null);const a=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,n=this.boxWriter.measureBox(r);if(n+8>a)throw new Error(`The moov box (${n} bytes) plus a free box (8 bytes) exceed the space reserved for them (${a} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r),this.boxWriter.writeBox(Kr(a-n))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.formatOptions.onMoov){const{data:a,start:n}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(a,n)}}e()}}/*!
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 un=-32768,dn=2**15-1,Ei=6,ln=5,mn={video:1,audio:2,subtitle:17};class fn extends Se{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=Ee(),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.currentClusterBlocks=[],this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Zs(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig&&this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:w.EBML,data:[{id:w.EBMLVersion,data:1},{id:w.EBMLReadVersion,data:1},{id:w.EBMLMaxIDLength,data:4},{id:w.EBMLMaxSizeLength,data:8},{id:w.DocType,data:this.format instanceof Mt?"webm":"matroska"},{id:w.DocTypeVersion,data:4},{id:w.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]),r=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),n=new Uint8Array([18,84,195,103]),o={id:w.SeekHead,data:[{id:w.Seek,data:[{id:w.SeekID,data:i},{id:w.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:w.Seek,data:[{id:w.SeekID,data:r},{id:w.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:w.Seek,data:[{id:w.SeekID,data:a},{id:w.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:w.Seek,data:[{id:w.SeekID,data:n},{id:w.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:w.Seek,data:[{id:w.SeekID,data:t},{id:w.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=o}createSegmentInfo(){const e={id:w.Duration,data:new ei(0)};this.segmentDuration=e;const t=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;let i=null;if(t){const a=1000000n*BigInt(t.getTime()-Js);if(BigInt.asIntN(64,a)!==a)throw new Error("creationTime is out of the range representable by Matroska files.");i={id:w.DateUTC,size:8,data:BigInt.asUintN(64,a)}}const r={id:w.Info,data:[{id:w.TimestampScale,data:1e6},this.format._options.appendOnly?null:e,i,{id:w.MuxingApp,data:$e},{id:w.WritingApp,data:$e}]};this.segmentInfo=r}createTracks(){var t,i,r,a,n,o;const e={id:w.Tracks,data:[]};this.tracksElement=e;for(const c of this.trackDatas){let d=er[c.track.source._codec];m(d),c.type==="audio"&&c.track.source._codec==="dts"&&(c.info.decoderConfig.codec==="dtse"?d="A_DTS/EXPRESS":c.info.decoderConfig.codec==="dtsl"&&(d="A_DTS/LOSSLESS"));let u=0;if(c.type==="audio"){const l=tr(c.track.source._codec,c.info.decoderConfig);u=Math.round(1e9*l)}e.data.push({id:w.TrackEntry,data:[{id:w.TrackNumber,data:c.track.id},{id:w.TrackUID,data:c.track.id},{id:w.TrackType,data:mn[c.type]},((t=c.track.metadata.disposition)==null?void 0:t.default)===!1?{id:w.FlagDefault,data:0}:null,(i=c.track.metadata.disposition)!=null&&i.forced?{id:w.FlagForced,data:1}:null,(r=c.track.metadata.disposition)!=null&&r.hearingImpaired?{id:w.FlagHearingImpaired,data:1}:null,(a=c.track.metadata.disposition)!=null&&a.visuallyImpaired?{id:w.FlagVisualImpaired,data:1}:null,(n=c.track.metadata.disposition)!=null&&n.original?{id:w.FlagOriginal,data:1}:null,(o=c.track.metadata.disposition)!=null&&o.commentary?{id:w.FlagCommentary,data:1}:null,{id:w.FlagLacing,data:0},{id:w.Language,data:c.track.metadata.languageCode??Ot},{id:w.CodecID,data:d},c.codecPrivate?{id:w.CodecPrivate,data:oe(c.codecPrivate)}:null,c.type==="audio"&&c.info.codecDelay?{id:w.CodecDelay,data:Math.round(1e9*c.info.codecDelay)}:null,u>0?{id:w.SeekPreRoll,data:u}:null,c.track.metadata.name!==void 0?{id:w.Name,data:new Me(c.track.metadata.name)}:null,c.type==="video"?this.videoSpecificTrackInfo(c):null,c.type==="audio"?this.audioSpecificTrackInfo(c):null,c.type==="subtitle"?this.subtitleSpecificTrackInfo(c):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,transformationMatrix:i}=e.track.metadata,r=[t?{id:w.DefaultDuration,data:1e9/t}:null];let a,n,o;if(i){a=ir(i);const y=Oi($i(-a),i);n=Math.sign(y[0]),o=Math.sign(y[4]),o===-1&&(o=1,n=-n,a=ti(a+180))}else a=e.track.metadata.rotation??0,n=e.track.metadata.flip?-1:1,o=1;const c=a?ti(n===-1?a:-a):0,d=Math.round(Math.acos(n)*si),u=Math.round(Math.acos(o)*si),l=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,h={id:w.Video,data:[{id:w.PixelWidth,data:e.info.width},{id:w.PixelHeight,data:e.info.height},l?{id:w.DisplayWidth,data:e.info.aspectRatio.num}:null,l?{id:w.DisplayHeight,data:e.info.aspectRatio.den}:null,l?{id:w.DisplayUnit,data:3}:null,e.info.alphaMode?{id:w.AlphaMode,data:1}:null,Qi(f)?null:{id:w.Colour,data:[{id:w.MatrixCoefficients,data:(f==null?void 0:f.matrix)!=null?Qt[f.matrix]:2},{id:w.TransferCharacteristics,data:(f==null?void 0:f.transfer)!=null?Kt[f.transfer]:2},{id:w.Primaries,data:(f==null?void 0:f.primaries)!=null?$t[f.primaries]:2},{id:w.Range,data:(f==null?void 0:f.fullRange)!=null?f.fullRange?2:1:0}]},c||d||u?{id:w.Projection,data:[{id:w.ProjectionType,data:0},d?{id:w.ProjectionPoseYaw,data:new Je(d)}:null,u?{id:w.ProjectionPosePitch,data:new Je(u)}:null,c?{id:w.ProjectionPoseRoll,data:new Je((c+180)%360-180)}:null]}:null]};return r.push(h),r}audioSpecificTrackInfo(e){const t=je.includes(e.track.source._codec)?ve(e.track.source._codec):null;return[{id:w.Audio,data:[{id:w.SamplingFrequency,data:new Je(e.info.sampleRate)},{id:w.Channels,data:e.info.numberOfChannels},t?{id:w.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(a,n)=>{e.push({id:w.SimpleTag,data:[{id:w.TagName,data:new Me(a)},typeof n=="string"?{id:w.TagString,data:new Me(n)}:{id:w.TagBinary,data:n}]})},i=this.output._metadataTags,r=new Set;for(const{key:a,value:n}of gt(i))switch(a){case"title":t("TITLE",n),r.add("TITLE");break;case"description":t("DESCRIPTION",n),r.add("DESCRIPTION");break;case"artist":t("ARTIST",n),r.add("ARTIST");break;case"album":t("ALBUM",n),r.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",n),r.add("ALBUM_ARTIST");break;case"genre":t("GENRE",n),r.add("GENRE");break;case"beatsPerMinute":t("BPM",n.toString()),r.add("BPM");break;case"comment":t("COMMENT",n),r.add("COMMENT");break;case"lyrics":t("LYRICS",n),r.add("LYRICS");break;case"date":t("DATE",n.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":{const o=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();t("PART_NUMBER",o),r.add("PART_NUMBER")}break;case"discNumber":{const o=i.discsTotal!==void 0?`${n}/${i.discsTotal}`:n.toString();t("DISC",o),r.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":case"creationTime":break;default:Be(a)}if(i.raw)for(const a in i.raw){const n=i.raw[a];n==null||r.has(a)||(typeof n=="string"||n instanceof Uint8Array)&&t(a,n)}e.length!==0&&(this.tagsElement={id:w.Tags,data:[{id:w.Tag,data:[{id:w.Targets,data:[{id:w.TargetTypeValue,data:50},{id:w.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,r=e.images??[];for(const a of r){let n=a.name;n===void 0&&(n=(a.kind==="coverFront"?"cover":a.kind==="coverBack"?"back":"image")+(sr(a.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:w.AttachedFile,data:[a.description!==void 0?{id:w.FileDescription,data:new Me(a.description)}:null,{id:w.FileName,data:new Me(n)},{id:w.FileMediaType,data:a.mimeType},{id:w.FileData,data:a.data},{id:w.FileUID,data:o}]})}for(const[a,n]of Object.entries(e.raw??{}))!(n instanceof rr)||!/^\d+$/.test(a)||r.find(c=>c.mimeType===n.mimeType&&ar(c.data,n.data))||t.push({id:w.AttachedFile,data:[n.description!==void 0?{id:w.FileDescription,data:new Me(n.description)}:null,{id:w.FileName,data:new Me(n.name??"")},{id:w.FileMediaType,data:n.mimeType??""},{id:w.FileData,data:n.data},{id:w.FileUID,data:BigInt(a)}]});t.length!==0&&(this.attachmentsElement={id:w.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:w.Segment,size:this.format._options.appendOnly?-1:Ei,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:w.Cues,data:[]}}get segmentDataOffset(){return m(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 nr({isWebM:this.format instanceof Mt,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const r=this.trackDatas.find(d=>d.track===e);if(r)return r;Xe(i,e.source._codec),m(i),m(i.decoderConfig),m(i.decoderConfig.codedWidth!==void 0),m(i.decoderConfig.codedHeight!==void 0);const a=i.decoderConfig.displayAspectWidth,n=i.decoderConfig.displayAspectHeight,o=a===void 0||n===void 0?null:Zi({num:a,den:n}),c={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:e.metadata.canBeTransparent||(t?!!t.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?c.codecPrivate=new Uint8Array(or(c.info.decoderConfig.codec)):e.source._codec==="av1"?c.codecPrivate=new Uint8Array(Gi(c.info.decoderConfig.codec)):e.source._codec==="prores"&&(c.codecPrivate=K.encode(i.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((d,u)=>d.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,i){const r=this.trackDatas.find(c=>c.track===e);if(r)return r;le(i,e.source._codec),m(i),m(i.decoderConfig);const a={...i.decoderConfig};let n=!1;if(e.source._codec==="aac"&&!a.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=ft(Qe.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 d=Ji[c.samplingFrequencyIndex],u=es[c.channelConfiguration];if(d===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");a.description=ts({objectType:c.objectType,outputSampleRate:d,outputNumberOfChannels:u}),n=!0}const o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:a,requiresAdtsStripping:n,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:a.description??null,closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const i=this.trackDatas.find(a=>a.track===e);if(i)return i;is(t),m(t),m(t.config);const r={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:K.encode(t.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,i){var a;const r=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i);(a=n.info).alphaMode??(a.alphaMode=!!t.sideData.alpha);let o=t.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}const c=t.type==="key";this.validateTimestamp(n.track,t.timestamp,c);let d=t.timestamp,u=t.duration;e.metadata.frameRate!==void 0&&(d=ii(d,e.metadata.frameRate),u=ii(u,e.metadata.frameRate));const l=n.info.alphaMode?t.sideData.alpha??null:null,f=this.createInternalChunk(o,d,u,t.type,l);e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,f),n.chunkQueue.push(f),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,i){var a;const r=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,i);let o=t.data;if(n.info.requiresAdtsStripping){const u=ft(Qe.tempFromBytes(o));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const l=u.crcCheck===null?rs:as;o=o.subarray(l)}const c=t.type==="key";this.validateTimestamp(n.track,t.timestamp,c),(a=n.info).codecDelay??(a.codecDelay=Math.max(-t.timestamp,0));const d=this.createInternalChunk(o,t.timestamp+n.info.codecDelay,t.duration,t.type);n.chunkQueue.push(d),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const a=this.getSubtitleTrackData(e,i);this.validateTimestamp(a.track,t.timestamp,!0);let n=t.text;const o=Math.round(t.timestamp*1e3);ht.lastIndex=0,n=n.replace(ht,l=>{const h=cr(l.slice(1,-1))-o;return`<${qi(h)}>`});const c=K.encode(n),d=`${t.settings??""}
50
- ${t.identifier??""}
51
- ${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",d.trim()?K.encode(d):null);a.chunkQueue.push(u),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&a.chunkQueue.length===0&&!a.closed)break e;a.chunkQueue.length>0&&a.chunkQueue[0].timestamp<i&&(t=a,i=a.chunkQueue[0].timestamp)}if(!t)break;const r=t.chunkQueue.shift();this.addBlock(t,r)}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 we(t.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(n===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;n>=2&&i.skipBits(1);const u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];ur(t.data,i.pos,i.pos+3,u)}createInternalChunk(e,t,i,r,a=null){return{data:e,type:r,timestamp:t,duration:i,additions:a}}addBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),r=this.trackDatas.every(o=>{if(e===o)return t.type==="key";const c=o.chunkQueue[0];return c?c.type==="key":o.closed});let a=!1;if(this.currentClusterStartMsTimestamp===null)a=!0;else{m(this.currentClusterMaxMsTimestamp!==null);const o=i-this.currentClusterStartMsTimestamp;a=r&&i>this.currentClusterMaxMsTimestamp&&o>=1e3*(this.format._options.minimumClusterDuration??1)||o>dn}if(a&&this.startNewCluster(i),i-this.currentClusterStartMsTimestamp<un){if(!this.warnedAboutTooNegativeTimestamp){const o=this.format instanceof Mt?"WebM":"Matroska";Y._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${o}.`),this.warnedAboutTooNegativeTimestamp=!0}return}this.currentClusterBlocks.push({trackData:e,chunk:t,msTimestamp:i,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+Math.round(1e3*t.duration)),e.lastWrittenMsTimestamp=i,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();const t=Math.max(0,e);this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t}writeCurrentCluster(){m(this.currentClusterStartMsTimestamp!==null);const e=this.currentClusterStartMsTimestamp,t=new Map,i=new Map;for(const u of this.currentClusterBlocks)u.chunk.type==="key"&&!t.has(u.trackData)&&t.set(u.trackData,u),i.set(u.trackData,u);const r=new Map;for(const u of this.currentClusterBlocks)r.set(u,this.createBlockElement(u,e,i.get(u.trackData)===u));const a={id:w.Cluster,size:this.format._options.appendOnly?-1:ln,data:[{id:w.Timestamp,data:e},...r.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(a),this.currentClusterBlocks=[],this.format._options.onCluster){const{data:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onCluster(u,l,e/1e3)}const n=this.ebmlWriter.offsets.get(a)-this.segmentDataOffset,o=this.ebmlWriter.dataOffsets.get(a),c=new Map;for(const u of t.values())c.has(u.msTimestamp)||c.set(u.msTimestamp,[]),c.get(u.msTimestamp).push(u);const d=[...c.entries()].sort((u,l)=>u[0]-l[0]);for(const[u,l]of d)m(this.cues),this.cues.data.push({id:w.CuePoint,data:[{id:w.CueTime,data:Math.max(0,u)},...l.map(f=>{const h=this.ebmlWriter.offsets.get(r.get(f));return{id:w.CueTrackPositions,data:[{id:w.CueTrack,data:f.trackData.track.id},{id:w.CueClusterPosition,data:n},{id:w.CueRelativePosition,data:h-o}]}})]})}createBlockElement(e,t,i){const{trackData:r,chunk:a,msTimestamp:n}=e,o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|r.track.id),c.setInt16(1,n-t,!1);const d=Math.round(1e3*a.duration);return!!a.additions||r.type==="subtitle"||i&&d>0?{id:w.BlockGroup,data:[{id:w.Block,data:[o,a.data]},a.type==="delta"?{id:w.ReferenceBlock,data:new dr(e.previousMsTimestamp-n)}:null,a.additions?{id:w.BlockAdditions,data:[{id:w.BlockMore,data:[{id:w.BlockAddID,data:1},{id:w.BlockAdditional,data:a.additions}]}]}:null,d>0?{id:w.BlockDuration,data:d}:null]}:(c.setUint8(3,+(a.type==="key")<<7),{id:w.SimpleBlock,data:[o,a.data]})}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(r=>r.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.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),m(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,Ei);const i=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new ei(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),m(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}/*!
52
- * Copyright (c) 2026-present, Vanilagy and contributors
53
- *
54
- * This Source Code Form is subject to the terms of the Mozilla Public
55
- * License, v. 2.0. If a copy of the MPL was not distributed with this
56
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
57
- */class hn{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.crc=0}writeAndUpdateCrc(e){for(const t of e){this.crc^=t;for(let i=0;i<8;i++)this.crc=this.crc>>>1^(this.crc&1?40961:0)}this.writer.write(e)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writeAndUpdateCrc(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos();this.crc=0;const i=255,r=224|e.mpegVersionId<<3|e.layer<<1;let a;e.mpegVersionId&2?a=e.mpegVersionId&1?0:1:a=1;const n=0,o=os(e.mpegVersionId,e.channel),c=e.encoderDelayInSamples===null?155:o+8+4+4+100+36;let d=-1;const u=a*16*4+e.layer*16;for(let p=0;p<16;p++){const _=ai[u+p];if(ri(a,e.layer,1e3*_,e.sampleRate,n)>=c){d=p;break}}if(d===-1)throw new Error("No suitable bitrate found.");const l=d<<4|e.frequencyIndex<<2|n<<1,f=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=i,this.helper[1]=r,this.helper[2]=l,this.helper[3]=f,this.writeAndUpdateCrc(this.helper.subarray(0,4)),this.writeAndUpdateCrc(new Uint8Array(o-4)),this.writeU32(e.isCbr?cs:us);let h=0;if(e.frameCount!==null&&(h|=_t.FrameCount),e.fileSize!==null&&(h|=_t.FileSize),e.toc!==null&&(h|=_t.Toc),this.writeU32(h),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writeAndUpdateCrc(e.toc??new Uint8Array(100)),e.encoderDelayInSamples!==null){const p=new Uint8Array(36);p.set([76,65,77,69]),p[21]=e.encoderDelayInSamples>>4,p[22]=(e.encoderDelayInSamples&15)<<4|Wt>>8,p[23]=Wt&255,this.writeAndUpdateCrc(p.subarray(0,34)),new DataView(p.buffer).setUint16(34,this.crc),this.writer.write(p.subarray(34))}const y=ai[u+d],T=ri(a,e.layer,1e3*y,e.sampleRate,n);this.writer.write(new Uint8Array(t+T-this.writer.getPos()))}}/*!
58
- * Copyright (c) 2026-present, Vanilagy and contributors
59
- *
60
- * This Source Code Form is subject to the terms of the Mozilla Public
61
- * License, v. 2.0. If a copy of the MPL was not distributed with this
62
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
63
- */class pn extends Se{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.frameBitrate=null,this.hasVariableBitrate=!1,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writeXingHeader=t._options.xingHeader!==!1}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new hn(this.writer),Ke(this.output._metadataTags)||new qt(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{if(this.writeXingHeader){const r=ce(t.data);if(r.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=r.getUint32(0,!1),n=ni(a,null).header;if(!n)throw new Error("Invalid MP3 header in sample.");if(!this.xingFrameData){const o=os(n.mpegVersionId,n.channel);if(r.byteLength>=o+4){const d=r.getUint32(o,!1);if(d===us||d===cs)return}let c=t.timestamp<0?Math.round(-t.timestamp*n.sampleRate)-Wt:null;c!==null&&(c<0||c>4095)&&(c=null),this.xingFrameData={mpegVersionId:n.mpegVersionId,layer:n.layer,frequencyIndex:n.frequencyIndex,sampleRate:n.sampleRate,channel:n.channel,modeExtension:n.modeExtension,copyright:n.copyright,original:n.original,emphasis:n.emphasis,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:c},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.frameBitrate===null?this.frameBitrate=n.bitrate:n.bitrate!==this.frameBitrate&&(this.hasVariableBitrate=!0)}this.validateTimestamp(e,t.timestamp,t.type==="key"),this.writeXingHeader&&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(){const e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");const i=this.output.tracks[0];m(i==null?void 0:i.isAudioTrack());const r=i.metadata.primingPacket;if(r){const a=ce(r.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");const n=a.getUint32(0,!1),o=ni(n,null).header;if(!o)throw new Error("Invalid MP3 header in priming packet.");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,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else if(i.metadata.decoderConfig){const{sampleRate:a,numberOfChannels:n}=i.metadata.decoderConfig,o=[3,2,0];let c=null,d=-1;for(let u=0;u<o.length;u++)if(d=lr.indexOf(a<<u),d!==-1){c=o[u];break}if(c===null)throw new Error(`${a} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:c,layer:1,frequencyIndex:d,sampleRate:a,channel:n===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else throw new Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}if(this.writeXingHeader){m(this.xingFrameData),m(this.xingFramePos!==null);const r=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){const a=new Uint8Array(100);for(let n=0;n<100;n++){const o=Math.floor(this.framePositions.length*(n/100)),c=this.framePositions[o]-this.xingFramePos;a[n]=256*(c/r)}this.xingFrameData.toc=a}if(this.xingFrameData.isCbr=this.frameBitrate!==null&&!this.hasVariableBitrate,this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:a,start:n}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(a,n)}}e()}}/*!
64
- * Copyright (c) 2026-present, Vanilagy and contributors
65
- *
66
- * This Source Code Form is subject to the terms of the Mozilla Public
67
- * License, v. 2.0. If a copy of the MPL was not distributed with this
68
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
69
- */const gn=8192;class wn extends Se{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=Ee(),this.pageBytes=new Uint8Array(mr),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);for(const t of this.output.tracks)m(t.isAudioTrack()),t.metadata.decoderConfig&&this.getTrackData(t,{decoderConfig:t.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,fr({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(n=>n.track===e);if(i)return i;let r;do r=Math.floor(2**32*Math.random());while(this.trackDatas.some(n=>n.serialNumber===r));m(e.source._codec==="vorbis"||e.source._codec==="opus"),le(t,e.source._codec),m(t),m(t.decoderConfig);const a={track:e,serialNumber:r,internalSampleRate:e.source._codec==="opus"?ns:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startOffsetInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(a,t),this.trackDatas.push(a),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}queueHeaderPackets(e,t){if(m(t.decoderConfig),e.track.source._codec==="vorbis"){m(t.decoderConfig.description);const i=oe(t.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let r=1;const a=()=>{let T=0;for(;;){const p=i[r++];if(p===void 0)throw new TypeError("Vorbis decoder description is too short.");if(T+=p,p<255)return T}},n=a(),o=a();if(i.length-r<=0)throw new TypeError("Vorbis decoder description is too short.");const d=i.subarray(r,r+=n);r+=o;const u=i.subarray(r),l=new Uint8Array(7);l[0]=3,l[1]=118,l[2]=111,l[3]=114,l[4]=98,l[5]=105,l[6]=115;const f=Rt(l,this.output._metadataTags,!0);e.packetQueue.push({data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:u,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});const y=ce(d).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(y&15),1<<(y>>4)],modeBlockflags:hr(u).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const i=oe(t.decoderConfig.description),r=new Uint8Array(8),a=ce(r);a.setUint32(0,1332770163,!1),a.setUint32(4,1415669619,!1);const n=Rt(r,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:ji(i).preSkip}}}async addEncodedAudioPacket(e,t,i){var a;const r=await this.mutex.acquire();try{const n=this.getTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const{durationInSamples:o,vorbisBlockSize:c}=pr(t.data,n.codecInfo,n.vorbisLastBlocksize);if(n.startOffsetInSamples===null){const f=Math.round(t.timestamp*n.internalSampleRate),h=((a=n.codecInfo.opusInfo)==null?void 0:a.preSkip)??0,y=n.codecInfo.codec==="vorbis"?-o:-h,T=Math.max(f,y);n.startOffsetInSamples=T-y,n.currentTimestampInSamples=T+h}const d=n.currentTimestampInSamples;n.currentTimestampInSamples+=o,n.vorbisLastBlocksize=c;const u=t.duration>0?lt(Math.round(t.duration*n.internalSampleRate),0,o):o,l=n.startOffsetInSamples>0&&n.audioPacketCount===1;n.audioPacketCount++,n.packetQueue.push({data:t.data,timestampInSamples:d,durationInSamples:o,trimmedDurationInSamples:u,forcePageFlush:l}),await this.interleavePages()}finally{r()}}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 n of this.trackDatas){if(!e&&n.packetQueue.length<=1&&!n.closed)break e;n.packetQueue.length>0&&n.packetQueue[0].timestampInSamples<i&&(t=n,i=n.packetQueue[0].timestampInSamples)}if(!t)break;const r=t.packetQueue.shift(),a=t.packetQueue.length===0;this.writePacket(t,r,a)}e||await this.writer.flush()}writePacket(e,t,i){const r=t.timestampInSamples+(i?t.trimmedDurationInSamples:t.durationInSamples);if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=t.timestampInSamples),this.format._options.maximumPageDuration!==void 0){const d=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&r-e.currentPageStartTimestampInSamples>d&&this.writePage(e,!1)}let a=t.data.length,n=0,o=0;for(;;){e.currentLacingValues.length===0&&n>0&&(e.currentPageStartsWithFreshPacket=!1);const d=Math.min(255,a);e.currentLacingValues.push(d),e.currentPageSize++,o+=d;const u=a<255;if(e.currentLacingValues.length===255){const l=t.data.subarray(n,o);if(n=o,e.currentPageData.push(l),e.currentPageSize+=l.length,u&&(e.currentGranulePosition=r),this.writePage(e,i&&u),u)return}if(u)break;a-=255}const c=t.data.subarray(n);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=r,(e.currentPageSize>=gn||t.forcePageFlush)&&this.writePage(e,i)}writePage(e,t){this.pageView.setUint32(0,gr,!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 r=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;wr(this.pageView,6,r),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 a=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,a),a+=c.length;const n=this.pageBytes.subarray(0,a),o=Tr(n);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(n),this.format._options.onPage){const{data:c,start:d}=this.writer.stopTrackingWrites();this.format._options.onPage(c,d,e.track.source)}}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(r=>r.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()}}/*!
70
- * Copyright (c) 2026-present, Vanilagy and contributors
71
- *
72
- * This Source Code Form is subject to the terms of the Mozilla Public
73
- * License, v. 2.0. If a copy of the MPL was not distributed with this
74
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
75
- */const Tn=0,bs=4096,vi=256,yn=224,Ai=192,Mi=new Uint8Array([9,240]),Ii=new Uint8Array([70,1]);class bn extends Se{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(oi),this.packetView=ce(this.packetBuffer),this.allTracksKnown=Ee(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t,this.timestampOffset=t._options.timestampOffset??0}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,yr(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const i=this.trackDatas.find(d=>d.track===e);if(i)return i;Xe(t,e.source._codec),m(t==null?void 0:t.decoderConfig);const r=e.source._codec;m(r==="avc"||r==="hevc");const a=r==="avc"?27:36,n=vi+this.trackDatas.length,o=yn+this.videoTrackIndex++,c={track:e,pid:n,streamType:a,streamId:o,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}getAudioTrackData(e,t){const i=this.trackDatas.find(d=>d.track===e);if(i)return i;le(t,e.source._codec),m(t==null?void 0:t.decoderConfig);const r=e.source._codec;m(r==="aac"||r==="mp3"||r==="ac3"||r==="eac3"||r==="dts");let a,n;switch(r){case"aac":a=15,n=Ai+this.audioTrackIndex++;break;case"mp3":a=3,n=Ai+this.audioTrackIndex++;break;case"ac3":a=129,n=189;break;case"eac3":a=135,n=189;break;case"dts":a=130,n=189;break}const o=vi+this.trackDatas.length,c={track:e,pid:o,streamType:a,streamId:n,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 r=await this.mutex.acquire();try{const a=this.getVideoTrackData(e,i);this.validateTimestamp(a.track,t.timestamp,t.type==="key");const n=this.prepareVideoPacket(a,t,i);t.type==="key"&&await this.flushTimestampQueue(a),a.timestampProcessingQueue.push({data:n,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const a=this.getAudioTrackData(e,i);this.validateTimestamp(a.track,t.timestamp,t.type==="key");const n=this.prepareAudioPacket(a,t,i);t.type==="key"&&await this.flushTimestampQueue(a),a.timestampProcessingQueue.push({data:n,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{r()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,i){var a;const r=e.track.source._codec;if(e.inputIsAnnexB===null){const n=(a=i==null?void 0:i.decoderConfig)==null?void 0:a.description;if(e.inputIsAnnexB=!n,!e.inputIsAnnexB){const o=oe(n);r==="avc"?e.avcDecoderConfig=br(o):e.hevcDecoderConfig=_r(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,r):this.prepareLengthPrefixedVideoPacket(e,t,r)}prepareAnnexBVideoPacket(e,t){const i=[];for(const a of ss(e)){const n=e.subarray(a.offset,a.offset+a.length);(t==="avc"?ci(n[0])===ui.AUD:di(n[0])===Ne.AUD_NUT)||i.push(n)}const r=t==="avc"?Mi:Ii;return i.unshift(r),li(i)}prepareLengthPrefixedVideoPacket(e,t,i){const r=t.data,a=i==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,n=[];for(const c of kr(r,a)){const d=r.subarray(c.offset,c.offset+c.length);(i==="avc"?ci(d[0])===ui.AUD:di(d[0])===Ne.AUD_NUT)||n.push(d)}if(t.type==="key")if(i==="avc"){const c=e.avcDecoderConfig;for(const d of c.pictureParameterSets)n.unshift(d);for(const d of c.sequenceParameterSets)n.unshift(d)}else{const c=e.hevcDecoderConfig;for(const d of c.arrays)if(d.nalUnitType===Ne.PPS_NUT)for(const u of d.nalUnits)n.unshift(u);for(const d of c.arrays)if(d.nalUnitType===Ne.SPS_NUT)for(const u of d.nalUnits)n.unshift(u);for(const d of c.arrays)if(d.nalUnitType===Ne.VPS_NUT)for(const u of d.nalUnits)n.unshift(u)}const o=i==="avc"?Mi:Ii;return n.unshift(o),li(n)}prepareAudioPacket(e,t,i){var c;const r=e.track.source._codec;if(r==="mp3"||r==="ac3"||r==="eac3"||r==="dts")return t.data;if(e.inputIsAdts===null){const d=(c=i==null?void 0:i.decoderConfig)==null?void 0:c.description;if(e.inputIsAdts=!d,!e.inputIsAdts){const u=Di(oe(d)),l=Ni(u);e.adtsHeader=l.header,e.adtsHeaderBitstream=l.bitstream}}if(e.inputIsAdts)return t.data;m(e.adtsHeader),m(e.adtsHeaderBitstream);const a=e.adtsHeader,n=t.data.byteLength+a.byteLength;Hi(e.adtsHeaderBitstream,n);const o=new Uint8Array(n);return o.set(a,0),o.set(t.data,a.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(r=>r.presentationTimestamp).sort((r,a)=>r-a);for(let r=0;r<e.timestampProcessingQueue.length;r++){const a=e.timestampProcessingQueue[r];a.decodeTimestamp=i[r],e.packetQueue.push(a)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length===0&&!a.closed)break e;a.packetQueue.length>0&&a.packetQueue[0].presentationTimestamp<i&&(t=a,i=a.packetQueue[0].presentationTimestamp)}if(!t)break;const r=t.packetQueue.shift();this.writePesPacket(t,r)}e||await this.writer.flush()}writeTables(){m(!this.tablesWritten),this.writePsiSection(Tn,Ie),this.writePsiSection(bs,kn(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let i=0,r=!0;for(;i<t.length;){const n=184-(r?1:0),o=t.length-i,c=Math.min(n,o);let d;r?(d=this.payloadBuffer.subarray(0,1+c),d[0]=0,d.set(t.subarray(i,i+c),1)):d=t.subarray(i,i+c),this.writeTsPacket(e,r,null,d),i+=c,r=!1}}writePesPacket(e,t){const i=e.track.type==="video",r=i?10:5,a=new Uint8Array(9+r),n=ce(a),o=new we(a.subarray(9));Sr(n,0,1,!1),a[3]=e.streamId;const c=e.track.type==="video"?0:Math.min(8+t.data.length,65535);n.setUint16(4,c,!1),n.setUint8(6,132),n.setUint8(7,i?192:128),n.setUint8(8,r);const d=zt(t.presentationTimestamp+this.timestampOffset);if(o.pos=0,o.writeBits(4,i?3:2),o.writeBits(3,Math.floor(d/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(d/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,d%2**15),o.writeBits(1,1),i){m(t.decodeTimestamp!==null);const h=zt(t.decodeTimestamp+this.timestampOffset);o.writeBits(4,1),o.writeBits(3,Math.floor(h/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(h/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,h%2**15),o.writeBits(1,1)}const u=a.length+t.data.length;let l=0,f=!0;for(;l<u;){const h=f,y=u-l,T=f&&t.isKeyframe,p=f&&!e.firstPacketWritten,_=Math.max(0,184-y);let b;T||p?b=Math.max(2,_):b=_;let S=null;if(b>0){const W=this.adaptationFieldBuffer;b===1?W[0]=0:(W[0]=b-1,W[1]=Number(p)<<7|Number(T)<<6,W.fill(255,2,b)),S=W.subarray(0,b)}const E=Math.min(184-b,y),C=this.payloadBuffer.subarray(0,E);let k=0;if(l<a.length){const W=Math.min(a.length-l,E);C.set(a.subarray(l,l+W),0),k=W}const U=Math.max(0,l-a.length),q=U+(E-k);k<E&&C.set(t.data.subarray(U,q),k),this.writeTsPacket(e.pid,h,S,C),l+=E,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,i,r){const a=this.continuityCounters.get(e)??0,n=r.length>0,o=i?n?3:2:n?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|a&15,n&&this.continuityCounters.set(e,a+1&15);let c=4;i&&(this.packetBuffer.set(i,c),c+=i.length),this.packetBuffer.set(r,c),c+=r.length,c<oi&&this.packetBuffer.fill(255,c);const d=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),d)}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(r=>r.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 _n=79764919,_s=new Uint32Array(256);for(let s=0;s<256;s++){let e=s<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^_n:e<<1;_s[s]=e>>>0&4294967295}const ks=s=>{let e=4294967295;for(let t=0;t<s.length;t++){const i=s[t];e=(e<<8^_s[e>>>24^i])>>>0}return e},Ie=new Uint8Array(16);{const s=ce(Ie);Ie[0]=0,s.setUint16(1,45069,!1),s.setUint16(3,1,!1),Ie[5]=193,Ie[6]=0,Ie[7]=0,s.setUint16(8,1,!1),s.setUint16(10,57344|bs&8191,!1),s.setUint32(12,ks(Ie.subarray(0,12)),!1)}const kn=s=>{let e=0;for(const c of s)e+=5,c.streamType===129?e+=et.length:c.streamType===135&&(e+=tt.length);const t=9+e+4,i=new Uint8Array(3+t-4),r=ce(i);i[0]=2,r.setUint16(1,45056|t&4095,!1),r.setUint16(3,1,!1),i[5]=193,i[6]=0,i[7]=0,r.setUint16(8,65535,!1),r.setUint16(10,61440,!1);let a=12;for(const c of s)i[a++]=c.streamType,r.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(r.setUint16(a,61440|et.length,!1),a+=2,i.set(et,a),a+=et.length):c.streamType===135?(r.setUint16(a,61440|tt.length,!1),a+=2,i.set(tt,a),a+=tt.length):(r.setUint16(a,61440,!1),a+=2);const n=ks(i),o=new Uint8Array(i.length+4);return o.set(i,0),ce(o).setUint32(i.length,n,!1),o};/*!
76
- * Copyright (c) 2026-present, Vanilagy and contributors
77
- *
78
- * This Source Code Form is subject to the terms of the Mozilla Public
79
- * License, v. 2.0. If a copy of the MPL was not distributed with this
80
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
81
- */class Sn{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(K.encode(e))}}/*!
82
- * Copyright (c) 2026-present, Vanilagy and contributors
83
- *
84
- * This Source Code Form is subject to the terms of the Mozilla Public
85
- * License, v. 2.0. If a copy of the MPL was not distributed with this
86
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
87
- */class Cn extends Se{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 Sn(this.writer);const t=this.output.tracks[0];m(t==null?void 0:t.isAudioTrack()),t.metadata.decoderConfig&&(le({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.writeHeader(t,t.metadata.decoderConfig),this.sampleRate=t.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{if(this.headerWritten||(le(i,e.source._codec),m(i),m(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let i;const r=e.source._codec,a=ve(r);a.dataType==="ulaw"?i=it.MULAW:a.dataType==="alaw"?i=it.ALAW:a.dataType==="float"?i=it.IEEE_FLOAT:i=it.PCM;const n=t.numberOfChannels,o=t.sampleRate,c=a.sampleSize*n;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(n),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*a.sampleSize),!Ke(this.output._metadataTags)){const d=this.format._options.metadataFormat??"info";d==="info"?this.writeInfoChunk(this.output._metadataTags):d==="id3"?this.writeId3Chunk(this.output._metadataTags):Be(d)}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:d,start:u}=this.writer.stopTrackingWrites();this.format._options.onHeader(d,u)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const i=new Set,r=(o,c)=>{if(!Cr(c)){Y._warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const d=c.length+1,u=new Uint8Array(d);for(let l=0;l<c.length;l++)u[l]=c.charCodeAt(l);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(d),this.writer.write(u),d&1&&this.writer.write(new Uint8Array(1)),i.add(o)};for(const{key:o,value:c}of gt(e))switch(o){case"title":r("INAM",c),i.add("INAM");break;case"artist":r("IART",c),i.add("IART");break;case"album":r("IPRD",c),i.add("IPRD");break;case"trackNumber":{const d=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();r("ITRK",d),i.add("ITRK")}break;case"genre":r("IGNR",c),i.add("IGNR");break;case"date":r("ICRD",c.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":r("ICMT",c),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":case"creationTime":break;case"raw":break;default:Be(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"&&r(o,c)}const a=this.writer.getPos(),n=a-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(n),this.writer.seek(a),n&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const r=new qt(this.writer).writeId3V2Tag(e),a=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(r),this.writer.seek(a),r&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire();if(!this.headerWritten)throw new Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");const t=this.writer.getPos();this.isRf64?(m(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),m(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),m(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(m(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),m(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}/*!
88
- * Copyright (c) 2026-present, Vanilagy and contributors
89
- *
90
- * This Source Code Form is subject to the terms of the Mozilla Public
91
- * License, v. 2.0. If a copy of the MPL was not distributed with this
92
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
93
- */const Fi=s=>s==="opus"?"Opus":s;class xn extends Se{constructor(e,t){if(!(e._target instanceof Pe))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.firstPacketTimestamp=null,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.mediaTimestampBase=t._options.mediaTimestampBase??10,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(p=>p.metadata.isRelativeToUnixEpoch),i=this.output.tracks.some(p=>!p.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 r=new Map,a=[];let n=!1,o=!1,c=!1;for(const p of this.output.tracks){p.type==="video"&&(n=!0);const _=new Map;for(const b of this.output.tracks){if(p===b||!p.canBePairedWith(b))continue;if(p.type===b.type){o||(Y._warn(`Illegal pairing of two ${p.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(p.isVideoTrack()&&p.metadata.hasOnlyKeyPackets||b.isVideoTrack()&&b.metadata.hasOnlyKeyPackets){c||(Y._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 S=_.get(b.source._codec);S||_.set(b.source._codec,S=[]),S.push(b)}for(const[,b]of _){const S=b.map(k=>k.id).join("-");a.find(k=>k.key===S)||a.push({name:b[0].type+"-"+(a.length+1),key:S,tracks:b,needsEmit:!1,firstNoUri:!1});let C=r.get(p);C||r.set(p,C=[]),C.push(S)}}const d=n?"video":"audio",u=[],l=[],f=[];for(const p of this.output.tracks){const _=r.get(p);if(_){if(m(_.length>0),p.type!==d)continue;for(const b of _){const S=a.find(E=>E.key===b);if(m(S),_.length===1&&S.tracks.length===1){const E=r.get(S.tracks[0]);if(m(E!==void 0),E.length===1){const C=a.find(k=>k.key===E[0]);if(C.tracks.length===1){m(C.tracks[0]===p),u.push({tracks:[p,S.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[p],linkedGroup:S}),S.needsEmit=!0}}else p.type==="video"?l.push(p):p.type==="audio"&&f.push(p)}const h=({metadata:p})=>{var b,S,E;let _="";return _+=`${p.languageCode??Ot}-`,_+=`${p.name??""}-`,_+=`${((b=p.disposition)==null?void 0:b.default)??!0}-`,_+=`${((S=p.disposition)==null?void 0:S.primary)??!1}-`,_+=`${((E=p.disposition)==null?void 0:E.forced)??!1}-`,_};if(l.length>0)if(new Set(l.map(h)).size>1){const _={key:l.map(b=>b.id).join("-"),name:"video-"+(a.length+1),tracks:l,needsEmit:!0,firstNoUri:!0};a.push(_),u.push({tracks:[l[0]],linkedGroup:_})}else for(const _ of l)u.push({tracks:[_],linkedGroup:null});if(f.length>0)if(new Set(f.map(h)).size>1){const _={key:f.map(b=>b.id).join("-"),name:"audio-"+(a.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};a.push(_),u.push({tracks:[f[0]],linkedGroup:_})}else for(const _ of f)u.push({tracks:[_],linkedGroup:null});const y=p=>{const _=[];let b=0,S=0,E=!1,C=null,k=-1/0;for(const U of p)U.isVideoTrack()?(b++,E||(E=(U.metadata.rotation??0)!==0||!!U.metadata.flip||!!U.metadata.transformationMatrix)):U.isAudioTrack()&&S++,_.push(U.source._codec);for(const U of Fe(this.format._options.segmentFormat)){const q=U.getSupportedCodecs(),W=U.getSupportedTrackCounts();if(_.some(A=>!q.includes(A))||b<W.video.min||b>W.video.max||S<W.audio.min||S>W.audio.max)continue;let L=0;E&&U.supportsVideoTransformationMetadata&&L++,L>k&&(C=U,k=L)}return m(C),C},T=async p=>{if(p.some(C=>this.playlists.some(k=>k.tracks.includes(C))))throw new Error("Internal error: track is already registered in a playlist.");const _=y(p),b=this.playlists.length+1,S=await this.getPlaylistPath({n:b,tracks:p,segmentFormat:_});Pn(S);const E={id:this.playlists.length+1,path:S,tracks:p,segmentFormat:_,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Ht};return this.playlists.push(E),E};for(const p of a)if(p.needsEmit)for(let _=0;_<p.tracks.length;_++){const b=p.tracks[_];let S=this.playlists.find(E=>E.tracks[0].id===b.id);S??(S=await T([b])),this.playlistDeclarations.push({playlist:S,groupId:p.name,noUri:p.firstNoUri&&_===0,references:[]})}for(const p of u){let _=this.playlists.find(b=>b.tracks[0].id===p.tracks[0].id);_??(_=await T(p.tracks)),this.playlistDeclarations.push({playlist:_,groupId:null,noUri:!1,references:p.linkedGroup?this.playlistDeclarations.filter(b=>b.groupId===p.linkedGroup.name):[]})}for(const p of this.output.tracks)p.isVideoTrack()&&p.metadata.decoderConfig?this.getVideoTrackData(p,p.metadata.primingPacket??null,{decoderConfig:p.metadata.decoderConfig}):p.isAudioTrack()&&p.metadata.decoderConfig&&this.getAudioTrackData(p,p.metadata.primingPacket??null,{decoderConfig:p.metadata.decoderConfig});e()}async getMimeType(){return mt}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(a=>a.track===e);t&&(t.closed=!0);const i=this.playlists.find(a=>a.tracks.includes(e));m(i);const r=await i.mutex.acquire();try{await this.advancePlaylist(i)}finally{r()}}getVideoTrackData(e,t,i){let r=this.trackDatas.find(n=>n.track===e);if(r)return r;Xe(i,e.source._codec),m(i),m(i==null?void 0:i.decoderConfig);const a=this.playlists.filter(n=>n.tracks.includes(e));return m(a.length===1),r={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"video",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(r),r}getAudioTrackData(e,t,i){let r=this.trackDatas.find(n=>n.track===e);if(r)return r;le(i,e.source._codec),m(i),m(i==null?void 0:i.decoderConfig);const a=this.playlists.filter(n=>n.tracks.includes(e));return m(a.length===1),r={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"audio",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(r),r}async addEncodedVideoPacket(e,t,i){const r=this.getVideoTrackData(e,t,i),a=r.playlist,n=await a.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),r.packets.push(t),this.firstPacketTimestamp??(this.firstPacketTimestamp=t.timestamp),a.currentSegmentStartTimestamp===null?a.currentSegmentStartTimestamp=t.timestamp:a.currentSegmentStartTimestampIsFixed||(a.currentSegmentStartTimestamp=Math.min(a.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(a)}finally{n()}}async addEncodedAudioPacket(e,t,i){const r=this.getAudioTrackData(e,t,i),a=r.playlist,n=await a.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),r.packets.push(t),this.firstPacketTimestamp??(this.firstPacketTimestamp=t.timestamp),a.currentSegmentStartTimestamp===null?a.currentSegmentStartTimestamp=t.timestamp:a.currentSegmentStartTimestampIsFixed||(a.currentSegmentStartTimestamp=Math.min(a.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(a)}finally{n()}}async addSubtitleCue(e,t,i){throw new Error("Unreachable.")}async advancePlaylist(e){var a,n,o,c,d,u;if(m(!e.done),!this.allTracksAreKnown(e))return;const t=this.trackDatas.filter(l=>e.tracks.includes(l.track));if(e.currentSegmentStartTimestamp===null){t.every(l=>l.closed)&&await this.onPlaylistDone(e);return}const i=t.find(l=>l.info.type==="video"),r=t.find(l=>l.info.type==="audio");for(;;){const l=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let f=0,h=0;if(i&&(!i.closed||i.packets.length>0)){const A=i.packets.every(F=>F.timestamp<l);let M=null,P=null;if(A){if(!i.closed)return}else for(let F=0;F<i.packets.length;F++){const z=i.packets[F];if(M!==null&&z.timestamp>l)break;F>0&&z.type==="key"&&(M=z,P=F)}if(P!==null){if(f=P,r){const F=r.packets.findIndex(z=>z.timestamp>=M.timestamp);if(F!==-1)h=F;else if(r.closed)h=r.packets.length;else return}}else{if(!i.closed)return;f=i.packets.length;const F=xr(i.packets,R=>R.timestamp),z=i.packets[F];if(m(z),r)if(z.timestamp<l){const R=r.packets.findIndex(Z=>Z.timestamp>=l);if(R!==-1)h=R;else if(r.closed)h=r.packets.length;else return}else{const R=r.packets.findIndex(Z=>Z.timestamp>z.timestamp);if(R!==-1)h=R;else if(r.closed)h=r.packets.length;else return}}}else if(r&&(!r.closed||r.packets.length>0))if(r.packets.every(M=>M.timestamp<l))if(r.closed)h=r.packets.length;else return;else{const M=Ki(r.packets,P=>P.timestamp<=l);h=Math.max(M,1)}if(f===0&&h===0){t.every(M=>M.closed)&&await this.onPlaylistDone(e);return}let y=null,T,p;m(this.output._target instanceof Pe);const _=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const A={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:ot(e)};T=await this.getSegmentPath(A),Bi(T),p=be(be(_.rootPath,e.path),T);const M=await this.output._getTarget({path:p,isRoot:!1,mimeType:e.segmentFormat.mimeType});let P=null;if(e.segmentFormat._isFragmentedIsobmff()){P={output:new pt({format:e.segmentFormat,target:M}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},M.on("write",({end:R})=>{P.currentFileSize=Math.max(P.currentFileSize,R)});const F=P.output._muxer;F.minimumFragmentDuration=1/0;const z=F.formatOptions.onMoof;F.formatOptions.onMoof=(R,Z,Ce)=>{P.firstMoofPosition=Z,z==null||z(R,Z,Ce),F.formatOptions.onMoof=z},i&&(P.videoSource=new Ut(i.track.source._codec),P.output.addVideoTrack(P.videoSource,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),r&&(P.audioSource=new Vt(r.track.source._codec),P.output.addAudioTrack(P.audioSource,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),await P.output.start()}else M._start();e.singleFile={target:M,path:T,nextOffset:0,info:A,fragmentedIsobmffOutput:P}}else T=e.singleFile.path,p=be(be(_.rootPath,e.path),T);else y={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:ot(e)},T=await this.getSegmentPath(y),Bi(T),p=be(be(_.rootPath,e.path),T),e.nextSegmentId++;let b=0,S=null,E=-1/0,C=null,k=null,U=null;try{if((a=e.singleFile)!=null&&a.fragmentedIsobmffOutput)C=e.singleFile.fragmentedIsobmffOutput.output,k=e.singleFile.fragmentedIsobmffOutput.videoSource,U=e.singleFile.fragmentedIsobmffOutput.audioSource;else{if(C=new pt({format:e.segmentFormat,target:new Pe(p,async A=>{const M={...A,isRoot:!1};if(A.isRoot)if(e.singleFile){const P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:F})=>b=Math.max(b,F)),P}else{const P=await this.output._getTarget(M);return S=P,P.on("write",({end:F})=>b=Math.max(b,F)),P}return this.output._getTarget(M)}),initTarget:async()=>{if(e.initSegment)return new ys;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const A=e.singleFile.target.slice(e.singleFile.nextOffset);return A.on("write",({end:M})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,M)}),A.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),A}else{const A=ot(e),M=await this.getInitPath(A);En(M),e.initSegment={path:M,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const P=be(be(_.rootPath,e.path),M),F=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return F.on("write",({end:z})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,z)}),F.on("finalized",()=>{var z,R;(R=(z=this.format._options).onInit)==null||R.call(z,F,A)}),F}}}),i&&(k=new Ut(i.track.source._codec),C.addVideoTrack(k,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),r&&(U=new Vt(r.track.source._codec),C.addAudioTrack(U,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0}),!e.segmentFormat.supportsTimestampedMediaData&&h>0)){const A=this.toMediaTimestamp(r.packets[0].timestamp),M=zt(A),P=new Uint8Array(st.length+1+8);P.set(K.encode(st),0);const F=ce(P);F.setUint32(st.length+1,Math.floor(M/2**32)),F.setUint32(st.length+5,M%2**32),C.setMetadataTags({raw:{PRIV:P}})}await C.start()}if(i){m(k);const A={decoderConfig:i.info.decoderConfig};for(let M=0;M<f;M++){const P=i.packets[M],F=P.clone({timestamp:this.toMediaTimestamp(P.timestamp)});await k.add(F,A),E=Math.max(E,P.timestamp+P.duration)}}if(r){m(U);const A={decoderConfig:r.info.decoderConfig};for(let M=0;M<h;M++){const P=r.packets[M],F=P.clone({timestamp:this.toMediaTimestamp(P.timestamp)});await U.add(F,A),E=Math.max(E,P.timestamp+P.duration)}}(n=e.singleFile)!=null&&n.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),b=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await C.finalize()}catch(A){throw await(C==null?void 0:C.cancel()),A}y&&(m(S),(c=(o=this.format._options).onSegment)==null||c.call(o,S,y)),f>0&&(m(i),i.packets.splice(0,f)),h>0&&(m(r),r.packets.splice(0,h));let q=1/0;i&&i.packets.length>0&&(q=i.packets[0].timestamp),r&&r.packets.length>0&&(q=Math.min(q,r.packets[0].timestamp));const W=q<1/0?q:E;m(Number.isFinite(W));const L=W-e.currentSegmentStartTimestamp;if(m(L>=0),e.writtenSegments.push({path:T,duration:L,timestamp:e.currentSegmentStartTimestamp,byteSize:b,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:y??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,L),e.currentSegmentStartTimestamp=W,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=b),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const A=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(m(A.info),(u=(d=this.format._options).onSegmentPopped)==null||u.call(d,A.path,A.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}toMediaTimestamp(e){return m(this.firstPacketTimestamp!==null),e-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(e){var t,i;m(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),(i=(t=this.format._options).onSegment)==null||i.call(t,e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){const t=e.writtenSegments;let i=0,r=0,a=0;for(let o=0;o<t.length;o++){a+=t[o].duration;let c=0,d=0;for(let u=o;u<t.length&&(c+=t[u].byteSize,d+=t[u].duration,d>=.5*this.globalTargetDuration&&d<=1.5*this.globalTargetDuration&&(i=Math.max(i,8*c/d)),!(d>1.5*this.globalTargetDuration));u++);}if(i===0)for(const o of t){const c=o.duration||1;i=Math.max(i,8*o.byteSize/c)}for(const o of t)r+=8*o.byteSize;let n=r/(a||1);if(t.length===0)for(const o of e.tracks){const c=this.trackDatas.find(u=>u.track===o);let d=o.source._nominalBitrate??o.metadata.bitrate??0;if(n+=o.source._nominalBitrate??o.metadata.averageBitrate??0,d===0){const u=new Re("medium");if(o.isVideoTrack()){const l=c==null?void 0:c.info.decoderConfig;d=u._toVideoBitrate(o.source._codec,(l==null?void 0:l.codedWidth)??1920,(l==null?void 0:l.codedHeight)??1080)}else o.isAudioTrack()&&(d=u._toAudioBitrate(o.source._codec)??0)}i+=d}e.peakBitrate=i,e.averageBitrate=n}async writePlaylist(e){var l,f;m(this.output._target instanceof Pe);const t=this.output._target;this.updatePlaylistBitrates(e);let i=!1;for(const h of e.writtenSegments)i||(i=h.byteOffset!==null);const r=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let a=3;(r||i)&&(a=4),e.initSegment&&(a=5),e.initSegment&&!r&&(a=6);const n=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=be(t.rootPath,e.path),c=`#EXTM3U
94
- #EXT-X-VERSION:${a}
95
- `+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
96
- `)+`#EXT-X-TARGETDURATION:${Math.ceil(n)}
97
- `+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
98
- `:"")+`#EXT-X-INDEPENDENT-SEGMENTS
99
- `+(r?`#EXT-X-I-FRAMES-ONLY
100
- `:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
101
- `:"")+`
102
- `+e.writtenSegments.map(h=>`#EXTINF:${+h.duration.toFixed(12)},
103
- `+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*h.timestamp).toISOString()}
104
- `:"")+(h.byteOffset!==null?`#EXT-X-BYTERANGE:${h.byteSize}@${h.byteOffset}
105
- `:"")+`${h.path}
106
- `).join("")+(e.done?(e.writtenSegments.length>0?`
107
- `:"")+`#EXT-X-ENDLIST
108
- `:"");(f=(l=this.format._options).onPlaylist)==null||f.call(l,c,ot(e));const d=await this.output._getTarget({path:o,isRoot:!1,mimeType:mt}),u=new Ge(d,!0);u.start(),u.write(K.encode(c)),await u.flush(),await u.finalize()}async writeMasterPlaylist(){var c,d;m(this.output._target instanceof Pe);const e=this.output._target;let t=`#EXTM3U
109
- `,i=!1,r=null,a=0,n=!1;for(const u of this.playlistDeclarations)if(u.groupId===null){const l=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,f=[];for(const b of u.playlist.tracks){const S=this.trackDatas.find(C=>C.track===b),E=(S==null?void 0:S.info.decoderConfig.codec)??b.source._codec;f.push(Fi(E))}let h=0,y=0;if(u.references.length>0){const S=u.references[0].playlist.tracks[0],E=this.trackDatas.find(k=>k.track===S),C=(E==null?void 0:E.info.decoderConfig.codec)??S.source._codec;f.push(Fi(C));for(const k of u.references)m(k.playlist.peakBitrate!==null),h=Math.max(h,k.playlist.peakBitrate),y=Math.max(y,k.playlist.averageBitrate??0)}m(u.playlist.peakBitrate!==null);const T=u.playlist.peakBitrate+h,p=(u.playlist.averageBitrate??0)+y;i||(t+=`
110
- `,i=!0),l?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(T)}`,p>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(p)}`),t+=`,CODECS="${f.join(",")}"`;const _=u.playlist.tracks.find(b=>b.isVideoTrack());if(_!=null&&_.isVideoTrack()){const b=this.trackDatas.find(E=>E.track===_),S=b==null?void 0:b.info.decoderConfig;if(S){let E=S.displayAspectWidth??S.codedWidth,C=S.displayAspectHeight??S.codedHeight;E!==void 0&&C!==void 0&&(_.metadata.rotation!==void 0&&_.metadata.rotation%180===90&&([E,C]=[C,E]),t+=`,RESOLUTION=${E}x${C}`)}!l&&_.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+_.metadata.frameRate.toFixed(3)}`)}if(!l){const b=new Map;for(const S of u.references){m(S.groupId!==null);const E=S.playlist.tracks[0].type;b.set(E,S.groupId)}for(const[S,E]of b)t+=`,${S.toUpperCase()}="${E}"`}l?(t+=`,URI="${u.playlist.path}"`,t+=`
111
- `):(t+=`
112
- `,t+=`${u.playlist.path}
113
- `)}else{m(u.playlist.tracks.length===1);const l=u.playlist.tracks[0],f=l.type;let h=l.metadata.name??null;const y=l.metadata.languageCode,T=l.metadata.disposition;(r===null||u.groupId!==r)&&(a=0,t+=`
114
- `,n=!1),r=u.groupId,a++,t+=`#EXT-X-MEDIA:TYPE=${f.toUpperCase()},GROUP-ID="${u.groupId}"`,h!==null&&/[\n\r"]/.test(h)&&(Y._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),h=null),h??(h=`${y??u.groupId}-${a}`),t+=`,NAME="${h}"`,y!==void 0&&(t+=`,LANGUAGE="${y}"`);const p=(T==null?void 0:T.primary)??!1,_=(T==null?void 0:T.default)??!0,b=(T==null?void 0:T.forced)??!1;if(p&&!n&&(t+=",DEFAULT=YES",n=!0),(p||_)&&(t+=",AUTOSELECT=YES"),b&&(t+=",FORCED=YES"),f==="audio"){const S=this.trackDatas.find(C=>C.track===l),E=S==null?void 0:S.info.decoderConfig;E&&(t+=`,CHANNELS="${E.numberOfChannels}"`)}u.noUri||(t+=`,URI="${u.playlist.path}"`),t+=`
115
- `}(d=(c=this.format._options).onMaster)==null||d.call(c,t);const o=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{const l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:mt});u=new Ge(l,!0),u.start()}u.write(K.encode(t)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){m(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 Pn=s=>{if(typeof s!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(s))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},Bi=s=>{if(typeof s!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(s))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},En=s=>{if(typeof s!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(s))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},ot=s=>({n:s.id,tracks:s.tracks,segmentFormat:s.segmentFormat});/*!
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
- */class ne{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ke.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>We.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ye.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class Xt extends ne{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&&(!Ve(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(e){return new cn(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class Ss extends Xt{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ke,...Ue,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}_codecUnsupportedHint(e){return new Cs().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Ri extends Xt{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ke,...Ue,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}}class Cs extends Xt{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ke,...We]}_codecUnsupportedHint(e){return new Ss().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class Wi extends ne{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&&(!Ve(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 fn(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:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...ke,...Ue,...je.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Ye]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class Mt extends Wi{constructor(e){super(e)}getSupportedCodecs(){return[...ke.filter(e=>["vp8","vp9","av1"].includes(e)),...We.filter(e=>["opus","vorbis"].includes(e)),...Ye]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Wi().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class zn extends ne{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 pn(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 supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Un extends ne{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 Cn(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[...je.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Vn extends ne{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Ve(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 wn(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:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...We.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}}class Ln extends ne{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 Nr(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 supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Dn extends ne{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 Or(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 supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Nn extends ne{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.timestampOffset!==void 0&&(!Number.isFinite(e.timestampOffset)||e.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");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 bn(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:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...ke.filter(e=>["avc","hevc"].includes(e)),...We.filter(e=>["aac","mp3","ac3","eac3","dts"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class Hn extends ne{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof ne)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof ne)))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.mediaTimestampBase!==void 0&&!Number.isFinite(e.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(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 xn(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return mt}getSupportedCodecs(){const e=new Set(Fe(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()));for(const t of Pr)e.delete(t);return[...e]}getSupportedTrackCounts(){let e=!1,t=!1,i=!1;for(const r of Fe(this._options.segmentFormat)){const a=r.getSupportedTrackCounts();e||(e=a.video.max>0),t||(t=a.audio.max>0),i||(i=a.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:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Fe(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){const e=Fe(this._options.segmentFormat);return e.some(t=>t.negativeTimestampSupport==="none")?"none":e.some(t=>t.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":e.some(t=>t.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}/*!
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 zi=["video","audio","subtitle"];class Ze{constructor(e,t,i,r,a){this.id=e,this.output=t,this.type=i,this.source=r,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Ze))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Fe(this.metadata.group),i=Fe(e.metadata.group);for(const r of t)if(this.type!==e.type&&i.some(o=>r===o)||i.some(o=>r._pairedGroups.has(o)))return!0;return!1}}class vn extends Ze{constructor(e,t,i,r){super(e,t,"video",i,r)}}class An extends Ze{constructor(e,t,i,r){super(e,t,"audio",i,r)}}class Mn extends Ze{constructor(e,t,i,r){super(e,t,"subtitle",i,r)}}class fe{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof fe))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 It=s=>{if(!s||typeof s!="object")throw new TypeError("metadata must be an object.");if(s.languageCode!==void 0&&!Dt(s.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(s.name!==void 0&&typeof s.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(s.disposition!==void 0&&Mr(s.disposition),s.maximumPacketCount!==void 0&&(!Number.isInteger(s.maximumPacketCount)||s.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(s.bitrate!==void 0&&(!Number.isFinite(s.bitrate)||s.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(s.averageBitrate!==void 0&&(!Number.isFinite(s.averageBitrate)||s.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(s.group!==void 0&&!(s.group instanceof fe)&&(!Array.isArray(s.group)||s.group.some(e=>!(e instanceof fe))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class pt extends Yi{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(kt(t))throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new fe,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Ht,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 ne))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ie||e.target instanceof Pe))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ie&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ie)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ie&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){m(this._target instanceof Pe);const t=this._target.getTarget(e),i=r=>{if(!(r instanceof ie))throw new TypeError("getTarget must return a Target.");return r};return kt(t)?t.then(i):i(t)}async _getTarget(e){m(this._target instanceof Pe);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(m(this._initTarget!==null),this._initTarget instanceof ie)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 ie)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=r=>(this.state==="canceled"?r._close():this._rememberTarget(r),this._emit("target",{target:r,request:e,isRoot:!0}),this._rootTarget=r,r);return kt(t)?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const t=await this._getRootTarget(),i=new Ge(t,typeof e=="boolean"?e:e(t));return i.start(),i})())}addVideoTrack(e,t={}){if(!(e instanceof Er))throw new TypeError("source must be a VideoSource.");if(It(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(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(r=>Number.isFinite(r))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");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.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(t.decoderConfig!==void 0&&Xe({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof mi))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new vn(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof vr))throw new TypeError("source must be an AudioSource.");if(It(t),t.decoderConfig!==void 0&&le({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof mi))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new An(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof Ar))throw new TypeError("source must be a SubtitleSource.");It(t);const i={...t};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new Mn(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(Lt(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((n,o)=>n+(o.type===e.type?1:0),0),r=t[e.type].max;if(i===r)throw new Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?"":"s"}.`);const a=t.total.max;if(this.tracks.length===a)throw new Error(`${this.format._name} does not support more than ${a} tracks${a===1?"":"s"} in total.`);if(e.isVideoTrack()){const n=this.format.getSupportedVideoCodecs();if(n.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!n.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${n.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const n=this.format.getSupportedAudioCodecs();if(n.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!n.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${n.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const n=this.format.getSupportedSubtitleCodecs();if(n.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!n.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${n.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const i of zi){const r=this.tracks.reduce((n,o)=>n+(o.type===i?1:0),0),a=e[i].min;if(r<a)return!1}const t=e.total.min;return!(this.tracks.length<t)}async start(){const e=this.format.getSupportedTrackCounts();for(const i of zi){const r=this.tracks.reduce((n,o)=>n+(o.type===i?1:0),0),a=e[i].min;if(r<a)throw new Error(a===e[i].max?`${this.format._name} requires exactly ${a} ${i} track${a===1?"":"s"}.`:`${this.format._name} requires at least ${a} ${i} track${a===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?(Y._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=this._mutex.acquire();try{await this._muxer.start();const r=this.tracks.map(a=>a.source._start());await Promise.all(r)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&Y._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?(Y._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"}catch(t){throw this.state="canceled",t}finally{await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}/*!
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
- */var qe=function(s,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,r;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&&(r=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");r&&(i=function(){try{r.call(this)}catch(a){return Promise.reject(a)}}),s.stack.push({value:e,dispose:i,async:t})}else t&&s.stack.push({async:!0});return e},ct=(function(s){return function(e){function t(n){e.error=e.hasError?new s(n,e.error,"An error was suppressed during disposal."):n,e.hasError=!0}var i,r=0;function a(){for(;i=e.stack.pop();)try{if(!i.async&&r===1)return r=0,e.stack.push(i),Promise.resolve().then(a);if(i.dispose){var n=i.dispose.call(i.value);if(i.async)return r|=2,Promise.resolve(n).then(a,function(o){return t(o),a()})}else r|=1}catch(o){t(o)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return a()}})(typeof SuppressedError=="function"?SuppressedError:function(s,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=s,i.suppressed=e,i});const ut=s=>{if(!s||typeof s!="object")throw new TypeError("options.video, when provided, must be an object.");if((s==null?void 0:s.discard)!==void 0&&typeof s.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if((s==null?void 0:s.forceTranscode)!==void 0&&typeof s.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if((s==null?void 0:s.codec)!==void 0&&!ke.includes(s.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ke.join(", ")}.`);const e=s==null?void 0:s.bitrate;if((s==null?void 0:s.quality)!==void 0&&!(s.quality instanceof Re))throw new TypeError("options.video.quality, when provided, must be a Quality.");if((s==null?void 0:s.quality)!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Re)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if((s==null?void 0:s.width)!==void 0&&(!Number.isInteger(s.width)||s.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if((s==null?void 0:s.height)!==void 0&&(!Number.isInteger(s.height)||s.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if((s==null?void 0:s.fit)!==void 0&&!["fill","contain","cover"].includes(s.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if((s==null?void 0:s.width)!==void 0&&s.height!==void 0&&s.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((s==null?void 0:s.rotate)!==void 0&&![0,90,180,270].includes(s.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if((s==null?void 0:s.flip)!==void 0&&typeof s.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if((s==null?void 0:s.allowTransformationMetadata)!==void 0&&typeof s.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if((s==null?void 0:s.allowRotationMetadata)!==void 0&&typeof s.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if((s==null?void 0:s.crop)!==void 0&&Dr(s.crop,"options.video."),(s==null?void 0:s.frameRate)!==void 0&&(!Number.isFinite(s.frameRate)||s.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if((s==null?void 0:s.alpha)!==void 0&&!["discard","keep"].includes(s.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if((s==null?void 0:s.keyFrameInterval)!==void 0&&(!Number.isFinite(s.keyFrameInterval)||s.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if((s==null?void 0:s.process)!==void 0&&typeof s.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if((s==null?void 0:s.processedWidth)!==void 0&&(!Number.isInteger(s.processedWidth)||s.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if((s==null?void 0:s.processedHeight)!==void 0&&(!Number.isInteger(s.processedHeight)||s.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if((s==null?void 0:s.hardwareAcceleration)!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(s.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if((s==null?void 0:s.group)!==void 0&&!(s.group instanceof fe||Array.isArray(s.group)&&s.group.every(t=>t instanceof fe)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if((s==null?void 0:s.maximumPacketCount)!==void 0&&(!Number.isInteger(s.maximumPacketCount)||s.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},dt=s=>{if(!s||typeof s!="object")throw new TypeError("options.audio, when provided, must be an object.");if((s==null?void 0:s.discard)!==void 0&&typeof s.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if((s==null?void 0:s.forceTranscode)!==void 0&&typeof s.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if((s==null?void 0:s.codec)!==void 0&&!We.includes(s.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${We.join(", ")}.`);const e=s==null?void 0:s.bitrate;if((s==null?void 0:s.quality)!==void 0&&!(s.quality instanceof Re))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if((s==null?void 0:s.quality)!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof Re)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if((s==null?void 0:s.numberOfChannels)!==void 0&&(!Number.isInteger(s.numberOfChannels)||s.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if((s==null?void 0:s.sampleRate)!==void 0&&(!Number.isInteger(s.sampleRate)||s.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if((s==null?void 0:s.sampleFormat)!==void 0&&!["u8","s16","s32","f32"].includes(s.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if((s==null?void 0:s.process)!==void 0&&typeof s.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if((s==null?void 0:s.processedNumberOfChannels)!==void 0&&(!Number.isInteger(s.processedNumberOfChannels)||s.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if((s==null?void 0:s.processedSampleRate)!==void 0&&(!Number.isInteger(s.processedSampleRate)||s.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if((s==null?void 0:s.group)!==void 0&&!(s.group instanceof fe||Array.isArray(s.group)&&s.group.every(t=>t instanceof fe)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if((s==null?void 0:s.maximumPacketCount)!==void 0&&(!Number.isInteger(s.maximumPacketCount)||s.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},Ft=2,Bt=48e3,Ui=256;class xs{get state(){return this._state}static async init(e){const t=new xs(e);return await t._init(),t}constructor(e){var i,r,a,n,o,c,d;if(this._state="idle",this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=new Map,this._copyStartPackets=new Map,this._trackDurations=new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new In(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this._lastProcessedTime=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof Ir))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof pt))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.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(e.copy.mode!==void 0&&!["forced","preferred"].includes(e.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(e.copy.shiftTolerance!==void 0&&(!Ve(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(e.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(e.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(e.copy.boundaryTolerance!==void 0&&(!Ve(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}const t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else 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.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const u of e.video)ut(u);else ut(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const u of e.audio)dt(u);else dt(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(((i=e.trim)==null?void 0:i.start)!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(((r=e.trim)==null?void 0:r.end)!==void 0&&!Ve(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(((a=e.trim)==null?void 0:a.start)!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&Lt(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._copyMode=e.copy===!1?!1:((n=e.copy)==null?void 0:n.mode)??"preferred",this._copyTimestampShiftTolerance=e.copy===!1?0:((o=e.copy)==null?void 0:o.shiftTolerance)??0,this._copyBoundaryPolicy=e.copy===!1?"expand":((c=e.copy)==null?void 0:c.boundaryPolicy)??"expand",this._copyBoundaryTolerance=e.copy===!1?1/0:((d=e.copy)==null?void 0:d.boundaryTolerance)??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){var d,u;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 l=await this.input.getPrimaryVideoTrack(),f=await this.input.getPrimaryAudioTrack();t=[l,f].filter(h=>h!==null)}else Be(i),m(!1);const r=this.output.format.getSupportedTrackCounts();let a=1,n=1;const o=[],c=[];for(const l of t){let f;if(l.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const T=await this._options.video(l,a)??{};if(Array.isArray(T))for(const p of T)ut(p);else ut(T);f=Array.isArray(T)?T:[T],a++}else f=Array.isArray(this._options.video)?this._options.video:[this._options.video];else f=[{}];else if(l.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const T=await this._options.audio(l,n)??{};if(Array.isArray(T))for(const p of T)dt(p);else dt(T);f=Array.isArray(T)?T:[T],n++}else f=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else f=[{}];else m(!1);const h=f.filter(T=>T.discard);for(const T of h)this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:T});if(f.length===h.length){f.length===0&&this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:{}});continue}const y=f.filter(T=>!T.discard);o.push(l),c.push(y)}((d=this._options.trim)==null?void 0:d.start)!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(((u=this._options.trim)==null?void 0:u.end)??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let l=0;l<o.length;l++){const f=o[l],h=c[l];for(const y of h){if(this.output.tracks.length===r.total.max){this.discardedTracks.push({track:f,reason:"max_track_count_reached",trackOptions:y});continue}if(this.output.tracks.reduce((_,b)=>_+(b.type===f.type?1:0),0)===r[f.type].max){this.discardedTracks.push({track:f,reason:"max_track_count_of_type_reached",trackOptions:y});continue}const p=this._nextOutputTrackId++;f.isVideoTrack()?await this._processVideoTrack(f,y,p):f.isAudioTrack()?await this._processAudioTrack(f,y,p):m(!1)}}for(let l=0;l<this.utilizedTracks.length-1;l++)for(let f=l+1;f<this.utilizedTracks.length;f++){const h=this.utilizedTracks[l],y=this.utilizedTracks[f],T=this._outputOwnTrackGroups[l],p=this._outputOwnTrackGroups[f];m(T!==void 0),m(p!==void 0),T&&p&&h.canBePairedWith(y)&&T.pairWith(p)}if(!this._composable){const l={...await this.input.getMetadataTags()};delete l.creationTime;let f;if(this._options.tags){const T=typeof this._options.tags=="function"?await this._options.tags(l):this._options.tags;Lt(T),f=T}else f=l;const h=e.mimeType===this.output.format.mimeType;l.raw===f.raw&&!h&&delete f.raw,this.output.setMetadataTags(f)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){const l=[],f=this.discardedTracks.filter(h=>h.reason!=="discarded_by_user");f.length>0&&l.push("Some tracks had to be discarded from the conversion:",f),this.isValid||(l.length>0&&l.push(`
134
-
135
- `),l.push(this._getInvalidityExplanation().join(""))),l.length>0&&Y._warn(...l)}}_getInvalidityExplanation(){const e=[];if(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(a=>{if(a.reason==="discarded_by_user")return[];let n;return a.track.type==="video"?n=this.output.format.getSupportedVideoCodecs():a.track.type==="audio"?n=this.output.format.getSupportedAudioCodecs():n=this.output.format.getSupportedSubtitleCodecs(),n.filter(o=>!a.trackOptions.codec||o===a.trackOptions.codec)}),r=[...new Set(i)];r.length===1?e.push(`
136
- Tracks were discarded because your environment is not able to encode '${r[0]}' with the provided parameters.`):e.push(`
137
- Tracks were discarded because your environment is not able to encode any of the codecs ${r.map(a=>`'${a}'`).join(", ")} with the provided parameters.`),r.includes("mp3")&&e.push(`
138
- The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),r.includes("aac")&&e.push(`
139
- The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(r.includes("ac3")||r.includes("eac3"))&&e.push(`
140
- The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),r.includes("flac")&&e.push(`
141
- The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
142
- Check the discardedTracks field for more info.`)}return e}async execute(e={}){var r,a,n,o,c,d;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.until!==void 0&&(typeof e.until!="number"||Number.isNaN(e.until)))throw new TypeError("options.until, when provided, must be a number.");if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");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.
143
- `+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new Vi;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=((r=e.pauseSignal)==null?void 0:r.aborted)??!1;const t=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};(a=e.pauseSignal)==null||a.addEventListener("abort",t);for(const u of this._trackPumps)u.done||(u.resolvers=Ee());if(this._executed)for(const u of this._trackPumps)(o=u.wake)==null||o.call(u);else{this._executed=!0;for(const u of this._outputTrackIds)this._synchronizer.declareTrack(u);if(this.onProgress){const l=[...new Set(this.utilizedTracks)].map(h=>this._getTrackDuration(h)),f=Math.max(0,...await Promise.all(l));this._computeProgress=!0,this._totalDuration=Math.min(f-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const h of this._outputTrackIds)this._maxTimestamps.set(h,0);(n=this.onProgress)==null||n.call(this,0,0)}this._composable||await this.output.start();for(const u of this._trackPumps)u.start()}try{await Promise.all(this._trackPumps.map(u=>u.resolvers.promise))}catch(u){throw this._state!=="canceled"&&this.cancel(),u}finally{(c=e.pauseSignal)==null||c.removeEventListener("abort",t)}if(this._state==="canceled")throw new Vi;const i=this._trackPumps.every(u=>u.done);this._state=i?"done":"idle",i&&(this._composable||await this.output.finalize(),this._computeProgress&&((d=this.onProgress)==null||d.call(this,1,this._lastProcessedTime)))}async cancel(){var e;if(this._state!=="done"){if(this._state==="canceled"){Y._warn("Conversion already canceled.");return}this._state="canceled";for(const t of this._trackPumps)(e=t.wake)==null||e.call(t);this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,i){const r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:"unknown_maximum_packet_count",trackOptions:t});return}let a;const n=await e.getRotation(),o=await e.getFlip(),{rotation:c,flip:d}=Fr(n,o,t.rotate??0,t.flip??!1);let u=c,l=d,f=t.rotate||t.flip?null:await e.getTransformationMatrix();const h=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??!0),y=await e.getSquarePixelWidth(),T=await e.getSquarePixelHeight(),[p,_]=c%180===0?[y,T]:[T,y];let b=t.crop;b&&(b=Br(b,p,_));const[S,E]=b?[b.width,b.height]:[p,_];let C=S,k=E;const U=C/k;t.width!==void 0&&t.height===void 0?(C=ze(t.width),k=ze(Math.round(C/U))):t.width===void 0&&t.height!==void 0?(k=ze(t.height),C=ze(Math.round(k*U))):t.width!==void 0&&t.height!==void 0&&(C=ze(t.width),k=ze(t.height));let q=this.output.format.getSupportedVideoCodecs();const W=t.alpha??"discard";let L=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!q.includes(r)||t.codec&&t.codec!==r||C!==S||k!==E||c!==0&&!h||d&&!h||!!b,A=null;if(!L){const j=new rt(e);let N=await j.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await j.getFirstKeyPacket({verifyKeyPackets:!0});if(N&&N.timestamp<this._startTimestamp&&N.timestamp+N.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(N=await j.getNextKeyPacket(N,{verifyKeyPackets:!0})),A=N,N){const G=this._copyBoundaryPolicy==="shrink"?Math.max(N.timestamp,this._startTimestamp):N.timestamp;if((this._copyBoundaryPolicy==="shrink"?G-this._startTimestamp:Math.max(this._startTimestamp-G,0))>this._copyBoundaryTolerance)L=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&G<this._startTimestamp){const X=Math.min(this._startTimestamp-G,this._copyTimestampShiftTolerance);G+X>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+X):L=!0}}else if(this._timestampOffsetAdjusted)G+this._timestampOffset===0||(L=!0);else{const X=lt(this._startTimestamp-G,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);G+X===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+X,this._timestampOffsetAdjusted=!0):L=!0}}}if(L&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(L){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(q=q.filter(J=>J===t.codec));const N=fi(t.quality,t.bitrate)??new Re("high"),G=await Rr(q,{width:t.process&&t.processedWidth?t.processedWidth:C,height:t.process&&t.processedHeight?t.processedHeight:k,quality:N});if(!G){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const Q={codec:G,quality:N,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:W,hardwareAcceleration:t.hardwareAcceleration,transform:{}};m(Q.transform);let X=C!==S||k!==E||c!==0&&(!h||t.process!==void 0)||d&&(!h||t.process!==void 0)||!!b||y!==await e.getCodedWidth()||T!==await e.getCodedHeight();if(!X){const J={stack:[],error:void 0,hasError:!1};try{const O=new pt({format:new Ss,target:new ys}),ee=new hi(Q);O.addVideoTrack(ee),await O.start();const te=new pi(e,{hardwareAcceleration:t.hardwareAcceleration}),$=qe(J,await te.getSample(await e.getFirstTimestamp()),!1);if($)try{await ee.add($),$.close(),await O.finalize()}catch(re){Y._warn("An error occurred when probing encoder support. Falling back to rerender path.",re),O.cancel(),X=!0,Q.transform.force=!0}else await O.cancel()}catch(O){J.error=O,J.hasError=!0}finally{ct(J)}}t.frameRate&&(Q.transform.frameRate=t.frameRate),t.process&&(Q.transform.process=t.process),X&&(u=0,l=!1,f=null,Q.transform.width=C,Q.transform.height=k,Q.transform.fit=t.fit??"fill",Q.transform.rotate=t.rotate,Q.transform.flip=t.flip,Q.transform.crop=b,Q.transform.alpha=W);let he=null;Q.onEncodedSample=J=>{he=J.timestamp};const ye=new hi(Q);a=ye,this._registerTrackPump(async J=>{const O=new pi(e,{hardwareAcceleration:t.hardwareAcceleration});for await(const ee of O.samples(this._startTimestamp,this._endTimestamp)){const te={stack:[],error:void 0,hasError:!1};try{const $=qe(te,ee,!1);if(this._state==="canceled")break;const re=Math.max(this._startTimestamp,$.timestamp),De=Math.min(this._endTimestamp,$.timestamp+$.duration);if(re>=De)continue;$.setTimestamp(re+this._timestampOffset),$.setDuration(De-re),this._updateProgress(i,$.timestamp+$.duration),await ye.add($),$.close(),he!==null&&(this._synchronizer.shouldWait(i,he)&&await this._synchronizer.wait(he),await this._checkpoint(J,he))}catch($){te.error=$,te.hasError=!0}finally{ct(te)}}ye.close(),this._closeTrack(i)})}else{const j=new Ut(r);a=j,this._registerTrackPump(async N=>{const G=new rt(e),X={decoderConfig:await e.getDecoderConfig()??void 0},he=new Nt;let ye=!1,J=!1;if(A)for await(const O of G.packets(A,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(O.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let De=O,Yt=!1;const Es=6;for(let Zt=0;Zt<Es;Zt++){const Tt=await G.getNextPacket(De,{metadataOnly:!0});if(!Tt)break;if(Tt.timestamp<this._endTimestamp){Yt=!0;break}De=Tt}if(!Yt)break}}let ee=O.timestamp,te=O.timestamp+O.duration;if(this._copyBoundaryPolicy==="shrink"&&(ee=Math.max(ee,this._startTimestamp),te=Math.min(te,this._endTimestamp),te=Math.max(te,ee)),ee+=this._timestampOffset,te+=this._timestampOffset,O.type==="key"&&(ye=!1),ye)continue;let $=O.type;if($==="key"&&!he.check(ee,"key")&&($="delta"),!he.digest(ee,$)){ye=O.type==="key",J||(Y._warn("Some video packets had to be dropped in order to produce correct output timestamps."),J=!0);continue}const re=O.clone({timestamp:ee,duration:te-ee,sideData:W==="discard"?{}:O.sideData,type:$});this._updateProgress(i,re.timestamp+re.duration),await j.add(re,X),this._synchronizer.shouldWait(i,re.timestamp)&&await this._synchronizer.wait(re.timestamp),await this._checkpoint(N,re.timestamp)}j.close(),this._closeTrack(i)})}let M=null;!t.group&&!this._composable&&(M=new fe);const P=await e.getLanguageCode(),F=await e.getName(),z=await e.getDisposition(),R=L?null:await e.getBitrate(),Z=L?null:await e.getAverageBitrate(),Ce=W==="keep"&&await e.canBeTransparent();let Ae=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&Ae===void 0){const j=t.frameRate??(await e.computePacketStats(Ui)).averagePacketRate,N=L?this._startTimestamp:(A==null?void 0:A.timestamp)??this._startTimestamp;Ae=await this._estimateMaximumPacketCount(e,N,j)}this.output.addVideoTrack(a,{frameRate:t.frameRate,languageCode:Dt(P)?P:void 0,name:F??void 0,disposition:z,rotation:u,flip:l,transformationMatrix:f??void 0,canBeTransparent:Ce,group:M??t.group,bitrate:R??void 0,averageBitrate:Z??void 0,maximumPacketCount:Ae}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(M)}async _processAudioTrack(e,t,i){const r=await e.getCodec();if(!r){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}if(this.output.format.requiresMaximumPacketCount&&t.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await e.isLive()){this.discardedTracks.push({track:e,reason:"unknown_maximum_packet_count",trackOptions:t});return}let a;const n=await e.getNumberOfChannels(),o=await e.getSampleRate();let c=t.numberOfChannels??n,d=t.sampleRate??o,u=null,l=this.output.format.getSupportedAudioCodecs(),f=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||c!==n||d!==o||!l.includes(r)||!!t.codec&&t.codec!==r||t.process!==void 0||t.sampleFormat!==void 0,h=null;if(!f){const C=new rt(e);let k=await C.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await C.getFirstKeyPacket({verifyKeyPackets:!0});k&&(this._copyBoundaryPolicy==="shrink"&&k.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&k.timestamp+k.duration<=this._startTimestamp)&&(k=await C.getNextKeyPacket(k,{verifyKeyPackets:!0}));const U=await e.getPreRollDuration();if(m(U!==null),k&&this._copyBoundaryPolicy==="expand"&&U>0&&(k=await C.getKeyPacket(k.timestamp-U,{verifyKeyPackets:!0})??await C.getFirstKeyPacket({verifyKeyPackets:!0})),h=k,k)if((this._copyBoundaryPolicy==="shrink"?Math.max(k.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-k.timestamp,0))>this._copyBoundaryTolerance)f=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&k.timestamp<this._startTimestamp){const W=Math.min(this._startTimestamp-k.timestamp,this._copyTimestampShiftTolerance);k.timestamp+W>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+W):f=!0}}else if(this._timestampOffsetAdjusted)k.timestamp+this._timestampOffset===0||(f=!0);else{const W=lt(this._startTimestamp-k.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);k.timestamp+W===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+W,this._timestampOffsetAdjusted=!0):f=!0}}if(f&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(f){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(l=l.filter(A=>A===t.codec));const k=fi(t.quality,t.bitrate)??new Re("high"),U=await gi(l,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:d,quality:k});if(!U.some(A=>Ue.includes(A))&&l.some(A=>Ue.includes(A))&&(c!==Ft||d!==Bt)){const M=(await gi(l,{numberOfChannels:Ft,sampleRate:Bt,quality:k})).find(P=>Ue.includes(P));M&&(u=M,c=Ft,d=Bt)}else u=U[0]??null;if(u===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const q={codec:u,quality:k,transform:{sampleFormat:t.sampleFormat,process:t.process}};m(q.transform),c!==n&&(q.transform.numberOfChannels=c),d!==o&&(q.transform.sampleRate=d);let W=null;q.onEncodedSample=A=>{W=A.timestamp};const L=new Wr(q);a=L,this._registerTrackPump(async A=>{let M=null;const P=new zr(e);for await(const F of P.samples(this._startTimestamp,this._endTimestamp)){const z={stack:[],error:void 0,hasError:!1};try{const R=qe(z,F,!1);if(this._state==="canceled")break;let Z=0,Ce=R.numberOfFrames;if(R.timestamp<this._startTimestamp&&(Z=Math.round((this._startTimestamp-R.timestamp)*R.sampleRate)),R.timestamp+R.duration>this._endTimestamp&&(Ce=Math.round((this._endTimestamp-R.timestamp)*R.sampleRate)),Z>=Ce){R.close();continue}let Ae;if(Z>0||Ce<R.numberOfFrames){const N=R.trim(Z,Ce);if(R.close(),Ae=N,N.numberOfFrames===0){N.close();continue}}else Ae=R;const j=qe(z,Ae,!1);if(j.setTimestamp(j.timestamp+this._timestampOffset),M===null&&(M=this.output.format.supportsTimestampedMediaData?0:Math.round(j.timestamp*o)),M>0){const N={stack:[],error:void 0,hasError:!1};try{const G=Ur(R.format),Q=new Uint8Array(G*M*n);(R.format==="u8"||R.format==="u8-planar")&&Q.fill(2**7);const X=qe(N,new Vr({data:Q,format:R.format,numberOfChannels:n,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(A,X,L,i,()=>W),M=0}catch(G){N.error=G,N.hasError=!0}finally{ct(N)}}await this._registerAudioSample(A,j,L,i,()=>W)}catch(R){z.error=R,z.hasError=!0}finally{ct(z)}}L.close(),this._closeTrack(i)})}else{const C=new Vt(r);a=C,this._registerTrackPump(async k=>{const U=new rt(e),W={decoderConfig:await e.getDecoderConfig()??void 0},L=new Nt;let A=!1,M=!1;if(h)for await(const P of U.packets(h)){if(this._state==="canceled"||P.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&P.timestamp+P.duration>this._endTimestamp)break;const F=P.timestamp+this._timestampOffset;if(P.type==="key"&&(A=!1),A)continue;if(!L.digest(F,P.type)){A=P.type==="key",M||(Y._warn("Some audio packets had to be dropped in order to produce correct output timestamps."),M=!0);continue}const z=P.clone({timestamp:F,duration:P.duration});this._updateProgress(i,z.timestamp+z.duration),await C.add(z,W),this._synchronizer.shouldWait(i,z.timestamp)&&await this._synchronizer.wait(z.timestamp),await this._checkpoint(k,z.timestamp)}C.close(),this._closeTrack(i)})}let y=null;!t.group&&!this._composable&&(y=new fe);const T=await e.getLanguageCode(),p=await e.getName(),_=await e.getDisposition(),b=f?null:await e.getBitrate(),S=f?null:await e.getAverageBitrate();let E=t.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&E===void 0){let C;f?(m(u),C=d/Lr(u,d)):C=(await e.computePacketStats(Ui)).averagePacketRate;const k=f?this._startTimestamp:(h==null?void 0:h.timestamp)??this._startTimestamp;E=await this._estimateMaximumPacketCount(e,k,C)}this.output.addAudioTrack(a,{languageCode:Dt(T)?T:void 0,name:p??void 0,disposition:_,group:y??t.group,bitrate:b??void 0,averageBitrate:S??void 0,maximumPacketCount:E}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(y)}async _estimateMaximumPacketCount(e,t,i){const r=Math.min(await this._getTrackDuration(e),this._endTimestamp),a=Math.max(r-t,0);return Math.ceil(1.5*i*a)+64}_getTrackDuration(e){let t=this._trackDurations.get(e);return t||(t=(async()=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration())(),this._trackDurations.set(e,t)),t}async _registerAudioSample(e,t,i,r,a){this._updateProgress(r,t.timestamp+t.duration),await i.add(t),t.close();const n=a();n!==null&&(this._synchronizer.shouldWait(r,n)&&await this._synchronizer.wait(n),await this._checkpoint(e,n))}_registerTrackPump(e){const t={done:!1,resolvers:Ee(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},i=>{t.resolvers.reject(i)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!=="canceled"&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();const{promise:i,resolve:r}=Ee();e.wake=r,await i}}_closeTrack(e){this._synchronizer.closeTrack(e),this._maxTimestamps.delete(e),this._reportProgress()}_updateProgress(e,t){this._computeProgress&&(this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e))),this._reportProgress())}_reportProgress(){var i;if(!this._computeProgress||this._maxTimestamps.size===0)return;m(this._totalDuration!==null);const e=Math.min(...this._maxTimestamps.values()),t=lt(e/this._totalDuration,0,1);this._lastProcessedTime=e,t!==this._lastProgress&&(this._lastProgress=t,(i=this.onProgress)==null||i.call(this,t,e))}}class Vi extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const Li=1;class In{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){const i=this.maxTimestamps.get(e);m(i!==void 0),this.maxTimestamps.set(e,Math.max(t,i));const r=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-r>Li}wait(e){const{promise:t,resolve:i}=Ee();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(const e of this.resolvers)e.resolve();this.resolvers.length=0}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<Li&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}}/*!
144
- * Copyright (c) 2026-present, Vanilagy and contributors
145
- *
146
- * This Source Code Form is subject to the terms of the Mozilla Public
147
- * License, v. 2.0. If a copy of the MPL was not distributed with this
148
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
149
- */const Ps=Symbol.for("mediabunny loaded");globalThis[Ps]&&Y._error(`[WARNING]
150
- Mediabunny 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[Ps]=!0;export{$n as ADTS,Kn as ALL_FORMATS,zi as ALL_TRACK_TYPES,We as AUDIO_CODECS,Qn as AdtsInputFormat,Ln as AdtsOutputFormat,Rn as AppendOnlyStreamTarget,rr as AttachedFile,Gn as AudioBufferSink,jn as AudioBufferSource,Vr as AudioSample,Xn as AudioSampleResource,zr as AudioSampleSink,Wr as AudioSampleSource,vr as AudioSource,Yn as BaseMediaSampleSink,Zn as BlobSource,Jn as BufferSource,At as BufferTarget,eo as CanvasSink,to as CanvasSource,Ri as CmafOutputFormat,io as ConcurrentRunner,xs as Conversion,Vi as ConversionCanceledError,so as CustomAudioDecoder,ro as CustomAudioEncoder,ao as CustomPathedSource,no as CustomSource,oo as CustomVideoDecoder,co as CustomVideoEncoder,Vt as EncodedAudioPacketSource,mi as EncodedPacket,rt as EncodedPacketSink,Ut as EncodedVideoPacketSource,Yi as EventEmitter,uo as FLAC,lo as FilePathSource,Wn as FilePathTarget,mo as FlacInputFormat,Dn as FlacOutputFormat,fo as HLS,ho as HLS_FORMATS,po as HlsInputFormat,Hn as HlsOutputFormat,Ir as Input,go as InputAudioTrack,wo as InputDisposedError,To as InputFormat,yo as InputTrack,bo as InputVideoTrack,_o as IsobmffInputFormat,Xt as IsobmffOutputFormat,ko as LogLevel,Y as Logging,So as MATROSKA,Co as MP3,xo as MP4,Po as MPEG_TS,Eo as MatroskaInputFormat,vo as MediaSource,Ao as MediaStreamAudioTrackSource,Mo as MediaStreamVideoTrackSource,Wi as MkvOutputFormat,Cs as MovOutputFormat,Io as Mp3InputFormat,zn as Mp3OutputFormat,Fo as Mp4InputFormat,Ss as Mp4OutputFormat,Bo as MpegTsInputFormat,Nn as MpegTsOutputFormat,Ue as NON_PCM_AUDIO_CODECS,ys as NullTarget,Ro as OGG,Wo as OggInputFormat,Vn as OggOutputFormat,pt as Output,An as OutputAudioTrack,ne as OutputFormat,Mn as OutputSubtitleTrack,Ze as OutputTrack,fe as OutputTrackGroup,vn as OutputVideoTrack,je as PCM_AUDIO_CODECS,zo as PathedSource,Pe as PathedTarget,Uo as QTFF,Vo as QUALITY_HIGH,Lo as QUALITY_LOW,Do as QUALITY_MEDIUM,No as QUALITY_VERY_HIGH,Ho as QUALITY_VERY_LOW,Re as Quality,qo as QuickTimeInputFormat,Oo as RangedSource,nn as RangedTarget,$o as ReadableStreamSource,Ws as RichImageData,Ye as SUBTITLE_CODECS,Ko as Source,Qo as SourceRef,Go as StreamSource,Ts as StreamTarget,Ar as SubtitleSource,ie as Target,jo as TextSubtitleSource,Xo as UnsupportedInputFormatError,Yo as UrlSource,ke as VIDEO_CODECS,Zo as VIDEO_SAMPLE_PIXEL_FORMATS,Jo as VideoSample,ec as VideoSampleColorSpace,tc as VideoSampleResource,pi as VideoSampleSink,hi as VideoSampleSource,Er as VideoSource,ic as WAVE,sc as WEBM,Un as WavOutputFormat,rc as WaveInputFormat,ac as WebMInputFormat,Mt as WebMOutputFormat,nc as asc,oc as canDecode,cc as canDecodeAudio,uc as canDecodeVideo,dc as canEncode,lc as canEncodeAudio,mc as canEncodeSubtitles,fc as canEncodeVideo,hc as desc,pc as getDecodableAudioCodecs,gc as getDecodableCodecs,wc as getDecodableVideoCodecs,gi as getEncodableAudioCodecs,Tc as getEncodableCodecs,yc as getEncodableSubtitleCodecs,bc as getEncodableVideoCodecs,_c as getFirstEncodableAudioCodec,kc as getFirstEncodableSubtitleCodec,Rr as getFirstEncodableVideoCodec,Sc as prefer,Cc as registerDecoder,xc as registerEncoder,Pc as registerVideoSampleTransformer};