mediabunny 1.44.1 → 1.44.2

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.
@@ -31032,13 +31032,13 @@ ${cue.notes ?? ""}`;
31032
31032
  this.maxWrittenFrame = null;
31033
31033
  this.targetSampleRate = options.targetSampleRate;
31034
31034
  this.targetNumberOfChannels = options.targetNumberOfChannels;
31035
- this.startTime = options.startTime;
31036
31035
  this.endTime = options.endTime;
31037
31036
  this.onSample = options.onSample;
31038
31037
  this.bufferSizeInFrames = Math.floor(this.targetSampleRate * 5);
31039
31038
  this.bufferSizeInSamples = this.bufferSizeInFrames * this.targetNumberOfChannels;
31040
31039
  this.outputBuffer = new Float32Array(this.bufferSizeInSamples);
31041
- this.bufferStartFrame = Math.floor(this.startTime * this.targetSampleRate);
31040
+ this.bufferStartFrame = Math.floor(options.startTime * this.targetSampleRate);
31041
+ this.timestampOffset = options.startTime - this.bufferStartFrame / this.targetSampleRate;
31042
31042
  }
31043
31043
  /**
31044
31044
  * Sets up the channel mixer to handle up/downmixing in the case where input and output channel counts don't match.
@@ -31188,7 +31188,7 @@ ${cue.notes ?? ""}`;
31188
31188
  format: "f32",
31189
31189
  sampleRate: this.targetSampleRate,
31190
31190
  numberOfChannels: this.targetNumberOfChannels,
31191
- timestamp: timestampSeconds,
31191
+ timestamp: timestampSeconds + this.timestampOffset,
31192
31192
  data: outputData
31193
31193
  });
31194
31194
  await this.onSample(audioSample);
@@ -36621,6 +36621,7 @@ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.
36621
36621
  startTime: this._startTimestamp,
36622
36622
  endTime: this._endTimestamp,
36623
36623
  onSample: async (sample) => {
36624
+ assert(sample.timestamp >= this._startTimestamp);
36624
36625
  sample.setTimestamp(sample.timestamp - this._startTimestamp);
36625
36626
  await this._registerAudioSample(trackOptions, outputTrackId, source, sample);
36626
36627
  sample.close();
@@ -36,7 +36,7 @@
36
36
 
37
37
  `,a);c===-1&&(c=t.length);let u=to(e[2]),m=to(e[3])-u,d=t.slice(s,c).trim();t=t.slice(c).trimStart(),ta.lastIndex=0;let f={timestamp:u/1e3,duration:m/1e3,text:d,identifier:i,settings:o,notes:r},h={};this.preambleEmitted||(h.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,h)}}},cf=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,to=n=>{let t=cf.exec(n);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},ro=n=>{let t=Math.floor(n/36e5),e=Math.floor(n%(60*60*1e3)/(60*1e3)),r=Math.floor(n%(60*1e3)/1e3),i=n%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+i.toString().padStart(3,"0")};var ai=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8===7&&this.writer.write(this.helper);t.length%8!==0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{let e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(let a of t.children)a&&this.writeBox(a);let r=this.writer.getPos(),i=t.size??r-e;this.writer.seek(e),this.writeBoxHeader(t,i),this.writer.seek(r)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){let e=this.offsets.get(t);p(e!==void 0);let r=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(r)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(let r of t.children)r&&(e+=this.measureBox(r));return e}}},G=new Uint8Array(8),Je=new DataView(G.buffer),fe=n=>[(n%256+256)%256],W=n=>(Je.setUint16(0,n,!1),[G[0],G[1]]),Zc=n=>(Je.setInt16(0,n,!1),[G[0],G[1]]),_d=n=>(Je.setUint32(0,n,!1),[G[1],G[2],G[3]]),_=n=>(Je.setUint32(0,n,!1),[G[0],G[1],G[2],G[3]]),ar=n=>(Je.setInt32(0,n,!1),[G[0],G[1],G[2],G[3]]),Mt=n=>(Je.setUint32(0,Math.floor(n/2**32),!1),Je.setUint32(4,n,!1),[G[0],G[1],G[2],G[3],G[4],G[5],G[6],G[7]]),uf=n=>(Je.setInt32(0,Math.floor(n/2**32),!1),Je.setUint32(4,n,!1),[G[0],G[1],G[2],G[3],G[4],G[5],G[6],G[7]]),Rd=n=>(Je.setInt16(0,2**8*n,!1),[G[0],G[1]]),kt=n=>(Je.setInt32(0,2**16*n,!1),[G[0],G[1],G[2],G[3]]),Xc=n=>(Je.setInt32(0,2**30*n,!1),[G[0],G[1],G[2],G[3]]),$c=(n,t)=>{let e=[],r=n;do{let i=r&127;r>>=7,e.length>0&&(i|=128),e.push(i),t!==void 0&&t--}while(r>0||t);return e.reverse()},ne=(n,t=!1)=>{let e=Array(n.length).fill(null).map((r,i)=>n.charCodeAt(i));return t&&e.push(0),e},Fd=n=>{let t=n*(Math.PI/180),e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},Md=Fd(0),Bd=n=>[kt(n[0]),kt(n[1]),Xc(n[2]),kt(n[3]),kt(n[4]),Xc(n[5]),kt(n[6]),kt(n[7]),Xc(n[8])],N=(n,t,e)=>({type:n,contents:t&&new Uint8Array(t.flat(10)),children:e}),Y=(n,t,e,r,i)=>N(n,[fe(t),_d(e),r??[]],i),Od=n=>n.isQuickTime?N("ftyp",[ne("qt "),_(512),ne("qt ")]):n.fragmented?n.cmaf?N("ftyp",[ne("iso5"),_(512),ne("iso5"),ne("iso6"),ne("mp41"),ne("cmfc"),ne("dash")]):N("ftyp",[ne("iso5"),_(512),ne("iso5"),ne("iso6"),ne("mp41")]):N("ftyp",[ne("isom"),_(512),ne("isom"),n.holdsAvc?ne("avc1"):[],ne("mp41")]),Jc=()=>N("styp",[ne("iso5"),_(0),ne("iso5"),ne("iso6"),ne("mp41"),ne("cmfc"),ne("dash")]),eu=(n,t)=>{let e=n.maxWrittenEndTimestamp-n.minWrittenTimestamp;return Number.isFinite(e)||(e=0),Y("sidx",1,0,[_(1),_(Ze),Mt(ue(n.minWrittenTimestamp,Ze)),Mt(0),W(0),W(1),_(t&2147483647),_(ue(e,Ze)),_(0)])},ra=n=>({type:"mdat",largeSize:n}),Dd=n=>({type:"free",size:n}),tn=n=>N("moov",void 0,[lf(n.creationTime,n.trackDatas),...n.trackDatas.map(t=>df(t,n.creationTime)),n.isFragmented?$f(n.trackDatas):null,ap(n)]),lf=(n,t)=>{let e=Math.max(0,...t.map(s=>ue(io(s),Ze)+ue(s.startTimestampOffset??0,Ze))),r=Math.max(0,...t.map(s=>s.track.id))+1,i=!Ut(n)||!Ut(e),a=i?Mt:_;return Y("mvhd",+i,0,[a(n),a(n),_(Ze),a(e),kt(1),Rd(1),Array(10).fill(0),Bd(Md),Array(24).fill(0),_(r)])},io=n=>{if(n.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;r<n.samples.length;r++){let i=n.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>e&&(e=i.timestamp+i.duration)}return t===1/0?0:e-t},df=(n,t)=>{let e=Kd(n),r=n.startTimestampOffset!==null&&n.startTimestampOffset>0;return N("trak",void 0,[mf(n,t),r?ff(n,n.startTimestampOffset):null,pf(n,t),e.name!==void 0?N("udta",void 0,[N("name",[...$.encode(e.name)])]):null])},mf=(n,t)=>{let e=ue(io(n),Ze)+ue(n.startTimestampOffset??0,Ze),r=!Ut(t)||!Ut(e),i=r?Mt:_,a;if(n.type==="video"){let o=n.track.metadata.rotation;a=Fd(o??0)}else a=Md;let s=2;return n.track.metadata.disposition?.default!==!1&&(s|=1),Y("tkhd",+r,s,[i(t),i(t),_(n.track.id),_(0),i(e),Array(8).fill(0),W(0),W(n.track.id),Rd(n.type==="audio"?1:0),W(0),Bd(a),kt(n.type==="video"?n.info.width:0),kt(n.type==="video"?n.info.height:0)])},ff=(n,t)=>{let e=ue(t,Ze),r=ue(io(n),Ze),i=!Ut(e)||!Ut(r),a=i?Mt:_,s=i?uf:ar;return N("edts",void 0,[Y("elst",i?1:0,0,[_(2),a(e),s(-1),kt(1),a(r),s(0),kt(1)])])},pf=(n,t)=>N("mdia",void 0,[hf(n,t),tu(!0,gf[n.type],bf[n.type]),yf(n)]),hf=(n,t)=>{let e=ue(io(n),n.timescale),r=!Ut(t)||!Ut(e),i=r?Mt:_;return Y("mdhd",+r,0,[i(t),i(t),_(n.timescale),i(e),W(qd(n.track.metadata.languageCode??ee)),W(0)])},gf={video:"vide",audio:"soun",subtitle:"text"},bf={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},tu=(n,t,e,r="\0\0\0\0")=>Y("hdlr",0,0,[n?ne("mhlr"):_(0),ne(t),ne(r),_(0),_(0),ne(e,!0)]),yf=n=>N("minf",void 0,[Sf[n.type](),Af(),Cf(n)]),kf=()=>Y("vmhd",0,1,[W(0),W(0),W(0),W(0)]),Tf=()=>Y("smhd",0,0,[W(0),W(0)]),wf=()=>Y("nmhd",0,0),Sf={video:kf,audio:Tf,subtitle:wf},Af=()=>N("dinf",void 0,[xf()]),xf=()=>Y("dref",0,0,[_(1)],[Pf()]),Pf=()=>Y("url ",0,1),Cf=n=>{let t=n.compositionTimeOffsetTable.length>1||n.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return N("stbl",void 0,[If(n),Hf(n),t?jf(n):null,t?Xf(n):null,Kf(n),Gf(n),Qf(n),qf(n)])},If=n=>{let t;if(n.type==="video")t=Ef(up(n.track.source._codec,n.info.decoderConfig.codec),n);else if(n.type==="audio"){let e=Hd(n.track.source._codec,n.muxer.isQuickTime);p(e),t=Bf(e,n)}else n.type==="subtitle"&&(t=Lf(mp[n.track.source._codec],n));return p(t),Y("stsd",0,0,[_(1)],[t])},Ef=(n,t)=>N(n,[Array(6).fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),_(4718592),_(4718592),_(0),W(1),Array(32).fill(0),W(24),Zc(65535)],[lp[t.track.source._codec](t),vf(t),fa(t.info.decoderConfig.colorSpace)?_f(t):null]),vf=n=>n.info.pixelAspectRatio.num===n.info.pixelAspectRatio.den?null:N("pasp",[_(n.info.pixelAspectRatio.num),_(n.info.pixelAspectRatio.den)]),_f=n=>N("colr",[ne("nclx"),W(rt[n.info.decoderConfig.colorSpace.primaries]),W(it[n.info.decoderConfig.colorSpace.transfer]),W(nt[n.info.decoderConfig.colorSpace.matrix]),fe((n.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Rf=n=>n.info.decoderConfig&&N("avcC",[...j(n.info.decoderConfig.description)]),Ff=n=>n.info.decoderConfig&&N("hvcC",[...j(n.info.decoderConfig.description)]),Ed=n=>{if(!n.info.decoderConfig)return null;let t=n.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),i=Number(e[2]),a=Number(e[3]),s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,u=e[5]?Number(e[5]):t.colorSpace?.primaries?rt[t.colorSpace.primaries]:2,l=e[6]?Number(e[6]):t.colorSpace?.transfer?it[t.colorSpace.transfer]:2,m=e[7]?Number(e[7]):t.colorSpace?.matrix?nt[t.colorSpace.matrix]:2;return Y("vpcC",1,0,[fe(r),fe(i),fe(c),fe(u),fe(l),fe(m),W(0)])},Mf=n=>N("av1C",Sa(n.info.decoderConfig.codec)),Bf=(n,t)=>{let e=0,r,i=16,a=te.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Ae(s);i=8*o,i>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),W(1),W(e),W(0),_(0),W(t.info.numberOfChannels),W(i),W(0),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0)];else{let s=a?0:-2;r=[Array(6).fill(0),W(1),W(e),W(0),_(0),W(t.info.numberOfChannels),W(Math.min(i,16)),Zc(s),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),a?[_(1),_(i/8),_(t.info.numberOfChannels*i/8)]:[_(0),_(0),_(0)],_(2)]}return N(n,r,[dp(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Yc=n=>{let t;switch(n.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${n.track.source._codec}`)}let e=[...fe(t),...fe(21),..._d(0),..._(0),..._(0)];if(n.info.decoderConfig.description){let r=j(n.info.decoderConfig.description);e=[...e,...fe(5),...$c(r.byteLength),...r]}return e=[...W(1),...fe(0),...fe(4),...$c(e.length),...e,...fe(6),...fe(1),...fe(2)],e=[...fe(3),...$c(e.length),...e],Y("esds",0,0,e)},Mr=n=>N("wave",void 0,[Of(n),Df(n),N("\0\0\0\0")]),Of=n=>N("frma",[ne(Hd(n.track.source._codec,n.muxer.isQuickTime))]),Df=n=>{let{littleEndian:t}=Ae(n.track.source._codec);return N("enda",[W(+t)])},Vf=n=>{let t=n.info.numberOfChannels,e=3840,r=n.info.sampleRate,i=0,a=0,s=new Uint8Array(0),o=n.info.decoderConfig?.description;if(o){p(o.byteLength>=18);let c=j(o),u=yr(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,i=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return N("dOps",[fe(0),fe(t),W(e),_(r),Zc(i),fe(a),...s])},Uf=n=>{let t=n.info.decoderConfig?.description;p(t);let e=j(t);return Y("dfLa",0,0,[...e.subarray(4)])},Rt=n=>{let{littleEndian:t,sampleSize:e}=Ae(n.track.source._codec),r=+t;return Y("pcmC",0,0,[fe(r),fe(8*e)])},zf=n=>{let t=Oa(n.info.firstPacket.data);if(!t)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).");let e=new Uint8Array(3),r=new H(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),N("dac3",[...e])},Nf=n=>{let t=Da(n.info.firstPacket.data);if(!t)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 e=16;for(let s of t.substreams)e+=23,s.numDepSub>0?e+=9:e+=1;let r=Math.ceil(e/8),i=new Uint8Array(r),a=new H(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let s of t.substreams)a.writeBits(2,s.fscod),a.writeBits(5,s.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,s.bsmod),a.writeBits(3,s.acmod),a.writeBits(1,s.lfeon),a.writeBits(3,0),a.writeBits(4,s.numDepSub),s.numDepSub>0?a.writeBits(9,s.chanLoc):a.writeBits(1,0);return N("dec3",[...i])},Lf=(n,t)=>N(n,[Array(6).fill(0),W(1)],[fp[t.track.source._codec](t)]),Wf=n=>N("vttC",[...$.encode(n.info.config.description)]);var Hf=n=>Y("stts",0,0,[_(n.timeToSampleTable.length),n.timeToSampleTable.map(t=>[_(t.sampleCount),_(t.sampleDelta)])]),qf=n=>{if(n.samples.every(e=>e.type==="key"))return null;let t=[...n.samples.entries()].filter(([,e])=>e.type==="key");return Y("stss",0,0,[_(t.length),t.map(([e])=>_(e+1))])},Kf=n=>Y("stsc",0,0,[_(n.compactlyCodedChunkTable.length),n.compactlyCodedChunkTable.map(t=>[_(t.firstChunk),_(t.samplesPerChunk),_(1)])]),Gf=n=>{if(n.type==="audio"&&n.info.requiresPcmTransformation){let{sampleSize:t}=Ae(n.track.source._codec);return Y("stsz",0,0,[_(t*n.info.numberOfChannels),_(n.samples.reduce((e,r)=>e+ue(r.duration,n.timescale),0))])}return Y("stsz",0,0,[_(0),_(n.samples.length),n.samples.map(t=>_(t.size))])},Qf=n=>n.finalizedChunks.length>0&&X(n.finalizedChunks).offset>=2**32?Y("co64",0,0,[_(n.finalizedChunks.length),n.finalizedChunks.map(t=>Mt(t.offset))]):Y("stco",0,0,[_(n.finalizedChunks.length),n.finalizedChunks.map(t=>_(t.offset))]),jf=n=>Y("ctts",1,0,[_(n.compositionTimeOffsetTable.length),n.compositionTimeOffsetTable.map(t=>[_(t.sampleCount),ar(t.sampleCompositionTimeOffset)])]),Xf=n=>{let t=1/0,e=-1/0,r=1/0,i=-1/0;p(n.compositionTimeOffsetTable.length>0),p(n.samples.length>0);for(let s=0;s<n.compositionTimeOffsetTable.length;s++){let o=n.compositionTimeOffsetTable[s];t=Math.min(t,o.sampleCompositionTimeOffset),e=Math.max(e,o.sampleCompositionTimeOffset)}for(let s=0;s<n.samples.length;s++){let o=n.samples[s];r=Math.min(r,ue(o.timestamp,n.timescale)),i=Math.max(i,ue(o.timestamp+o.duration,n.timescale))}let a=Math.max(-t,0);return i>=2**31?null:Y("cslg",0,0,[ar(a),ar(t),ar(e),ar(r),ar(i)])},$f=n=>N("mvex",void 0,n.map(Yf)),Yf=n=>Y("trex",0,0,[_(n.track.id),_(1),_(0),_(0),_(0)]),ru=(n,t)=>N("moof",void 0,[Zf(n),...t.map(Jf)]),Zf=n=>Y("mfhd",0,0,[_(n)]),Vd=n=>{let t=0,e=0,r=0,i=0,a=n.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|i},Jf=n=>N("traf",void 0,[ep(n),tp(n),rp(n)]),ep=n=>{p(n.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=n.currentChunk.samples[1]??n.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Vd(e)};return Y("tfhd",0,t,[_(n.track.id),_(r.duration),_(r.size),_(r.flags)])},tp=n=>(p(n.currentChunk),Y("tfdt",1,0,[Mt(ue(n.currentChunk.startTimestamp,n.timescale))])),rp=n=>{p(n.currentChunk);let t=n.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),e=n.currentChunk.samples.map(b=>b.size),r=n.currentChunk.samples.map(Vd),i=n.currentChunk.samples.map(b=>ue(b.timestamp-b.decodeTimestamp,n.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(i),u=o.size===2&&r[0]!==r[1],l=a.size>1,m=s.size>1,d=!u&&o.size>1,f=c.size>1||[...c].some(b=>b!==0),h=0;return h|=1,h|=4*+u,h|=256*+l,h|=512*+m,h|=1024*+d,h|=2048*+f,Y("trun",1,h,[_(n.currentChunk.samples.length),_(n.currentChunk.offset-n.currentChunk.moofOffset||0),u?_(r[0]):[],n.currentChunk.samples.map((b,g)=>[l?_(t[g]):[],m?_(e[g]):[],d?_(r[g]):[],f?ar(i[g]):[]])])},Ud=n=>N("mfra",void 0,[...n.map(ip),np()]),ip=(n,t)=>Y("tfra",1,0,[_(n.track.id),_(63),_(n.finalizedChunks.length),n.finalizedChunks.map(r=>[Mt(ue(r.samples[0].timestamp,n.timescale)),Mt(r.moofOffset),_(t+1),_(1),_(1)])]),np=()=>Y("mfro",0,0,[_(0)]),zd=()=>N("vtte"),Nd=(n,t,e,r,i)=>N("vttc",void 0,[i!==null?N("vsid",[ar(i)]):null,e!==null?N("iden",[...$.encode(e)]):null,t!==null?N("ctim",[...$.encode(ro(t))]):null,r!==null?N("sttg",[...$.encode(r)]):null,N("payl",[...$.encode(n)])]),Ld=n=>N("vtta",[...$.encode(n)]),ap=n=>{let t=[],e=n.format._options.metadataFormat??"auto",r=n.output._metadataTags;if(e==="mdir"||e==="auto"&&!n.isQuickTime){let i=op(r);i&&t.push(i)}else if(e==="mdta"){let i=cp(r);i&&t.push(i)}else(e==="udta"||e==="auto"&&n.isQuickTime)&&sp(t,n.output._metadataTags);return t.length===0?null:N("udta",void 0,t)},sp=(n,t)=>{for(let{key:e,value:r}of at(t))switch(e){case"title":n.push(Ft("\xA9nam",r));break;case"description":n.push(Ft("\xA9des",r));break;case"artist":n.push(Ft("\xA9ART",r));break;case"album":n.push(Ft("\xA9alb",r));break;case"albumArtist":n.push(Ft("albr",r));break;case"genre":n.push(Ft("\xA9gen",r));break;case"date":n.push(Ft("\xA9day",r.toISOString().slice(0,10)));break;case"comment":n.push(Ft("\xA9cmt",r));break;case"lyrics":n.push(Ft("\xA9lyr",r));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ae(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||n.some(i=>i.type===e)||(typeof r=="string"?n.push(Ft(e,r)):r instanceof Uint8Array&&n.push(N(e,Array.from(r))))}},Ft=(n,t)=>{let e=$.encode(t);return N(n,[W(e.length),W(qd("und")),Array.from(e)])},vd={"image/jpeg":13,"image/png":14,"image/bmp":27},Wd=(n,t)=>{let e=[];for(let{key:r,value:i}of at(n))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:yt(i)});break;case"description":e.push({key:t?"description":"\xA9des",value:yt(i)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:yt(i)});break;case"album":e.push({key:t?"album":"\xA9alb",value:yt(i)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:yt(i)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:yt(i)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:yt(i)});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:yt(i)});break;case"date":e.push({key:t?"date":"\xA9day",value:yt(i.toISOString().slice(0,10))});break;case"images":for(let a of i)a.kind==="coverFront"&&e.push({key:"covr",value:N("data",[_(vd[a.mimeType]??0),_(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=n.tracksTotal!==void 0?`${i}/${n.tracksTotal}`:i.toString();e.push({key:"track",value:yt(a)})}else e.push({key:"trkn",value:N("data",[_(0),_(0),W(0),W(i),W(n.tracksTotal??0),W(0)])});break;case"discNumber":t||e.push({key:"disc",value:N("data",[_(0),_(0),W(0),W(i),W(n.discsTotal??0),W(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(r)}if(n.raw)for(let r in n.raw){let i=n.raw[r];i==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof i=="string"?e.push({key:r,value:yt(i)}):i instanceof Uint8Array?e.push({key:r,value:N("data",[_(0),_(0),Array.from(i)])}):i instanceof He&&e.push({key:r,value:N("data",[_(vd[i.mimeType]??0),_(0),Array.from(i.data)])}))}return e},op=n=>{let t=Wd(n,!1);return t.length===0?null:Y("meta",0,0,void 0,[tu(!1,"mdir","","appl"),N("ilst",void 0,t.map(e=>N(e.key,void 0,[e.value])))])},cp=n=>{let t=Wd(n,!0);return t.length===0?null:N("meta",void 0,[tu(!1,"mdta",""),Y("keys",0,0,[_(t.length)],t.map(e=>N("mdta",[...$.encode(e.key)]))),N("ilst",void 0,t.map((e,r)=>{let i=String.fromCharCode(..._(r+1));return N(i,void 0,[e.value])}))])},yt=n=>N("data",[_(1),_(0),...$.encode(n)]),up=(n,t)=>{switch(n){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},lp={avc:Rf,hevc:Ff,vp8:Ed,vp9:Ed,av1:Mf},Hd=(n,t)=>{switch(n){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(t)switch(n){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(n){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"}},dp=(n,t)=>{switch(n){case"aac":return Yc;case"mp3":return Yc;case"opus":return Vf;case"vorbis":return Yc;case"flac":return Uf;case"ac3":return zf;case"eac3":return Nf}if(t)switch(n){case"pcm-s24":return Mr;case"pcm-s24be":return Mr;case"pcm-s32":return Mr;case"pcm-s32be":return Mr;case"pcm-f32":return Mr;case"pcm-f32be":return Mr;case"pcm-f64":return Mr;case"pcm-f64be":return Mr}else switch(n){case"pcm-s16":return Rt;case"pcm-s16be":return Rt;case"pcm-s24":return Rt;case"pcm-s24be":return Rt;case"pcm-s32":return Rt;case"pcm-s32be":return Rt;case"pcm-f32":return Rt;case"pcm-f32be":return Rt;case"pcm-f64":return Rt;case"pcm-f64be":return Rt}return null},mp={webvtt:"wvtt"},fp={webvtt:Wf},qd=n=>{p(n.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=n.charCodeAt(e)-96;return t};var Bt=class{constructor(t,e){this.finalized=!1;this.started=!1;this.pos=0;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1;if(t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){p(!this.started),this.target._start(),this.started=!0}write(t){p(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}let r=e+t.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<r;)i*=2;if(i!==this.trackedWrites.byteLength){let a=new Uint8Array(i);a.set(this.trackedWrites,0),this.trackedWrites=a}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.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.");let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};var Gd=yu(xc(),1);var Qd=typeof Gd<"u"?Gd:void 0,Pe=class extends je{constructor(){super(...arguments);this._writerAcquired=!1;this._monotonicity=null;this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,r){this.onwrite?.(e,r),this._emit("write",{start:e,end:r})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new ia(this,e)}},iu=2**16,nu=2**32,Br=class extends Pe{constructor(e={}){super();this.buffer=null;this._maxPos=0;if(!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(iu,{maxByteLength:nu})}catch{this._buffer=new ArrayBuffer(iu),this._supportsResize=!1}else this._buffer=new ArrayBuffer(iu);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>nu)throw new Error(`ArrayBuffer exceeded maximum size of ${nu} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let i=new ArrayBuffer(r),a=new Uint8Array(i);a.set(this._bytes,0),this._buffer=i,this._bytes=a}}}_start(){}_write(e,r){this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return this._bytes.slice(e,r)}},pp=2**24,hp=2,rn=class extends Pe{constructor(e,r={}){super();this._sections=[];this._lastWriteEnd=0;this._lastFlushEnd=0;this._streamWriter=null;this._writeError=null;this._chunks=[];if(!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??pp}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let i=r-this._lastWriteEnd;this._write(new Uint8Array(i),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(p(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((i,a)=>i.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let i=1;i<r.length;i++){let a=e[e.length-1],s=r[i];s.start<=a.start+a.size?a.size=Math.max(a.size,s.start+s.data.byteLength-a.start):e.push({start:s.start,size:s.data.byteLength})}for(let i of e){i.data=new Uint8Array(i.size);for(let a of this._sections)i.start<=a.start&&a.start<i.start+i.size&&i.data.set(a.data,a.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(a=>{this._writeError??=a}),this._lastFlushEnd=i.start+i.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){let i=this._chunks.findIndex(u=>u.start<=r&&r<u.start+this._chunkSize);i===-1&&(i=this._createChunk(r));let a=this._chunks[i],s=r-a.start,o=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));a.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this._insertSectionIntoChunk(a,c),a.written[0].start===0&&a.written[0].end===this._chunkSize&&(a.shouldFlush=!0),this._chunks.length>hp){for(let u=0;u<this._chunks.length-1;u++)this._chunks[u].shouldFlush=!0;this._tryToFlushChunks()}o.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(o.byteLength),r+o.byteLength)}_insertSectionIntoChunk(e,r){let i=0,a=e.written.length-1,s=-1;for(;i<=a;){let o=Math.floor(i+(a-i+1)/2);e.written[o].start<=r.start?(i=o+1,s=o):a=o-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let 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((a,s)=>a.start-s.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){p(this._streamWriter);for(let r=0;r<this._chunks.length;r++){let i=this._chunks[r];if(!(!i.shouldFlush&&!e)){for(let a of i.written){let s=i.start+a.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data.subarray(a.start,a.end),position:s}).catch(o=>{this._writeError??=o}),this._lastFlushEnd=i.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;p(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}},no=class extends Pe{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new rn(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:r=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return p(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,p(this._writer),this._writer.write(r.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},ao=class extends Pe{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Qd.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let i=new WritableStream({start:async()=>{this._fileHandle=await Qd.fs.open(e,"w")},write:async a=>{p(this._fileHandle),await this._fileHandle.write(a.data,0,a.data.byteLength,a.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new rn(i,{chunked:!0,...r})}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+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)}},Or=class extends Pe{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},ia=class extends Pe{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},Ne=class{constructor(t,e){this.rootPath=t;this.getTarget=e;if(typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}};var Ze=57600,gp=2082844800,Kd=n=>{let t={},e=n.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},ue=(n,t,e=!0)=>{let r=n*t;return e?Math.round(r):r},so=class extends we{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new Br;this.auxWriter=new Bt(this.auxTarget,!1);this.auxBoxWriter=new ai(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=J();this.creationTime=Math.floor(Date.now()/1e3)+gp;this.finalizedChunks=[];this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.minWrittenTimestamp=1/0;this.maxWrittenEndTimestamp=-1/0;this.segmentHeaderSize=null;this.format=r,this.isQuickTime=r instanceof oi,this.isCmaf=r instanceof si,this.minimumFragmentDuration=r._options.minimumFragmentDuration??(r instanceof si?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(i=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":i instanceof Br),this.boxWriter=new ai(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Br?"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.");let i=await this.output._getInitTarget(),a=new Bt(i,!0);a.start(),this.initWriter=a,this.initBoxWriter=new ai(a)}let r=this.output._tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{let i=this.initBoxWriter??this.boxWriter;if(p(i),this.format._options.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Od({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:a,start:s}=i.writer.stopTrackingWrites();this.format._options.onFtyp(a,s)}this.ftypSize=i.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(p(this.writer),p(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ra(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return za({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){let a=this.trackDatas.find(f=>f.track===e);if(a)return a;pr(i),p(i),p(i.decoderConfig);let s={...i.decoderConfig};p(s.codedWidth!==void 0),p(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){let f=Ai(r.data);if(!f)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=nl(f),o=!0}else if(e.source._codec==="hevc"&&!s.description){let f=xi(r.data);if(!f)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=sl(f),o=!0}let c=Mu(1/(e.metadata.frameRate??Ze),1e6).denominator,u=s.displayAspectWidth,l=s.displayAspectHeight,m=u===void 0||l===void 0?{num:1,den:1}:Ht({num:u*s.codedHeight,den:l*s.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:m,decoderConfig:s,requiresAnnexBTransformation:o},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((f,h)=>f.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r,i){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;_e(i),p(i),p(i.decoderConfig);let s={...i.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){let u=Ue(ye.tempFromBytes(r.data));if(!u)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.");let l=Xe[u.samplingFrequencyIndex],m=Ct[u.channelConfiguration];if(l===void 0||m===void 0)throw new Error("Invalid ADTS frame header.");s.description=ki({objectType:u.objectType,sampleRate:l,numberOfChannels:m}),o=!0}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&te.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let i=this.trackDatas.find(s=>s.track===e);if(i)return i;xa(r),p(r),p(r.config);let a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,i),o=r.data;if(s.info.requiresAnnexBTransformation){let u=[...br(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(u.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.");o=_a(u,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,i),o=r.data;if(s.info.requiresAdtsStripping){let m=Ue(ye.tempFromBytes(o));if(!m)throw new Error("Expected ADTS frame, didn't get one.");let d=m.crcCheck===null?rr:Ke;o=o.subarray(d)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=r.timestamp,u=r.duration;if(s.info.requiresPcmTransformation){let d=Ae(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(u=o.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let f=c-s.info.expectedNextPcmPacketTimestamp;if(f<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let h=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+h}}s.info.expectedNextPcmPacketTimestamp=c+u}let l=this.createSampleForTrack(s,o,c,u,r.type);await this.registerSample(s,l)}finally{a()}}async padWithSilence(e,r,i){let a=ue(i,e.timescale);if(i=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Ae(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(s*c).fill(o),l=this.createSampleForTrack(e,new Uint8Array(u.buffer),r,i,"key");await this.registerSample(e,l)}return i}async addSubtitleCue(e,r,i){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){let i=new Set([]);for(let l of e.cueQueue)p(l.timestamp<=r),p(e.lastCueEndTimestamp<=l.timestamp+l.duration),i.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),i.add(l.timestamp+l.duration);let a=[...i].sort((l,m)=>l-m),s=a[0],o=a[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=zd();this.auxBoxWriter.writeBox(l);let m=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,m,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let m=e.cueQueue[l];if(m.timestamp>=o)break;en.lastIndex=0;let d=en.test(m.text),f=m.timestamp+m.duration,h=e.cueToSourceId.get(m);if(h===void 0&&o<f&&(h=e.nextSourceId++,e.cueToSourceId.set(m,h)),m.notes){let g=Ld(m.notes);this.auxBoxWriter.writeBox(g)}let b=Nd(m.text,d?s:null,m.identifier??null,m.settings??null,h??null);this.auxBoxWriter.writeBox(b),f===o&&e.cueQueue.splice(l--,1)}let c=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,c,s,o-s,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,i,a,s){return{timestamp:i,decodeTimestamp:i,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:ue(a,e.timescale)}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let a=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s],c=ue(o.duration,e.timescale);a+=c}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:a,sampleDelta:1});else{let s=X(e.timeToSampleTable);s.sampleCount+=a}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);this.isFragmented||(e.startTimestampOffset??=i[0]);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];s.decodeTimestamp=i[a];let o=ue(s.timestamp-s.decodeTimestamp,e.timescale),c=ue(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);let u=ue(s.decodeTimestamp,e.timescale,!1),l=Math.round(u-e.lastTimescaleUnits);if(p(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let m=X(e.timeToSampleTable);if(p(m),m.sampleCount===1){m.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),m=f)}else m.sampleDelta!==l&&(m.sampleCount--,e.timeToSampleTable.push(m={sampleCount:1,sampleDelta:l}));m.sampleDelta===c?m.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let d=X(e.compositionTimeOffsetTable);p(d),d.sampleCompositionTimeOffset===o?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=ue(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,p(e.lastSample),p(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(r.type==="key");let a=ue(r.timestamp,e.timescale,!1),s=Math.round(a-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let a=e.track.metadata.maximumPacketCount;if(p(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). 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,r.timestamp);let a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=a>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),p(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(p(!this.isFragmented),p(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((i,a)=>i+ue(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||X(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let i of e.currentChunk.samples)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(r=s,i=s.sampleQueue[0].timestamp)}if(!r)break;let a=r.sampleQueue.shift();await this.addSampleToTrack(r,a)}}async finalizeFragment(e=!this.isCmaf){p(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){let h=this.initBoxWriter??this.boxWriter;p(h),this.format._options.onMoov&&h.writer.startTrackingWrites();let b=tn(this);if(h.writeBox(b),this.format._options.onMoov){let{data:g,start:y}=h.writer.stopTrackingWrites();this.format._options.onMoov(g,y)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new ai(this.writer);let g=this.boxWriter.measureBox(Jc()),y=this.boxWriter.measureBox(eu(this,0));this.segmentHeaderSize=g+y,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(this.boxWriter);let i=this.trackDatas.filter(h=>h.currentChunk),a=ru(r,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+ut,u=1/0;for(let h of i){h.currentChunk.offset=c,h.currentChunk.moofOffset=s;for(let b of h.currentChunk.samples)c+=b.size;u=Math.min(u,h.currentChunk.startTimestamp)}let l=c-o,m=l>=2**32;if(m)for(let h of i)h.currentChunk.offset+=Xt-ut;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=ru(r,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:h,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,b,u)}p(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=ra(m);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(m?Xt:ut));for(let h of i)for(let b of h.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.format._options.onMdat){let{data:h,start:b}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,b)}for(let h of i)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(p(this.writer),p(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){let i=tn(this),s=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ra(!0),this.boxWriter.writeBox(this.mdat);for(let o of this.trackDatas){for(let c of o.sampleQueue)await this.addSampleToTrack(o,c);o.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){p(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let i=r.track.metadata.maximumPacketCount;p(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0,i.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas){await this.finalizeCurrentChunk(r),p(r.startTimestampOffset!==null);for(let i=0;i<r.samples.length;i++){let a=r.samples[i];a.timestamp-=r.startTimestampOffset,a.decodeTimestamp-=r.startTimestampOffset}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=ra(!1);let r;for(let a=0;a<2;a++){let s=tn(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+o+r;for(let u of this.finalizedChunks){u.offset=c;for(let{data:l}of u.samples)p(l),c+=l.byteLength,r+=l.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let i=tn(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onMoov(a,s)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let a of this.finalizedChunks)for(let s of a.samples)p(s.data),this.writer.write(s.data),s.data=null;if(this.format._options.onMdat){let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onMdat(a,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Jc()),this.boxWriter.writeBox(eu(this,r))}else{let r=this.writer.getPos(),i=Ud(this.trackDatas);this.boxWriter.writeBox(i);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{p(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);p(r!==void 0);let i=this.writer.getPos()-r;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}let a=tn(this);if(this.fastStart==="reserve"){p(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Dd(s))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.format._options.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}}e()}};var bp=-(2**15),yp=2**15-1,jd="Mediabunny",Xd=6,$d=5,kp={video:1,audio:2,subtitle:17},oo=class extends we{constructor(e,r){super(e);this.trackDatas=[];this.allTracksKnown=J();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.startTimestamp=1/0;this.endTimestamp=-1/0;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Xa(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof ci?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),c={id:290298740,data:[{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:i},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:o},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=c}createSegmentInfo(){let e={id:17545,data:new Ri(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:jd},{id:22337,data:jd},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let i=Me[r.track.source._codec];p(i);let a=0;if(r.type==="audio"&&r.track.source._codec==="opus"){a=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=j(s),c=yr(o);a=Math.round(1e9*(c.preSkip/ot))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:kp[r.type]},r.track.metadata.disposition?.default===!1?{id:136,data:0}:null,r.track.metadata.disposition?.forced?{id:21930,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,r.track.metadata.disposition?.original?{id:21934,data:1}:null,r.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??ee},{id:134,data:i},{id:22186,data:0},{id:22203,data:a},r.track.metadata.name!==void 0?{id:21358,data:new ft(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,rotation:i}=e.track.metadata,a=[e.info.decoderConfig.description?{id:25506,data:j(e.info.decoderConfig.description)}:null,r?{id:2352003,data:1e9/r}:null],s=i?Tt(-i):0,o=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,c=e.info.decoderConfig.colorSpace,u={id:224,data:[{id:176,data:e.info.width},{id:186,data:e.info.height},o?{id:21680,data:e.info.aspectRatio.num}:null,o?{id:21690,data:e.info.aspectRatio.den}:null,o?{id:21682,data:3}:null,e.info.alphaMode?{id:21440,data:1}:null,fa(c)?{id:21936,data:[{id:21937,data:nt[c.matrix]},{id:21946,data:it[c.transfer]},{id:21947,data:rt[c.primaries]},{id:21945,data:c.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new _i((s+180)%360-180)}]}:null]};return a.push(u),a}audioSpecificTrackInfo(e){let r=te.includes(e.track.source._codec)?Ae(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:25506,data:j(e.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new _i(e.info.sampleRate)},{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:25506,data:$.encode(e.info.config.description)}]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new ft(s)},typeof o=="string"?{id:17543,data:new ft(o)}:{id:17541,data:o}]})},i=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of at(i))switch(s){case"title":r("TITLE",o),a.add("TITLE");break;case"description":r("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":r("ARTIST",o),a.add("ARTIST");break;case"album":r("ALBUM",o),a.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":r("GENRE",o),a.add("GENRE");break;case"comment":r("COMMENT",o),a.add("COMMENT");break;case"lyrics":r("LYRICS",o),a.add("LYRICS");break;case"date":r("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":{let c=i.tracksTotal!==void 0?`${o}/${i.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=i.discsTotal!==void 0?`${o}/${i.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ae(s)}if(i.raw)for(let s in i.raw){let o=i.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&r(s,o)}e.length!==0&&(this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],i=new Set,a=e.images??[];for(let s of a){let o=s.name;o===void 0&&(o=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(Ou(s.mimeType)??""));let c;for(;;){c=0n;for(let u=0;u<8;u++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!i.has(c))break}i.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new ft(s.description)}:null,{id:18030,data:new ft(o)},{id:18016,data:s.mimeType},{id:18012,data:s.data},{id:18094,data:c}]})}for(let[s,o]of Object.entries(e.raw??{}))!(o instanceof Kt)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&ga(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new ft(o.description)}:null,{id:18030,data:new ft(o.name??"")},{id:18016,data:o.mimeType??""},{id:18012,data:o.data},{id:18094,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:423732329,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:408125543,size:this.format._options.appendOnly?-1:Xd,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){let{data:r,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,i)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return p(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ja({isWebM:this.format instanceof ci,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,i){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;pr(i),p(i),p(i.decoderConfig),p(i.decoderConfig.codedWidth!==void 0),p(i.decoderConfig.codedHeight!==void 0);let s=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:Ht({num:s,den:o}),u={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:i.decoderConfig,alphaMode:!!r.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec==="vp9"?u.info.decoderConfig={...u.info.decoderConfig,description:new Uint8Array(Qu(u.info.decoderConfig.codec))}:e.source._codec==="av1"&&(u.info.decoderConfig={...u.info.decoderConfig,description:new Uint8Array(Sa(u.info.decoderConfig.codec))}),this.trackDatas.push(u),this.trackDatas.sort((l,m)=>l.track.id-m.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r,i){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;_e(i),p(i),p(i.decoderConfig);let s={...i.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){let u=Ue(ye.tempFromBytes(r.data));if(!u)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.");let l=Xe[u.samplingFrequencyIndex],m=Ct[u.channelConfiguration];if(l===void 0||m===void 0)throw new Error("Invalid ADTS frame header.");s.description=ki({objectType:u.objectType,sampleRate:l,numberOfChannels:m}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let i=this.trackDatas.find(s=>s.track===e);if(i)return i;xa(r),p(r),p(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,i),o=r.type==="key";this.validateTimestamp(s.track,r.timestamp,o);let c=r.timestamp,u=r.duration;e.metadata.frameRate!==void 0&&(c=St(c,e.metadata.frameRate),u=St(u,e.metadata.frameRate));let l=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(r.data,c,u,r.type,l);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,m),s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,i),o=r.data;if(s.info.requiresAdtsStripping){let l=Ue(ye.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let m=l.crcCheck===null?rr:Ke;o=o.subarray(m)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=this.createInternalChunk(o,r.timestamp,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,r,i){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);en.lastIndex=0,o=o.replace(en,d=>{let h=to(d.slice(1,-1))-c;return`<${ro(h)}>`});let u=$.encode(o),l=`${r.settings??""}
38
38
  ${r.identifier??""}
39
- ${r.notes??""}`,m=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?$.encode(l):null);s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<i&&(r=s,i=s.chunkQueue[0].timestamp)}if(!r)break;let a=r.chunkQueue.shift();this.writeBlock(r,a)}e||await this.writer.flush()}}fixVP9ColorSpace(e,r){if(r.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let i=new H(r.data);i.skipBits(2);let a=i.readBits(1),o=(i.readBits(1)<<1)+a;if(o===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;o>=2&&i.skipBits(1);let m={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];wu(r.data,i.pos,i.pos+3,m)}createInternalChunk(e,r,i,a,s=null){return{data:e,type:a,timestamp:r,duration:i,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let i=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let d=m.chunkQueue[0];return d?d.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{p(this.currentClusterStartMsTimestamp!==null),p(this.currentClusterMaxMsTimestamp!==null);let m=i-this.currentClusterStartMsTimestamp;s=a&&i>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>yp}s&&this.createNewCluster(i);let o=i-this.currentClusterStartMsTimestamp;if(o<bp)return;let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|e.track.id),u.setInt16(1,o,!1);let l=Math.round(1e3*r.duration);if(r.additions){let m={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new Sn(e.lastWrittenMsTimestamp-i)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:r.additions}]}]}:null,l>0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:$d,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(p(this.currentCluster),!this.format._options.appendOnly){let a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,$d),this.writer.seek(s)}if(this.format._options.onCluster){p(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let i=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of i)p(this.cues),this.cues.data.push({id:187,data:[{id:179,data:a},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),p(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,Xd);let i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Ri(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),p(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var co=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,i=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let g=0;g<16;g++){let y=Pa[u+g];if(Ca(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=g;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,m=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=i,this.helper[2]=l,this.helper[3]=m,this.writer.write(this.helper.subarray(0,4));let d=gr(t.mpegVersionId,t.channel);this.writer.seek(e+d),this.writeU32(hr);let f=0;t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writer.write(t.toc??new Uint8Array(100));let h=Pa[u+c],b=Ca(a,t.layer,1e3*h,t.sampleRate,s);this.writer.seek(e+b)}};var uo=class extends we{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new co(this.writer),Gt(this.output._metadataTags)||new Fr(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,r){let i=await this.mutex.acquire();try{let a=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&a){let s=U(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=Gr(o,null).header;if(!c)throw new Error("Invalid MP3 header in sample.");let u=gr(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let l=s.getUint32(u,!1);if(l===hr||l===Si)return}this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,r.timestamp,r.type==="key"),a&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let e=await this.mutex.acquire(),i=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);let a=new Uint8Array(100);for(let s=0;s<100;s++){let o=Math.floor(this.framePositions.length*(s/100)),c=this.framePositions[o]-this.xingFramePos;a[s]=256*(c/i)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=i,this.xingFrameData.toc=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}e()}};var Tp=8192,lo=class extends we{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(ss);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,as({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let i=this.trackDatas.find(o=>o.track===e);if(i)return i;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));p(e.source._codec==="vorbis"||e.source._codec==="opus"),_e(r),p(r),p(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?ot:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(p(r.decoderConfig),e.track.source._codec==="vorbis"){p(r.decoderConfig.description);let i=j(r.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let g=0;for(;;){let y=i[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=y,y<255)return g}},o=s(),c=s();if(i.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=i.subarray(a,a+=o);a+=c;let m=i.subarray(a),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;let f=gn(d,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:m,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});let b=U(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:Ba(m).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let i=j(r.decoderConfig.description),a=new Uint8Array(8),s=U(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=gn(a,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:yr(i).preSkip}}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=ns(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,forcePageFlush:!1}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let i=r.packetQueue.shift();if(this.writePacket(r,i,!1),i.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,i=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples<i&&(r=o,i=o.packetQueue[0].timestampInSamples)}if(!r)break;let a=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,a,s)}e||await this.writer.flush()}writePacket(e,r,i){let a=r.timestampInSamples+r.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){let l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;let m=s<255;if(e.currentLacingValues.length===255){let d=r.data.subarray(o,c);if(o=c,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,i&&m),m)return}if(m)break;s-=255}let u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Tp||r.forcePageFlush)&&this.writePage(e,i)}writePage(e,r){this.pageView.setUint32(0,Cn,!0),this.pageView.setUint8(4,0);let i=0;e.currentPageStartsWithFreshPacket||(i|=1),e.pagesWritten===0&&(i|=2),r&&(i|=4),this.pageView.setUint8(5,i);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Eu(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=is(o);if(this.pageView.setUint32(22,c,!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(o),this.format._options.onPage){let{data:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var wp=0,tm=4096,Yd=256,Sp=224,Zd=192,Jd=new Uint8Array([9,240]),em=new Uint8Array([70,1]),mo=class extends we{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=U(this.packetBuffer);this.allTracksKnown=J();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,ps(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;pr(r),p(r?.decoderConfig);let a=e.source._codec;p(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=Yd+this.trackDatas.length,c=Sp+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;_e(r),p(r?.decoderConfig);let a=e.source._codec;p(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3");let s,o;switch(a){case"aac":s=15,o=Zd+this.audioTrackIndex++;break;case"mp3":s=3,o=Zd+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break}let c=Yd+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,i);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,i);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,i){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=i?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=j(s);a==="avc"?e.avcDecoderConfig=Ra(o):e.hevcDecoderConfig=ol(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let i=[];for(let s of br(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?jt(o[0])===9:ct(o[0])===35)||i.push(o)}let a=r==="avc"?Jd:em;return i.unshift(a),fn(i)}prepareLengthPrefixedVideoPacket(e,r,i){let a=r.data,s=i==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Ea(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(i==="avc"?jt(l[0])===9:ct(l[0])===35)||o.push(l)}if(r.type==="key")if(i==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let m of l.nalUnits)o.unshift(m);for(let l of u.arrays)if(l.nalUnitType===33)for(let m of l.nalUnits)o.unshift(m);for(let l of u.arrays)if(l.nalUnitType===32)for(let m of l.nalUnits)o.unshift(m)}let c=i==="avc"?Jd:em;return o.unshift(c),fn(o)}prepareAudioPacket(e,r,i){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3")return r.data;if(e.inputIsAdts===null){let u=i?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=It(j(u)),m=ka(l);e.adtsHeader=m.header,e.adtsHeaderBitstream=m.bitstream}}if(e.inputIsAdts)return r.data;p(e.adtsHeader),p(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;Ta(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let i=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];s.decodeTimestamp=i[a],e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,r&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!s.closed)break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<i&&(r=s,i=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){p(!this.tablesWritten),this.writePsiSection(wp,ui),this.writePsiSection(tm,xp(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let i=0,a=!0;for(;i<r.length;){let o=184-(a?1:0),c=r.length-i,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(i,i+u),1)):l=r.subarray(i,i+u),this.writeTsPacket(e,a,null,l),i+=u,a=!1}}writePesPacket(e,r){let i=e.track.type==="video",a=i?10:5,s=new Uint8Array(9+a),o=U(s),c=new H(s.subarray(9));Wr(o,0,1,!1),s[3]=e.streamId;let u=e.track.type==="video"?0:Math.min(8+r.data.length,65535);o.setUint16(4,u,!1),o.setUint8(6,132),o.setUint8(7,i?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4);if(c.pos=0,c.writeBits(4,i?3:2),c.writeBits(3,l>>>30&7),c.writeBits(1,1),c.writeBits(15,l>>>15&32767),c.writeBits(1,1),c.writeBits(15,l&32767),c.writeBits(1,1),i){p(r.decodeTimestamp!==null);let h=Math.round(r.decodeTimestamp*9e4);c.writeBits(4,1),c.writeBits(3,h>>>30&7),c.writeBits(1,1),c.writeBits(15,h>>>15&32767),c.writeBits(1,1),c.writeBits(15,h&32767),c.writeBits(1,1)}let m=s.length+r.data.length,d=0,f=!0;for(;d<m;){let h=f,b=m-d,g=f&&r.isKeyframe,y=f&&!e.firstPacketWritten,k=Math.max(0,184-b),T;g||y?T=Math.max(2,k):T=k;let w=null;if(T>0){let I=this.adaptationFieldBuffer;T===1?I[0]=0:(I[0]=T-1,I[1]=Number(y)<<7|Number(g)<<6,I.fill(255,2,T)),w=I.subarray(0,T)}let S=Math.min(184-T,b),x=this.payloadBuffer.subarray(0,S),P=0;if(d<s.length){let I=Math.min(s.length-d,S);x.set(s.subarray(d,d+I),0),P=I}let A=Math.max(0,d-s.length),C=A+(S-P);P<S&&x.set(r.data.subarray(A,C),P),this.writeTsPacket(e.pid,h,w,x),d+=S,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,i,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=i?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let u=4;i&&(this.packetBuffer.set(i,u),u+=i.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0,await this.flushTimestampQueue(i,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},Ap=79764919,rm=new Uint32Array(256);for(let n=0;n<256;n++){let t=n<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Ap:t<<1;rm[n]=t>>>0&4294967295}var im=n=>{let t=4294967295;for(let e=0;e<n.length;e++){let r=n[e];t=(t<<8^rm[t>>>24^r])>>>0}return t},ui=new Uint8Array(16);{let n=U(ui);ui[0]=0,n.setUint16(1,45069,!1),n.setUint16(3,1,!1),ui[5]=193,ui[6]=0,ui[7]=0,n.setUint16(8,1,!1),n.setUint16(10,57344|tm&8191,!1),n.setUint32(12,im(ui.subarray(0,12)),!1)}var xp=n=>{let t=0;for(let c of n)t+=5,c.streamType===129?t+=yn.length:c.streamType===135&&(t+=kn.length);let e=9+t+4,r=new Uint8Array(3+e-4),i=U(r);r[0]=2,i.setUint16(1,45056|e&4095,!1),i.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let a=12;for(let c of n)r[a++]=c.streamType,i.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(i.setUint16(a,61440|yn.length,!1),a+=2,r.set(yn,a),a+=yn.length):c.streamType===135?(i.setUint16(a,61440|kn.length,!1),a+=2,r.set(kn,a),a+=kn.length):(i.setUint16(a,61440,!1),a+=2);let s=im(r),o=new Uint8Array(r.length+4);return o.set(r,0),U(o).setUint32(r.length,s,!1),o};var fo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(new TextEncoder().encode(t))}};var po=class extends we{constructor(e,r){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=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new fo(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{if(this.headerWritten||(_e(i),p(i),p(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.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(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let i,a=e.source._codec,s=Ae(a);s.dataType==="ulaw"?i=7:s.dataType==="alaw"?i=6:s.dataType==="float"?i=3:i=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;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(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!Gt(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:m}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,m)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let i=new Set,a=(c,u)=>{if(!tt(u)){console.warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,m=new Uint8Array(l);for(let d=0;d<u.length;d++)m[d]=u.charCodeAt(d);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(l),this.writer.write(m),l&1&&this.writer.write(new Uint8Array(1)),i.add(c)};for(let{key:c,value:u}of at(e))switch(c){case"title":a("INAM",u),i.add("INAM");break;case"artist":a("IART",u),i.add("IART");break;case"album":a("IPRD",u),i.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),i.add("ITRK")}break;case"genre":a("IGNR",u),i.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":a("ICMT",u),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:ae(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||i.has(c)||typeof u=="string"&&a(c,u)}let s=this.writer.getPos(),o=s-r-8;this.writer.seek(r+4),this.riffWriter.writeU32(o),this.writer.seek(s),o&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let a=new Fr(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(r+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(p(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),p(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),p(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(p(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),p(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}};var nn=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.startTime=t.startTime,this.endTime=t.endTime,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(this.startTime*this.targetSampleRate)}doChannelMixerSetup(){p(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,i)=>r[i*t]:t===1&&e===4?this.channelMixer=(r,i,a)=>r[i*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,i,a)=>r[i*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,i,a)=>r[i*t+a]*+(a<2):t===2&&e===6?this.channelMixer=(r,i,a)=>r[i*t+a]*+(a<2):t===4&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,i,a)=>{let s=i*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,i,a)=>{let s=i*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,i,a)=>{let s=i*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,i,a)=>{let s=i*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,i,a)=>a<t?r[i*t+a]:0}ensureTempBufferSize(t){let e=this.tempSourceBuffer.length;for(;e<t;)e*=2;if(e!==this.tempSourceBuffer.length){let r=new Float32Array(e);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(t){this.sourceSampleRate===null&&(this.sourceSampleRate=t.sampleRate,this.sourceNumberOfChannels=t.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(i,{planeIndex:0,format:"f32"});let a=t.timestamp,s=Math.min(t.timestamp+t.duration,this.endTime),o=Math.floor(a*this.targetSampleRate),c=Math.ceil(s*this.targetSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;p(l<this.bufferSizeInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,h=Math.floor(f),b=Math.ceil(f),g=f-h;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,T=0;h>=0&&h<t.numberOfFrames&&(k=this.channelMixer(i,h,y)),b>=0&&b<t.numberOfFrames&&(T=this.channelMixer(i,b,y));let w=k+g*(T-k),S=l*this.targetNumberOfChannels+y;this.outputBuffer[S]+=w}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;let t=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=this.bufferStartFrame/this.targetSampleRate,i=new Te({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:e});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var li=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},Ot=class extends li{constructor(e){super();this._connectedTrack=null;if(!re.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${re.join(", ")}.`);this._codec=e}},ou=(n,t)=>{if(n.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Dr=class extends Ot{constructor(t){super(t)}add(t,e){if(!(t instanceof Q))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),ou(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},na=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.resizeCanvas=null;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new cr;this.customEncoderQueueSize=0;this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.lastMuxerPromise=Promise.resolve();let r=e.sizeChangeBehavior??"deny";if(["fill","contain","cover"].includes(r)&&e.transform?.fit!==void 0)throw new TypeError(`Cannot set 'fit' when 'sizeChangeBehavior' is '${r}'. The size change behavior determines the fit in this case.`)}async add(t,e,r){let i=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let m=Tt(t.rotation+(a.transform?.rotate??0)),[d,f]=m%180===0?[t.codedWidth,t.codedHeight]:[t.codedHeight,t.codedWidth],h=a.transform?.crop;h&&(h=ri(h,d,f));let b=h?h.width:d,g=h?h.height:f,y=b/g,k,T,w=a.transform?.fit??"fill";o&&s!=="passThrough"?(p(this.outputWidth),p(this.outputHeight),p(s!=="deny"),k=this.outputWidth,T=this.outputHeight,w=s):a.transform?.width!==void 0&&a.transform?.height===void 0?(k=a.transform.width,T=Pt(Math.round(k/y))):a.transform?.width===void 0&&a.transform?.height!==void 0?(T=a.transform.height,k=Pt(Math.round(T*y))):a.transform?.width!==void 0&&a.transform?.height!==void 0?(k=a.transform?.width,T=a.transform?.height):(k=b,T=g),(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=k,this.outputHeight=T);let S=!1;this.resizeCanvas?(this.resizeCanvas.width!==k||this.resizeCanvas.height!==T)&&(this.resizeCanvas.width=k,this.resizeCanvas.height=T):(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=k,this.resizeCanvas.height=T):this.resizeCanvas=new OffscreenCanvas(k,T),S=!0);let x=this.resizeCanvas.getContext("2d",{alpha:this.encodingConfig.alpha==="keep"||xt()});p(x),typeof x.resetTransform=="function"&&x.resetTransform(),S||(xt()?(x.fillStyle="black",x.fillRect(0,0,k,T)):x.clearRect(0,0,k,T)),t.drawWithFit(x,{fit:w,rotation:m,crop:h}),e&&t.close(),t=new me(this.resizeCanvas,{timestamp:t.timestamp,duration:t.duration,rotation:0}),e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let m=t.timestamp+t.duration,d=dr(t.timestamp,l);if(this.frameRateLastSample!==null)if(d<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=m;return}else await this.padFrameRate(d,r);t===i&&(t=t.clone(),e=!0),t.setTimestamp(d),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=d,this.frameRateLastEndTimestamp=m}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,i;if(r.transform?.process){let a=r.transform.process(t);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]),i=a.map(s=>s instanceof me?s:typeof VideoFrame<"u"&&s instanceof VideoFrame?new me(s):new me(s,{timestamp:t.timestamp,duration:t.duration}))}else i=[t];try{for(let a of i){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized);let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...e,keyFrame:e?.keyFrame||s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.customEncoder){this.customEncoderQueueSize++;let u=a.clone(),l=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,c)).then(()=>this.customEncoderQueueSize--).catch(m=>this.error??=m).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await l}else{p(this.encoder);let u=a.toVideoFrame(),l=q(this.preciseTimings,u.timestamp,d=>d.microsecondTimestamp),m=l!==-1?this.preciseTimings[l]:null;if(m&&m.microsecondTimestamp===u.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(l+1,0,{microsecondTimestamp:u.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,c),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,c),u.close();else{let f=u.displayWidth,h=u.displayHeight;if(!this.splitter)try{this.splitter=new cu(f,h)}catch(b){console.error("Due to an error, only color data will be encoded.",b),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(u,c),u.close()}if(this.splitter){let b=this.splitter.extractColor(u),g=this.splitter.extractAlpha(u);this.alphaFrameQueue.push(g),this.encoder.encode(b,c),b.close(),u.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(d=>this.encoder.addEventListener("dequeue",d,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of i)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);let i=Math.round((t-this.frameRateLastTimestamp)*r);for(let a=1;a<i;a++){let s=this.frameRateLastSample.clone();s.setTimestamp(this.frameRateLastTimestamp+a/r),s.setDuration(1/r),await this.processAndEncode(s,e),s.close()}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=Vc({...this.encodingConfig,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(e);let r=Gi.find(i=>i.supports(this.encodingConfig.codec,e));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(i,a)=>{if(!(i instanceof Q))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");ou(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,a),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,a).catch(s=>{this.error??=s})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(e.alpha="discard",this.encodingConfig.alpha==="keep"&&(e.latencyMode="quality"),(e.width%2===1||e.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(e)).supported)throw new Error(`This specific encoder configuration (${e.codec}, ${e.bitrate} bps, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let s=[],o=[],c=0,u=0,l=(d,f,h)=>{let b={};if(f){let T=new Uint8Array(f.byteLength);f.copyTo(T),b.alpha=T}let g=Q.fromEncodedChunk(d,b),y=q(this.preciseTimings,d.timestamp,T=>T.microsecondTimestamp),k=y!==-1?this.preciseTimings[y]:null;k&&k.microsecondTimestamp===d.timestamp&&(g=g.clone({timestamp:k.timestampIsValid?k.timestamp:void 0,duration:k.durationIsValid?k.duration:void 0})),ou(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,h),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,h).catch(T=>{this.error??=T})},m=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(d,f)=>{if(!this.alphaEncoder){l(d,null,f);return}let h=this.alphaFrameQueue.shift();p(h!==void 0),h?(this.alphaEncoder.encode(h,{keyFrame:d.type==="key"}),u++,h.close(),s.push({chunk:d,meta:f})):u===0?l(d,null,f):(o.push(c+u),s.push({chunk:d,meta:f}))},error:d=>{d.stack=m,this.error??=d}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){let d=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,h)=>{u--;let b=s.shift();for(p(b!==void 0),l(b.chunk,f,b.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=s.shift();p(g!==void 0),l(g.chunk,null,g.meta)}},error:f=>{f.stack=d,this.error??=f}}),this.alphaEncoder.configure(e)}}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(t){if(t||this.checkForEncoderError(),!t&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,r=dr(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},cu=class{constructor(t,e){this.lastFrame=null;typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(t,e):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e);let r=this.canvas.getContext("webgl2",{alpha:!0});if(!r)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=r,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
39
+ ${r.notes??""}`,m=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?$.encode(l):null);s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<i&&(r=s,i=s.chunkQueue[0].timestamp)}if(!r)break;let a=r.chunkQueue.shift();this.writeBlock(r,a)}e||await this.writer.flush()}}fixVP9ColorSpace(e,r){if(r.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let i=new H(r.data);i.skipBits(2);let a=i.readBits(1),o=(i.readBits(1)<<1)+a;if(o===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;o>=2&&i.skipBits(1);let m={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];wu(r.data,i.pos,i.pos+3,m)}createInternalChunk(e,r,i,a,s=null){return{data:e,type:a,timestamp:r,duration:i,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let i=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let d=m.chunkQueue[0];return d?d.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{p(this.currentClusterStartMsTimestamp!==null),p(this.currentClusterMaxMsTimestamp!==null);let m=i-this.currentClusterStartMsTimestamp;s=a&&i>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>yp}s&&this.createNewCluster(i);let o=i-this.currentClusterStartMsTimestamp;if(o<bp)return;let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|e.track.id),u.setInt16(1,o,!1);let l=Math.round(1e3*r.duration);if(r.additions){let m={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new Sn(e.lastWrittenMsTimestamp-i)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:r.additions}]}]}:null,l>0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:$d,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(p(this.currentCluster),!this.format._options.appendOnly){let a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,$d),this.writer.seek(s)}if(this.format._options.onCluster){p(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let i=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of i)p(this.cues),this.cues.data.push({id:187,data:[{id:179,data:a},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),p(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,Xd);let i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Ri(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),p(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var co=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,i=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let g=0;g<16;g++){let y=Pa[u+g];if(Ca(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=g;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,m=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=i,this.helper[2]=l,this.helper[3]=m,this.writer.write(this.helper.subarray(0,4));let d=gr(t.mpegVersionId,t.channel);this.writer.seek(e+d),this.writeU32(hr);let f=0;t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writer.write(t.toc??new Uint8Array(100));let h=Pa[u+c],b=Ca(a,t.layer,1e3*h,t.sampleRate,s);this.writer.seek(e+b)}};var uo=class extends we{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new co(this.writer),Gt(this.output._metadataTags)||new Fr(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,r){let i=await this.mutex.acquire();try{let a=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&a){let s=U(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=Gr(o,null).header;if(!c)throw new Error("Invalid MP3 header in sample.");let u=gr(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let l=s.getUint32(u,!1);if(l===hr||l===Si)return}this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,r.timestamp,r.type==="key"),a&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let e=await this.mutex.acquire(),i=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);let a=new Uint8Array(100);for(let s=0;s<100;s++){let o=Math.floor(this.framePositions.length*(s/100)),c=this.framePositions[o]-this.xingFramePos;a[s]=256*(c/i)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=i,this.xingFrameData.toc=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}e()}};var Tp=8192,lo=class extends we{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(ss);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,as({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let i=this.trackDatas.find(o=>o.track===e);if(i)return i;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));p(e.source._codec==="vorbis"||e.source._codec==="opus"),_e(r),p(r),p(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?ot:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(p(r.decoderConfig),e.track.source._codec==="vorbis"){p(r.decoderConfig.description);let i=j(r.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let g=0;for(;;){let y=i[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=y,y<255)return g}},o=s(),c=s();if(i.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=i.subarray(a,a+=o);a+=c;let m=i.subarray(a),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;let f=gn(d,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:m,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});let b=U(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:Ba(m).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let i=j(r.decoderConfig.description),a=new Uint8Array(8),s=U(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=gn(a,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:yr(i).preSkip}}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=ns(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,forcePageFlush:!1}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let i=r.packetQueue.shift();if(this.writePacket(r,i,!1),i.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,i=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples<i&&(r=o,i=o.packetQueue[0].timestampInSamples)}if(!r)break;let a=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,a,s)}e||await this.writer.flush()}writePacket(e,r,i){let a=r.timestampInSamples+r.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){let l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;let m=s<255;if(e.currentLacingValues.length===255){let d=r.data.subarray(o,c);if(o=c,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,i&&m),m)return}if(m)break;s-=255}let u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Tp||r.forcePageFlush)&&this.writePage(e,i)}writePage(e,r){this.pageView.setUint32(0,Cn,!0),this.pageView.setUint8(4,0);let i=0;e.currentPageStartsWithFreshPacket||(i|=1),e.pagesWritten===0&&(i|=2),r&&(i|=4),this.pageView.setUint8(5,i);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Eu(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=is(o);if(this.pageView.setUint32(22,c,!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(o),this.format._options.onPage){let{data:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var wp=0,tm=4096,Yd=256,Sp=224,Zd=192,Jd=new Uint8Array([9,240]),em=new Uint8Array([70,1]),mo=class extends we{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=U(this.packetBuffer);this.allTracksKnown=J();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,ps(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;pr(r),p(r?.decoderConfig);let a=e.source._codec;p(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=Yd+this.trackDatas.length,c=Sp+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let i=this.trackDatas.find(l=>l.track===e);if(i)return i;_e(r),p(r?.decoderConfig);let a=e.source._codec;p(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3");let s,o;switch(a){case"aac":s=15,o=Zd+this.audioTrackIndex++;break;case"mp3":s=3,o=Zd+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break}let c=Yd+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,i);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,i);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,i);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,i){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=i?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=j(s);a==="avc"?e.avcDecoderConfig=Ra(o):e.hevcDecoderConfig=ol(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let i=[];for(let s of br(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?jt(o[0])===9:ct(o[0])===35)||i.push(o)}let a=r==="avc"?Jd:em;return i.unshift(a),fn(i)}prepareLengthPrefixedVideoPacket(e,r,i){let a=r.data,s=i==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Ea(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(i==="avc"?jt(l[0])===9:ct(l[0])===35)||o.push(l)}if(r.type==="key")if(i==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let m of l.nalUnits)o.unshift(m);for(let l of u.arrays)if(l.nalUnitType===33)for(let m of l.nalUnits)o.unshift(m);for(let l of u.arrays)if(l.nalUnitType===32)for(let m of l.nalUnits)o.unshift(m)}let c=i==="avc"?Jd:em;return o.unshift(c),fn(o)}prepareAudioPacket(e,r,i){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3")return r.data;if(e.inputIsAdts===null){let u=i?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=It(j(u)),m=ka(l);e.adtsHeader=m.header,e.adtsHeaderBitstream=m.bitstream}}if(e.inputIsAdts)return r.data;p(e.adtsHeader),p(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;Ta(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let i=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];s.decodeTimestamp=i[a],e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,r&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let r=null,i=1/0;for(let s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!s.closed)break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<i&&(r=s,i=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){p(!this.tablesWritten),this.writePsiSection(wp,ui),this.writePsiSection(tm,xp(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let i=0,a=!0;for(;i<r.length;){let o=184-(a?1:0),c=r.length-i,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(i,i+u),1)):l=r.subarray(i,i+u),this.writeTsPacket(e,a,null,l),i+=u,a=!1}}writePesPacket(e,r){let i=e.track.type==="video",a=i?10:5,s=new Uint8Array(9+a),o=U(s),c=new H(s.subarray(9));Wr(o,0,1,!1),s[3]=e.streamId;let u=e.track.type==="video"?0:Math.min(8+r.data.length,65535);o.setUint16(4,u,!1),o.setUint8(6,132),o.setUint8(7,i?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4);if(c.pos=0,c.writeBits(4,i?3:2),c.writeBits(3,l>>>30&7),c.writeBits(1,1),c.writeBits(15,l>>>15&32767),c.writeBits(1,1),c.writeBits(15,l&32767),c.writeBits(1,1),i){p(r.decodeTimestamp!==null);let h=Math.round(r.decodeTimestamp*9e4);c.writeBits(4,1),c.writeBits(3,h>>>30&7),c.writeBits(1,1),c.writeBits(15,h>>>15&32767),c.writeBits(1,1),c.writeBits(15,h&32767),c.writeBits(1,1)}let m=s.length+r.data.length,d=0,f=!0;for(;d<m;){let h=f,b=m-d,g=f&&r.isKeyframe,y=f&&!e.firstPacketWritten,k=Math.max(0,184-b),T;g||y?T=Math.max(2,k):T=k;let w=null;if(T>0){let I=this.adaptationFieldBuffer;T===1?I[0]=0:(I[0]=T-1,I[1]=Number(y)<<7|Number(g)<<6,I.fill(255,2,T)),w=I.subarray(0,T)}let S=Math.min(184-T,b),x=this.payloadBuffer.subarray(0,S),P=0;if(d<s.length){let I=Math.min(s.length-d,S);x.set(s.subarray(d,d+I),0),P=I}let A=Math.max(0,d-s.length),C=A+(S-P);P<S&&x.set(r.data.subarray(A,C),P),this.writeTsPacket(e.pid,h,w,x),d+=S,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,i,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=i?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let u=4;i&&(this.packetBuffer.set(i,u),u+=i.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.track===e);i&&(i.closed=!0,await this.flushTimestampQueue(i,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},Ap=79764919,rm=new Uint32Array(256);for(let n=0;n<256;n++){let t=n<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Ap:t<<1;rm[n]=t>>>0&4294967295}var im=n=>{let t=4294967295;for(let e=0;e<n.length;e++){let r=n[e];t=(t<<8^rm[t>>>24^r])>>>0}return t},ui=new Uint8Array(16);{let n=U(ui);ui[0]=0,n.setUint16(1,45069,!1),n.setUint16(3,1,!1),ui[5]=193,ui[6]=0,ui[7]=0,n.setUint16(8,1,!1),n.setUint16(10,57344|tm&8191,!1),n.setUint32(12,im(ui.subarray(0,12)),!1)}var xp=n=>{let t=0;for(let c of n)t+=5,c.streamType===129?t+=yn.length:c.streamType===135&&(t+=kn.length);let e=9+t+4,r=new Uint8Array(3+e-4),i=U(r);r[0]=2,i.setUint16(1,45056|e&4095,!1),i.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let a=12;for(let c of n)r[a++]=c.streamType,i.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(i.setUint16(a,61440|yn.length,!1),a+=2,r.set(yn,a),a+=yn.length):c.streamType===135?(i.setUint16(a,61440|kn.length,!1),a+=2,r.set(kn,a),a+=kn.length):(i.setUint16(a,61440,!1),a+=2);let s=im(r),o=new Uint8Array(r.length+4);return o.set(r,0),U(o).setUint32(r.length,s,!1),o};var fo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(new TextEncoder().encode(t))}};var po=class extends we{constructor(e,r){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=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new fo(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,i){let a=await this.mutex.acquire();try{if(this.headerWritten||(_e(i),p(i),p(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.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(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let i,a=e.source._codec,s=Ae(a);s.dataType==="ulaw"?i=7:s.dataType==="alaw"?i=6:s.dataType==="float"?i=3:i=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;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(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!Gt(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:m}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,m)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let i=new Set,a=(c,u)=>{if(!tt(u)){console.warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,m=new Uint8Array(l);for(let d=0;d<u.length;d++)m[d]=u.charCodeAt(d);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(l),this.writer.write(m),l&1&&this.writer.write(new Uint8Array(1)),i.add(c)};for(let{key:c,value:u}of at(e))switch(c){case"title":a("INAM",u),i.add("INAM");break;case"artist":a("IART",u),i.add("IART");break;case"album":a("IPRD",u),i.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),i.add("ITRK")}break;case"genre":a("IGNR",u),i.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":a("ICMT",u),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:ae(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||i.has(c)||typeof u=="string"&&a(c,u)}let s=this.writer.getPos(),o=s-r-8;this.writer.seek(r+4),this.riffWriter.writeU32(o),this.writer.seek(s),o&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let a=new Fr(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(r+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(p(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),p(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),p(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(p(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),p(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}};var nn=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.endTime=t.endTime,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(t.startTime*this.targetSampleRate),this.timestampOffset=t.startTime-this.bufferStartFrame/this.targetSampleRate}doChannelMixerSetup(){p(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,i)=>r[i*t]:t===1&&e===4?this.channelMixer=(r,i,a)=>r[i*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,i,a)=>r[i*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,i,a)=>r[i*t+a]*+(a<2):t===2&&e===6?this.channelMixer=(r,i,a)=>r[i*t+a]*+(a<2):t===4&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,i,a)=>{let s=i*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,i,a)=>{let s=i*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,i)=>{let a=i*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,i,a)=>{let s=i*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,i,a)=>{let s=i*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,i,a)=>a<t?r[i*t+a]:0}ensureTempBufferSize(t){let e=this.tempSourceBuffer.length;for(;e<t;)e*=2;if(e!==this.tempSourceBuffer.length){let r=new Float32Array(e);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(t){this.sourceSampleRate===null&&(this.sourceSampleRate=t.sampleRate,this.sourceNumberOfChannels=t.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(i,{planeIndex:0,format:"f32"});let a=t.timestamp,s=Math.min(t.timestamp+t.duration,this.endTime),o=Math.floor(a*this.targetSampleRate),c=Math.ceil(s*this.targetSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;p(l<this.bufferSizeInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,h=Math.floor(f),b=Math.ceil(f),g=f-h;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,T=0;h>=0&&h<t.numberOfFrames&&(k=this.channelMixer(i,h,y)),b>=0&&b<t.numberOfFrames&&(T=this.channelMixer(i,b,y));let w=k+g*(T-k),S=l*this.targetNumberOfChannels+y;this.outputBuffer[S]+=w}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;let t=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=this.bufferStartFrame/this.targetSampleRate,i=new Te({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r+this.timestampOffset,data:e});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var li=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},Ot=class extends li{constructor(e){super();this._connectedTrack=null;if(!re.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${re.join(", ")}.`);this._codec=e}},ou=(n,t)=>{if(n.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Dr=class extends Ot{constructor(t){super(t)}add(t,e){if(!(t instanceof Q))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),ou(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},na=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.resizeCanvas=null;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new cr;this.customEncoderQueueSize=0;this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.lastMuxerPromise=Promise.resolve();let r=e.sizeChangeBehavior??"deny";if(["fill","contain","cover"].includes(r)&&e.transform?.fit!==void 0)throw new TypeError(`Cannot set 'fit' when 'sizeChangeBehavior' is '${r}'. The size change behavior determines the fit in this case.`)}async add(t,e,r){let i=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let m=Tt(t.rotation+(a.transform?.rotate??0)),[d,f]=m%180===0?[t.codedWidth,t.codedHeight]:[t.codedHeight,t.codedWidth],h=a.transform?.crop;h&&(h=ri(h,d,f));let b=h?h.width:d,g=h?h.height:f,y=b/g,k,T,w=a.transform?.fit??"fill";o&&s!=="passThrough"?(p(this.outputWidth),p(this.outputHeight),p(s!=="deny"),k=this.outputWidth,T=this.outputHeight,w=s):a.transform?.width!==void 0&&a.transform?.height===void 0?(k=a.transform.width,T=Pt(Math.round(k/y))):a.transform?.width===void 0&&a.transform?.height!==void 0?(T=a.transform.height,k=Pt(Math.round(T*y))):a.transform?.width!==void 0&&a.transform?.height!==void 0?(k=a.transform?.width,T=a.transform?.height):(k=b,T=g),(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=k,this.outputHeight=T);let S=!1;this.resizeCanvas?(this.resizeCanvas.width!==k||this.resizeCanvas.height!==T)&&(this.resizeCanvas.width=k,this.resizeCanvas.height=T):(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=k,this.resizeCanvas.height=T):this.resizeCanvas=new OffscreenCanvas(k,T),S=!0);let x=this.resizeCanvas.getContext("2d",{alpha:this.encodingConfig.alpha==="keep"||xt()});p(x),typeof x.resetTransform=="function"&&x.resetTransform(),S||(xt()?(x.fillStyle="black",x.fillRect(0,0,k,T)):x.clearRect(0,0,k,T)),t.drawWithFit(x,{fit:w,rotation:m,crop:h}),e&&t.close(),t=new me(this.resizeCanvas,{timestamp:t.timestamp,duration:t.duration,rotation:0}),e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let m=t.timestamp+t.duration,d=dr(t.timestamp,l);if(this.frameRateLastSample!==null)if(d<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=m;return}else await this.padFrameRate(d,r);t===i&&(t=t.clone(),e=!0),t.setTimestamp(d),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=d,this.frameRateLastEndTimestamp=m}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,i;if(r.transform?.process){let a=r.transform.process(t);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]),i=a.map(s=>s instanceof me?s:typeof VideoFrame<"u"&&s instanceof VideoFrame?new me(s):new me(s,{timestamp:t.timestamp,duration:t.duration}))}else i=[t];try{for(let a of i){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),p(this.encoderInitialized);let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...e,keyFrame:e?.keyFrame||s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.customEncoder){this.customEncoderQueueSize++;let u=a.clone(),l=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,c)).then(()=>this.customEncoderQueueSize--).catch(m=>this.error??=m).finally(()=>{u.close()});this.customEncoderQueueSize>=4&&await l}else{p(this.encoder);let u=a.toVideoFrame(),l=q(this.preciseTimings,u.timestamp,d=>d.microsecondTimestamp),m=l!==-1?this.preciseTimings[l]:null;if(m&&m.microsecondTimestamp===u.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(l+1,0,{microsecondTimestamp:u.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(u,c),u.close();else if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(u,c),u.close();else{let f=u.displayWidth,h=u.displayHeight;if(!this.splitter)try{this.splitter=new cu(f,h)}catch(b){console.error("Due to an error, only color data will be encoded.",b),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(u,c),u.close()}if(this.splitter){let b=this.splitter.extractColor(u),g=this.splitter.extractAlpha(u);this.alphaFrameQueue.push(g),this.encoder.encode(b,c),b.close(),u.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(d=>this.encoder.addEventListener("dequeue",d,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of i)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;p(this.frameRateLastSample);let i=Math.round((t-this.frameRateLastTimestamp)*r);for(let a=1;a<i;a++){let s=this.frameRateLastSample.clone();s.setTimestamp(this.frameRateLastTimestamp+a/r),s.setDuration(1/r),await this.processAndEncode(s,e),s.close()}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=Vc({...this.encodingConfig,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(e);let r=Gi.find(i=>i.supports(this.encodingConfig.codec,e));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(i,a)=>{if(!(i instanceof Q))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(a!==void 0&&(!a||typeof a!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");ou(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,a),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,a).catch(s=>{this.error??=s})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(e.alpha="discard",this.encodingConfig.alpha==="keep"&&(e.latencyMode="quality"),(e.width%2===1||e.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(e)).supported)throw new Error(`This specific encoder configuration (${e.codec}, ${e.bitrate} bps, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let s=[],o=[],c=0,u=0,l=(d,f,h)=>{let b={};if(f){let T=new Uint8Array(f.byteLength);f.copyTo(T),b.alpha=T}let g=Q.fromEncodedChunk(d,b),y=q(this.preciseTimings,d.timestamp,T=>T.microsecondTimestamp),k=y!==-1?this.preciseTimings[y]:null;k&&k.microsecondTimestamp===d.timestamp&&(g=g.clone({timestamp:k.timestampIsValid?k.timestamp:void 0,duration:k.durationIsValid?k.duration:void 0})),ou(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,h),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,h).catch(T=>{this.error??=T})},m=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(d,f)=>{if(!this.alphaEncoder){l(d,null,f);return}let h=this.alphaFrameQueue.shift();p(h!==void 0),h?(this.alphaEncoder.encode(h,{keyFrame:d.type==="key"}),u++,h.close(),s.push({chunk:d,meta:f})):u===0?l(d,null,f):(o.push(c+u),s.push({chunk:d,meta:f}))},error:d=>{d.stack=m,this.error??=d}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){let d=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,h)=>{u--;let b=s.shift();for(p(b!==void 0),l(b.chunk,f,b.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=s.shift();p(g!==void 0),l(g.chunk,null,g.meta)}},error:f=>{f.stack=d,this.error??=f}}),this.alphaEncoder.configure(e)}}p(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(t){if(t||this.checkForEncoderError(),!t&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,r=dr(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},cu=class{constructor(t,e){this.lastFrame=null;typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(t,e):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e);let r=this.canvas.getContext("webgl2",{alpha:!0});if(!r)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=r,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
40
40
  in vec2 a_position;
41
41
  in vec2 a_texCoord;
42
42
  out vec2 v_texCoord;
@@ -132,6 +132,6 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
132
132
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),i.includes("flac")&&t.push(`
133
133
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else t.push(`
134
134
  Check the discardedTracks field for more info.`)}return t}async execute(){if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
135
- `+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async i=>await i.isLive()?1/0:await i.getDurationFromMetadata()??await i.computeDuration()),r=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(r-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let i of this._outputTrackIds)this._maxTimestamps.set(i,0);this.onProgress?.(0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(t){throw this._canceled||this.cancel(),t}if(this._canceled)throw new ua;if(await this.output.finalize(),this._computeProgress){let t=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,t)}}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(t,e,r){let i=await t.getCodec();if(!i){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=Tt(await t.getRotation()+(e.rotate??0)),o=s,c=this.output.format.supportsVideoRotationMetadata&&(e.allowRotationMetadata??!0),u=await t.getSquarePixelWidth(),l=await t.getSquarePixelHeight(),[m,d]=s%180===0?[u,l]:[l,u],f=e.crop;f&&(f=ri(f,m,d));let[h,b]=f?[f.width,f.height]:[m,d],g=h,y=b,k=g/y;e.width!==void 0&&e.height===void 0?(g=Pt(e.width),y=Pt(Math.round(g/k))):e.width===void 0&&e.height!==void 0?(y=Pt(e.height),g=Pt(Math.round(y*k))):e.width!==void 0&&e.height!==void 0&&(g=Pt(e.width),y=Pt(e.height));let T=await t.getFirstTimestamp(),w=this.output.format.getSupportedVideoCodecs(),S=!!e.forceTranscode||T<this._startTimestamp||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.bitrate!==void 0||!w.includes(i)||e.codec&&e.codec!==i||g!==h||y!==b||s!==0&&!c||!!f,x=e.alpha??"discard";if(S){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(w=w.filter(z=>z===e.codec));let I=e.bitrate??Kn,F=await Xs(w,{width:e.process&&e.processedWidth?e.processedWidth:g,height:e.process&&e.processedHeight?e.processedHeight:y,bitrate:I});if(!F){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let v={codec:F,bitrate:I,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:x,hardwareAcceleration:e.hardwareAcceleration},E=new di(v);a=E;let D=g!==h||y!==b||s!==0&&(!c||e.process!==void 0)||!!f||u!==await t.getCodedWidth()||l!==await t.getCodedHeight();if(!D){let z=new sr({format:new hi,target:new Or}),V=new di(v);z.addVideoTrack(V),await z.start();let Z=await new Ir(t).getSample(T);if(Z)try{await V.add(Z),Z.close(),await z.finalize()}catch(oe){console.info("Error when probing encoder support. Falling back to rerender path.",oe),D=!0,z.cancel()}else await z.cancel()}D?(o=0,this._trackPromises.push((async()=>{await this._started;let V=new Xi(t,{width:g,height:y,fit:e.fit??"fill",rotation:s,crop:e.crop,poolSize:1,alpha:x==="keep"}).canvases(this._startTimestamp,this._endTimestamp),L=e.frameRate,Z=null,oe=null,Vt=null,Oe=async We=>{p(Z),p(L!==void 0);let Qe=Math.round((We-oe)*L);for(let bi=1;bi<Qe;bi++){let or=new me(Z,{timestamp:oe+bi/L,duration:1/L});await this._registerVideoSample(e,r,E,or),or.close()}};for await(let{canvas:We,timestamp:Qe,duration:bi}of V){if(this._canceled)return;let or=Math.max(Qe-this._startTimestamp,0);if(Vt=or+bi,L!==void 0){let la=dr(or,L);if(Z!==null)if(la<=oe){Z=We,oe=la;continue}else await Oe(la);or=la}let pu=new me(We,{timestamp:or,duration:L!==void 0?1/L:bi});await this._registerVideoSample(e,r,E,pu),pu.close(),L!==void 0&&(Z=We,oe=or)}Z&&(p(Vt!==null),p(L!==void 0),await Oe(dr(Vt,L))),E.close(),this._synchronizer.closeTrack(r)})())):this._trackPromises.push((async()=>{await this._started;let z=new Ir(t),V=e.frameRate,L=null,Z=null,oe=null,Vt=async Oe=>{p(L),p(V!==void 0);let We=Math.round((Oe-Z)*V);for(let Qe=1;Qe<We;Qe++)L.setTimestamp(Z+Qe/V),L.setDuration(1/V),await this._registerVideoSample(e,r,E,L);L.close()};for await(let Oe of z.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){Oe.close(),L?.close();return}let We=Math.max(Oe.timestamp-this._startTimestamp,0);if(oe=We+Oe.duration,V!==void 0){let Qe=dr(We,V);if(L!==null)if(Qe<=Z){L.close(),L=Oe,Z=Qe;continue}else await Vt(Qe);We=Qe,Oe.setDuration(1/V)}Oe.setTimestamp(We),await this._registerVideoSample(e,r,E,Oe),V!==void 0?(L=Oe,Z=We):Oe.close()}L&&(p(oe!==null),p(V!==void 0),await Vt(dr(oe,V))),E.close(),this._synchronizer.closeTrack(r)})())}else{let C=new Dr(i);a=C,this._trackPromises.push((async()=>{await this._started;let I=new bt(t),v={decoderConfig:await t.getDecoderConfig()??void 0};for await(let E of I.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(E.timestamp>=this._endTimestamp)break;let D=E.clone({timestamp:E.timestamp-this._startTimestamp,sideData:x==="discard"?{}:E.sideData});p(D.timestamp>=0),this._reportProgress(r,D.timestamp+D.duration),await C.add(D,v),this._synchronizer.shouldWait(r,D.timestamp)&&await this._synchronizer.wait(D.timestamp)}C.close(),this._synchronizer.closeTrack(r)})())}let P=null;e.group||(P=new Le);let A=await t.getLanguageCode();this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Wt(A)?A:void 0,name:await t.getName()??void 0,disposition:await t.getDisposition(),rotation:o,group:P??e.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(P)}async _registerVideoSample(t,e,r,i){if(this._canceled)return;this._reportProgress(e,i.timestamp+i.duration);let a;if(!t.process)a=[i];else{let s=t.process(i);s instanceof Promise&&(s=await s),Array.isArray(s)||(s=s===null?[]:[s]),a=s.map(o=>o instanceof me?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new me(o):new me(o,{timestamp:i.timestamp,duration:i.duration}))}try{for(let s of a){if(this._canceled)break;await r.add(s),this._synchronizer.shouldWait(e,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}}finally{for(let s of a)s!==i&&s.close()}}async _processAudioTrack(t,e,r){let i=await t.getCodec();if(!i){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=await t.getFirstTimestamp(),u=e.numberOfChannels??s,l=e.sampleRate??o,m=u!==s||l!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,d=this.output.format.getSupportedAudioCodecs();if(!e.forceTranscode&&!e.bitrate&&!m&&d.includes(i)&&(!e.codec||e.codec===i)&&!e.process&&e.sampleFormat===void 0){let b=new Vr(i);a=b,this._trackPromises.push((async()=>{await this._started;let g=new bt(t),k={decoderConfig:await t.getDecoderConfig()??void 0};for await(let T of g.packets()){if(this._canceled)return;if(T.timestamp>=this._endTimestamp)break;let w=T.clone({timestamp:T.timestamp-this._startTimestamp});p(w.timestamp>=0),this._reportProgress(r,w.timestamp+w.duration),await b.add(w,k),this._synchronizer.shouldWait(r,w.timestamp)&&await this._synchronizer.wait(w.timestamp)}b.close(),this._synchronizer.closeTrack(r)})())}else{if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let g=null;e.codec&&(d=d.filter(T=>T===e.codec));let y=e.bitrate??Kn,k=await Ki(d,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:u,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:l,bitrate:y});if(!k.some(T=>st.includes(T))&&d.some(T=>st.includes(T))&&(u!==du||l!==mu)){let w=(await Ki(d,{numberOfChannels:du,sampleRate:mu,bitrate:y})).find(S=>st.includes(S));w&&(m=!0,g=w,u=du,l=mu)}else g=k[0]??null;if(g===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}if(m)a=this._resampleAudio(t,e,r,g,u,l,y);else{let T=new mi({codec:g,bitrate:y});a=T,this._trackPromises.push((async()=>{await this._started;let w=new Er(t);for await(let S of w.samples(void 0,this._endTimestamp)){if(this._canceled){S.close();return}S.setTimestamp(S.timestamp-this._startTimestamp),await this._registerAudioSample(e,r,T,S),S.close()}T.close(),this._synchronizer.closeTrack(r)})())}}let f=null;e.group||(f=new Le);let h=await t.getLanguageCode();this.output.addAudioTrack(a,{languageCode:Wt(h)?h:void 0,name:await t.getName()??void 0,disposition:await t.getDisposition(),group:f??e.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(f)}async _registerAudioSample(t,e,r,i){if(this._canceled)return;let a=i;t.sampleFormat!==void 0&&Hs(a.format)!==t.sampleFormat&&(a=qs(a,t.sampleFormat)),this._reportProgress(e,a.timestamp+a.duration);let s;if(!t.process)s=[a];else{let o=t.process(a);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(c=>c instanceof Te))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");s=o}try{for(let o of s){if(this._canceled)break;await r.add(o),this._synchronizer.shouldWait(e,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}}finally{a!==i&&a.close();for(let o of s)o!==i&&o.close()}}_resampleAudio(t,e,r,i,a,s,o){let c=new mi({codec:i,bitrate:o});return this._trackPromises.push((async()=>{await this._started;let u=new nn({targetNumberOfChannels:a,targetSampleRate:s,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async d=>{d.setTimestamp(d.timestamp-this._startTimestamp),await this._registerAudioSample(e,r,c,d),d.close()}}),m=new Er(t).samples(this._startTimestamp,this._endTimestamp);for await(let d of m){if(this._canceled){d.close();return}await u.add(d),d.close()}await u.finalize(),c.close(),this._synchronizer.closeTrack(r)})()),c}_reportProgress(t,e){if(!this._computeProgress)return;p(this._totalDuration!==null),this._maxTimestamps.set(t,Math.max(e,this._maxTimestamps.get(t)));let r=Math.min(...this._maxTimestamps.values()),i=de(r/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,this.onProgress?.(i,r))}},ua=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},am=5,fu=class{constructor(){this.maxTimestamps=new Map;this.resolvers=[]}computeMinAndMaybeResolve(){let t=1/0;for(let[,e]of this.maxTimestamps)t=Math.min(t,e);for(let e=0;e<this.resolvers.length;e++){let r=this.resolvers[e];r.timestamp-t<am&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}shouldWait(t,e){this.maxTimestamps.set(t,Math.max(e,this.maxTimestamps.get(t)??-1/0));let r=this.computeMinAndMaybeResolve();return e-r>=am}wait(t){let{promise:e,resolve:r}=J();return this.resolvers.push({timestamp:t,resolve:r}),e}closeTrack(t){this.maxTimestamps.delete(t),this.computeMinAndMaybeResolve()}};var sm=Symbol.for("mediabunny loaded");globalThis[sm]&&console.error(`[WARNING]
135
+ `+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async i=>await i.isLive()?1/0:await i.getDurationFromMetadata()??await i.computeDuration()),r=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(r-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let i of this._outputTrackIds)this._maxTimestamps.set(i,0);this.onProgress?.(0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(t){throw this._canceled||this.cancel(),t}if(this._canceled)throw new ua;if(await this.output.finalize(),this._computeProgress){let t=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,t)}}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(t,e,r){let i=await t.getCodec();if(!i){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=Tt(await t.getRotation()+(e.rotate??0)),o=s,c=this.output.format.supportsVideoRotationMetadata&&(e.allowRotationMetadata??!0),u=await t.getSquarePixelWidth(),l=await t.getSquarePixelHeight(),[m,d]=s%180===0?[u,l]:[l,u],f=e.crop;f&&(f=ri(f,m,d));let[h,b]=f?[f.width,f.height]:[m,d],g=h,y=b,k=g/y;e.width!==void 0&&e.height===void 0?(g=Pt(e.width),y=Pt(Math.round(g/k))):e.width===void 0&&e.height!==void 0?(y=Pt(e.height),g=Pt(Math.round(y*k))):e.width!==void 0&&e.height!==void 0&&(g=Pt(e.width),y=Pt(e.height));let T=await t.getFirstTimestamp(),w=this.output.format.getSupportedVideoCodecs(),S=!!e.forceTranscode||T<this._startTimestamp||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.bitrate!==void 0||!w.includes(i)||e.codec&&e.codec!==i||g!==h||y!==b||s!==0&&!c||!!f,x=e.alpha??"discard";if(S){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(w=w.filter(z=>z===e.codec));let I=e.bitrate??Kn,F=await Xs(w,{width:e.process&&e.processedWidth?e.processedWidth:g,height:e.process&&e.processedHeight?e.processedHeight:y,bitrate:I});if(!F){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let v={codec:F,bitrate:I,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:x,hardwareAcceleration:e.hardwareAcceleration},E=new di(v);a=E;let D=g!==h||y!==b||s!==0&&(!c||e.process!==void 0)||!!f||u!==await t.getCodedWidth()||l!==await t.getCodedHeight();if(!D){let z=new sr({format:new hi,target:new Or}),V=new di(v);z.addVideoTrack(V),await z.start();let Z=await new Ir(t).getSample(T);if(Z)try{await V.add(Z),Z.close(),await z.finalize()}catch(oe){console.info("Error when probing encoder support. Falling back to rerender path.",oe),D=!0,z.cancel()}else await z.cancel()}D?(o=0,this._trackPromises.push((async()=>{await this._started;let V=new Xi(t,{width:g,height:y,fit:e.fit??"fill",rotation:s,crop:e.crop,poolSize:1,alpha:x==="keep"}).canvases(this._startTimestamp,this._endTimestamp),L=e.frameRate,Z=null,oe=null,Vt=null,Oe=async We=>{p(Z),p(L!==void 0);let Qe=Math.round((We-oe)*L);for(let bi=1;bi<Qe;bi++){let or=new me(Z,{timestamp:oe+bi/L,duration:1/L});await this._registerVideoSample(e,r,E,or),or.close()}};for await(let{canvas:We,timestamp:Qe,duration:bi}of V){if(this._canceled)return;let or=Math.max(Qe-this._startTimestamp,0);if(Vt=or+bi,L!==void 0){let la=dr(or,L);if(Z!==null)if(la<=oe){Z=We,oe=la;continue}else await Oe(la);or=la}let pu=new me(We,{timestamp:or,duration:L!==void 0?1/L:bi});await this._registerVideoSample(e,r,E,pu),pu.close(),L!==void 0&&(Z=We,oe=or)}Z&&(p(Vt!==null),p(L!==void 0),await Oe(dr(Vt,L))),E.close(),this._synchronizer.closeTrack(r)})())):this._trackPromises.push((async()=>{await this._started;let z=new Ir(t),V=e.frameRate,L=null,Z=null,oe=null,Vt=async Oe=>{p(L),p(V!==void 0);let We=Math.round((Oe-Z)*V);for(let Qe=1;Qe<We;Qe++)L.setTimestamp(Z+Qe/V),L.setDuration(1/V),await this._registerVideoSample(e,r,E,L);L.close()};for await(let Oe of z.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){Oe.close(),L?.close();return}let We=Math.max(Oe.timestamp-this._startTimestamp,0);if(oe=We+Oe.duration,V!==void 0){let Qe=dr(We,V);if(L!==null)if(Qe<=Z){L.close(),L=Oe,Z=Qe;continue}else await Vt(Qe);We=Qe,Oe.setDuration(1/V)}Oe.setTimestamp(We),await this._registerVideoSample(e,r,E,Oe),V!==void 0?(L=Oe,Z=We):Oe.close()}L&&(p(oe!==null),p(V!==void 0),await Vt(dr(oe,V))),E.close(),this._synchronizer.closeTrack(r)})())}else{let C=new Dr(i);a=C,this._trackPromises.push((async()=>{await this._started;let I=new bt(t),v={decoderConfig:await t.getDecoderConfig()??void 0};for await(let E of I.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(E.timestamp>=this._endTimestamp)break;let D=E.clone({timestamp:E.timestamp-this._startTimestamp,sideData:x==="discard"?{}:E.sideData});p(D.timestamp>=0),this._reportProgress(r,D.timestamp+D.duration),await C.add(D,v),this._synchronizer.shouldWait(r,D.timestamp)&&await this._synchronizer.wait(D.timestamp)}C.close(),this._synchronizer.closeTrack(r)})())}let P=null;e.group||(P=new Le);let A=await t.getLanguageCode();this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Wt(A)?A:void 0,name:await t.getName()??void 0,disposition:await t.getDisposition(),rotation:o,group:P??e.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(P)}async _registerVideoSample(t,e,r,i){if(this._canceled)return;this._reportProgress(e,i.timestamp+i.duration);let a;if(!t.process)a=[i];else{let s=t.process(i);s instanceof Promise&&(s=await s),Array.isArray(s)||(s=s===null?[]:[s]),a=s.map(o=>o instanceof me?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new me(o):new me(o,{timestamp:i.timestamp,duration:i.duration}))}try{for(let s of a){if(this._canceled)break;await r.add(s),this._synchronizer.shouldWait(e,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}}finally{for(let s of a)s!==i&&s.close()}}async _processAudioTrack(t,e,r){let i=await t.getCodec();if(!i){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=await t.getFirstTimestamp(),u=e.numberOfChannels??s,l=e.sampleRate??o,m=u!==s||l!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,d=this.output.format.getSupportedAudioCodecs();if(!e.forceTranscode&&!e.bitrate&&!m&&d.includes(i)&&(!e.codec||e.codec===i)&&!e.process&&e.sampleFormat===void 0){let b=new Vr(i);a=b,this._trackPromises.push((async()=>{await this._started;let g=new bt(t),k={decoderConfig:await t.getDecoderConfig()??void 0};for await(let T of g.packets()){if(this._canceled)return;if(T.timestamp>=this._endTimestamp)break;let w=T.clone({timestamp:T.timestamp-this._startTimestamp});p(w.timestamp>=0),this._reportProgress(r,w.timestamp+w.duration),await b.add(w,k),this._synchronizer.shouldWait(r,w.timestamp)&&await this._synchronizer.wait(w.timestamp)}b.close(),this._synchronizer.closeTrack(r)})())}else{if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let g=null;e.codec&&(d=d.filter(T=>T===e.codec));let y=e.bitrate??Kn,k=await Ki(d,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:u,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:l,bitrate:y});if(!k.some(T=>st.includes(T))&&d.some(T=>st.includes(T))&&(u!==du||l!==mu)){let w=(await Ki(d,{numberOfChannels:du,sampleRate:mu,bitrate:y})).find(S=>st.includes(S));w&&(m=!0,g=w,u=du,l=mu)}else g=k[0]??null;if(g===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}if(m)a=this._resampleAudio(t,e,r,g,u,l,y);else{let T=new mi({codec:g,bitrate:y});a=T,this._trackPromises.push((async()=>{await this._started;let w=new Er(t);for await(let S of w.samples(void 0,this._endTimestamp)){if(this._canceled){S.close();return}S.setTimestamp(S.timestamp-this._startTimestamp),await this._registerAudioSample(e,r,T,S),S.close()}T.close(),this._synchronizer.closeTrack(r)})())}}let f=null;e.group||(f=new Le);let h=await t.getLanguageCode();this.output.addAudioTrack(a,{languageCode:Wt(h)?h:void 0,name:await t.getName()??void 0,disposition:await t.getDisposition(),group:f??e.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(f)}async _registerAudioSample(t,e,r,i){if(this._canceled)return;let a=i;t.sampleFormat!==void 0&&Hs(a.format)!==t.sampleFormat&&(a=qs(a,t.sampleFormat)),this._reportProgress(e,a.timestamp+a.duration);let s;if(!t.process)s=[a];else{let o=t.process(a);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(c=>c instanceof Te))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");s=o}try{for(let o of s){if(this._canceled)break;await r.add(o),this._synchronizer.shouldWait(e,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}}finally{a!==i&&a.close();for(let o of s)o!==i&&o.close()}}_resampleAudio(t,e,r,i,a,s,o){let c=new mi({codec:i,bitrate:o});return this._trackPromises.push((async()=>{await this._started;let u=new nn({targetNumberOfChannels:a,targetSampleRate:s,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async d=>{p(d.timestamp>=this._startTimestamp),d.setTimestamp(d.timestamp-this._startTimestamp),await this._registerAudioSample(e,r,c,d),d.close()}}),m=new Er(t).samples(this._startTimestamp,this._endTimestamp);for await(let d of m){if(this._canceled){d.close();return}await u.add(d),d.close()}await u.finalize(),c.close(),this._synchronizer.closeTrack(r)})()),c}_reportProgress(t,e){if(!this._computeProgress)return;p(this._totalDuration!==null),this._maxTimestamps.set(t,Math.max(e,this._maxTimestamps.get(t)));let r=Math.min(...this._maxTimestamps.values()),i=de(r/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,this.onProgress?.(i,r))}},ua=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},am=5,fu=class{constructor(){this.maxTimestamps=new Map;this.resolvers=[]}computeMinAndMaybeResolve(){let t=1/0;for(let[,e]of this.maxTimestamps)t=Math.min(t,e);for(let e=0;e<this.resolvers.length;e++){let r=this.resolvers[e];r.timestamp-t<am&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}shouldWait(t,e){this.maxTimestamps.set(t,Math.max(e,this.maxTimestamps.get(t)??-1/0));let r=this.computeMinAndMaybeResolve();return e-r>=am}wait(t){let{promise:e,resolve:r}=J();return this.resolvers.push({timestamp:t,resolve:r}),e}closeTrack(t){this.maxTimestamps.delete(t),this.computeMinAndMaybeResolve()}};var sm=Symbol.for("mediabunny loaded");globalThis[sm]&&console.error(`[WARNING]
136
136
  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[sm]=!0;return pm(Rp);})();
137
137
  if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Mediabunny)