mediabunny 1.50.6 → 1.50.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -44,14 +44,6 @@ Mediabunny is a JavaScript library for reading, writing, and converting media (l
44
44
  </a>
45
45
  </div>
46
46
 
47
- ### Silver sponsors
48
-
49
- <div align="center">
50
- <a href="https://ponder.ai/" target="_blank" rel="sponsored">
51
- <img src="./docs/public/sponsors/ponder.png" width="50" height="50" alt="Ponder">
52
- </a>
53
- </div>
54
-
55
47
  ### Bronze sponsors
56
48
 
57
49
  <div align="center">
@@ -32423,7 +32423,7 @@ ${cue.notes ?? ""}`;
32423
32423
  audioSample.copyTo(sourceView, { planeIndex: 0, format: "f32" });
32424
32424
  const inputStartTime = audioSample.timestamp - this.startTime;
32425
32425
  const inputEndTime = inputStartTime + audioSample.duration;
32426
- const outputStartFrame = Math.floor(inputStartTime * this.targetSampleRate);
32426
+ const outputStartFrame = Math.floor((inputStartTime - 1 / this.sourceSampleRate) * this.targetSampleRate) + 1;
32427
32427
  const outputEndFrame = Math.ceil(inputEndTime * this.targetSampleRate);
32428
32428
  for (let outputFrame = outputStartFrame; outputFrame < outputEndFrame; outputFrame++) {
32429
32429
  if (outputFrame < this.bufferStartFrame) {
@@ -14,7 +14,7 @@
14
14
 
15
15
  `,a);c===-1&&(c=t.length);let u=ao(e[2]),m=ao(e[3])-u,d=t.slice(s,c).trim();t=t.slice(c).trimStart(),sa.lastIndex=0;let f={timestamp:u/1e3,duration:m/1e3,text:d,identifier:n,settings:o,notes:r},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}},Cf=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ao=i=>{let t=Cf.exec(i);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])},so=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),n=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var oi=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(),n=t.size??r-e;this.writer.seek(e),this.writeBoxHeader(t,n),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);h(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}}},Q=new Uint8Array(8),Je=new DataView(Q.buffer),fe=i=>[(i%256+256)%256],W=i=>(Je.setUint16(0,i,!1),[Q[0],Q[1]]),iu=i=>(Je.setInt16(0,i,!1),[Q[0],Q[1]]),Ld=i=>(Je.setUint32(0,i,!1),[Q[1],Q[2],Q[3]]),R=i=>(Je.setUint32(0,i,!1),[Q[0],Q[1],Q[2],Q[3]]),ar=i=>(Je.setInt32(0,i,!1),[Q[0],Q[1],Q[2],Q[3]]),Ft=i=>(Je.setUint32(0,Math.floor(i/2**32),!1),Je.setUint32(4,i,!1),[Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7]]),If=i=>(Je.setInt32(0,Math.floor(i/2**32),!1),Je.setUint32(4,i,!1),[Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7]]),Wd=i=>(Je.setInt16(0,2**8*i,!1),[Q[0],Q[1]]),Tt=i=>(Je.setInt32(0,2**16*i,!1),[Q[0],Q[1],Q[2],Q[3]]),eu=i=>(Je.setInt32(0,2**30*i,!1),[Q[0],Q[1],Q[2],Q[3]]),tu=(i,t)=>{let e=[],r=i;do{let n=r&127;r>>=7,e.length>0&&(n|=128),e.push(n),t!==void 0&&t--}while(r>0||t);return e.reverse()},se=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},Hd=i=>{let t=i*(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]},qd=Hd(0),Kd=i=>[Tt(i[0]),Tt(i[1]),eu(i[2]),Tt(i[3]),Tt(i[4]),eu(i[5]),Tt(i[6]),Tt(i[7]),eu(i[8])],L=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),Z=(i,t,e,r,n)=>L(i,[fe(t),Ld(e),r??[]],n),Gd=i=>i.isQuickTime?L("ftyp",[se("qt "),R(512),se("qt ")]):i.fragmented?i.cmaf?L("ftyp",[se("iso5"),R(512),se("iso5"),se("iso6"),se("mp41"),se("cmfc"),se("dash")]):L("ftyp",[se("iso5"),R(512),se("iso5"),se("iso6"),se("mp41")]):L("ftyp",[se("isom"),R(512),se("isom"),i.holdsAvc?se("avc1"):[],se("mp41")]),nu=()=>L("styp",[se("iso5"),R(0),se("iso5"),se("iso6"),se("mp41"),se("cmfc"),se("dash")]),au=(i,t)=>{let e=i.maxWrittenEndTimestamp-i.minWrittenTimestamp;return Number.isFinite(e)||(e=0),Z("sidx",1,0,[R(1),R(Ze),Ft(le(i.minWrittenTimestamp,Ze)),Ft(0),W(0),W(1),R(t&2147483647),R(le(e,Ze)),R(0)])},oa=i=>({type:"mdat",largeSize:i}),Qd=i=>({type:"free",size:i}),rn=i=>L("moov",void 0,[Ef(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>vf(t,i.creationTime)),i.isFragmented?pp(i.trackDatas):null,Ap(i)]),Ef=(i,t)=>{let e=Math.max(0,...t.map(s=>le(oo(s),Ze)+le(s.startTimestampOffset??0,Ze))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!Dt(i)||!Dt(e),a=n?Ft:R;return Z("mvhd",+n,0,[a(i),a(i),R(Ze),a(e),Tt(1),Wd(1),Array(10).fill(0),Kd(qd),Array(24).fill(0),R(r)])},oo=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;r<i.samples.length;r++){let n=i.samples[r];n.timestamp<t&&(t=n.timestamp),n.timestamp+n.duration>e&&(e=n.timestamp+n.duration)}return t===1/0?0:e-t},vf=(i,t)=>{let e=rm(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset>0;return L("trak",void 0,[_f(i,t),r?Rf(i,i.startTimestampOffset):null,Ff(i,t),e.name!==void 0?L("udta",void 0,[L("name",[...$.encode(e.name)])]):null])},_f=(i,t)=>{let e=le(oo(i),Ze)+le(i.startTimestampOffset??0,Ze),r=!Dt(t)||!Dt(e),n=r?Ft:R,a;if(i.type==="video"){let o=i.track.metadata.rotation;a=Hd(o??0)}else a=qd;let s=2;return i.track.metadata.disposition?.default!==!1&&(s|=1),Z("tkhd",+r,s,[n(t),n(t),R(i.track.id),R(0),n(e),Array(8).fill(0),W(0),W(i.track.id),Wd(i.type==="audio"?1:0),W(0),Kd(a),Tt(i.type==="video"?i.info.width:0),Tt(i.type==="video"?i.info.height:0)])},Rf=(i,t)=>{let e=le(t,Ze),r=le(oo(i),Ze),n=!Dt(e)||!Dt(r),a=n?Ft:R,s=n?If:ar;return L("edts",void 0,[Z("elst",n?1:0,0,[R(2),a(e),s(-1),Tt(1),a(r),s(0),Tt(1)])])},Ff=(i,t)=>L("mdia",void 0,[Mf(i,t),su(!0,Bf[i.type],Of[i.type]),Df(i)]),Mf=(i,t)=>{let e=le(oo(i),i.timescale),r=!Dt(t)||!Dt(e),n=r?Ft:R;return Z("mdhd",+r,0,[n(t),n(t),R(i.timescale),n(e),W(tm(i.track.metadata.languageCode??te)),W(0)])},Bf={video:"vide",audio:"soun",subtitle:"text"},Of={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},su=(i,t,e,r="\0\0\0\0")=>Z("hdlr",0,0,[i?se("mhlr"):R(0),se(t),se(r),R(0),R(0),se(e,!0)]),Df=i=>L("minf",void 0,[Nf[i.type](),Lf(),qf(i)]),Vf=()=>Z("vmhd",0,1,[W(0),W(0),W(0),W(0)]),Uf=()=>Z("smhd",0,0,[W(0),W(0)]),zf=()=>Z("nmhd",0,0),Nf={video:Vf,audio:Uf,subtitle:zf},Lf=()=>L("dinf",void 0,[Wf()]),Wf=()=>Z("dref",0,0,[R(1)],[Hf()]),Hf=()=>Z("url ",0,1),qf=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return L("stbl",void 0,[Kf(i),op(i),t?mp(i):null,t?fp(i):null,up(i),lp(i),dp(i),cp(i)])},Kf=i=>{let t;if(i.type==="video")t=Gf(Ip(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=em(i.track.source._codec,i.muxer.isQuickTime);h(e),t=Zf(e,i)}else i.type==="subtitle"&&(t=ap(_p[i.track.source._codec],i));return h(t),Z("stsd",0,0,[R(1)],[t])},Gf=(i,t)=>L(i,[Array(6).fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),R(4718592),R(4718592),R(0),W(1),Array(32).fill(0),W(24),iu(65535)],[Ep[t.track.source._codec]?.(t)??null,Qf(t),ya(t.info.decoderConfig.colorSpace)?jf(t):null]),Qf=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:L("pasp",[R(i.info.pixelAspectRatio.num),R(i.info.pixelAspectRatio.den)]),jf=i=>L("colr",[se(i.muxer.isQuickTime?"nclc":"nclx"),W(it[i.info.decoderConfig.colorSpace.primaries]),W(nt[i.info.decoderConfig.colorSpace.transfer]),W(at[i.info.decoderConfig.colorSpace.matrix]),i.muxer.isQuickTime?[]:fe((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Xf=i=>i.info.decoderConfig&&L("avcC",[...X(i.info.decoderConfig.description)]),$f=i=>i.info.decoderConfig&&L("hvcC",[...X(i.info.decoderConfig.description)]),zd=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),n=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?it[t.colorSpace.primaries]:2,l=e[6]?Number(e[6]):t.colorSpace?.transfer?nt[t.colorSpace.transfer]:2,m=e[7]?Number(e[7]):t.colorSpace?.matrix?at[t.colorSpace.matrix]:2;return Z("vpcC",1,0,[fe(r),fe(n),fe(c),fe(u),fe(l),fe(m),W(0)])},Yf=i=>L("av1C",Ca(i.info.decoderConfig.codec)),Zf=(i,t)=>{let e=0,r,n=16,a=re.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Se(s);n=8*o,n>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),W(1),W(e),W(0),R(0),W(t.info.numberOfChannels),W(n),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),R(0),W(t.info.numberOfChannels),W(Math.min(n,16)),iu(s),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),a?[R(1),R(n/8),R(t.info.numberOfChannels*n/8)]:[R(0),R(0),R(0)],R(2)]}return L(i,r,[vp(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},ru=i=>{let t;switch(i.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: ${i.track.source._codec}`)}let e=[...fe(t),...fe(21),...Ld(0),...R(0),...R(0)];if(i.info.decoderConfig.description){let r=X(i.info.decoderConfig.description);e=[...e,...fe(5),...tu(r.byteLength),...r]}return e=[...W(1),...fe(0),...fe(4),...tu(e.length),...e,...fe(6),...fe(1),...fe(2)],e=[...fe(3),...tu(e.length),...e],Z("esds",0,0,e)},Br=i=>L("wave",void 0,[Jf(i),ep(i),L("\0\0\0\0")]),Jf=i=>L("frma",[se(em(i.track.source._codec,i.muxer.isQuickTime))]),ep=i=>{let{littleEndian:t}=Se(i.track.source._codec);return L("enda",[W(+t)])},tp=i=>{let t=i.info.numberOfChannels,e=3840,r=i.info.sampleRate,n=0,a=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){h(o.byteLength>=18);let c=X(o),u=br(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,n=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return L("dOps",[fe(0),fe(t),W(e),R(r),iu(n),fe(a),...s])},rp=i=>{let t=i.info.decoderConfig?.description;h(t);let e=X(t);return Z("dfLa",0,0,[...e.subarray(4)])},_t=i=>{let{littleEndian:t,sampleSize:e}=Se(i.track.source._codec),r=+t;return Z("pcmC",0,0,[fe(r),fe(8*e)])},ip=i=>{let t=za(i.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 q(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),L("dac3",[...e])},np=i=>{let t=Na(i.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),n=new Uint8Array(r),a=new q(n);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 L("dec3",[...n])},ap=(i,t)=>L(i,[Array(6).fill(0),W(1)],[Rp[t.track.source._codec](t)]),sp=i=>L("vttC",[...$.encode(i.info.config.description)]);var op=i=>Z("stts",0,0,[R(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[R(t.sampleCount),R(t.sampleDelta)])]),cp=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return Z("stss",0,0,[R(t.length),t.map(([e])=>R(e+1))])},up=i=>Z("stsc",0,0,[R(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[R(t.firstChunk),R(t.samplesPerChunk),R(1)])]),lp=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Se(i.track.source._codec);return Z("stsz",0,0,[R(t*i.info.numberOfChannels),R(i.samples.reduce((e,r)=>e+le(r.duration,i.timescale),0))])}return Z("stsz",0,0,[R(0),R(i.samples.length),i.samples.map(t=>R(t.size))])},dp=i=>i.finalizedChunks.length>0&&Y(i.finalizedChunks).offset>=2**32?Z("co64",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>Ft(t.offset))]):Z("stco",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>R(t.offset))]),mp=i=>Z("ctts",1,0,[R(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[R(t.sampleCount),ar(t.sampleCompositionTimeOffset)])]),fp=i=>{let t=1/0,e=-1/0,r=1/0,n=-1/0;h(i.compositionTimeOffsetTable.length>0),h(i.samples.length>0);for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];t=Math.min(t,o.sampleCompositionTimeOffset),e=Math.max(e,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,le(o.timestamp,i.timescale)),n=Math.max(n,le(o.timestamp+o.duration,i.timescale))}let a=Math.max(-t,0);return n>=2**31?null:Z("cslg",0,0,[ar(a),ar(t),ar(e),ar(r),ar(n)])},pp=i=>L("mvex",void 0,i.map(hp)),hp=i=>Z("trex",0,0,[R(i.track.id),R(1),R(0),R(0),R(0)]),ou=(i,t)=>L("moof",void 0,[gp(i),...t.map(bp)]),gp=i=>Z("mfhd",0,0,[R(i)]),jd=i=>{let t=0,e=0,r=0,n=0,a=i.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|n},bp=i=>L("traf",void 0,[yp(i),kp(i),Tp(i)]),yp=i=>{h(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:jd(e)};return Z("tfhd",0,t,[R(i.track.id),R(r.duration),R(r.size),R(r.flags)])},kp=i=>(h(i.currentChunk),Z("tfdt",1,0,[Ft(le(i.currentChunk.startTimestamp,i.timescale))])),Tp=i=>{h(i.currentChunk);let t=i.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(b=>b.size),r=i.currentChunk.samples.map(jd),n=i.currentChunk.samples.map(b=>le(b.timestamp-b.decodeTimestamp,i.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(n),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),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+m,p|=1024*+d,p|=2048*+f,Z("trun",1,p,[R(i.currentChunk.samples.length),R(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?R(r[0]):[],i.currentChunk.samples.map((b,g)=>[l?R(t[g]):[],m?R(e[g]):[],d?R(r[g]):[],f?ar(n[g]):[]])])},Xd=i=>L("mfra",void 0,[...i.map(wp),Sp()]),wp=(i,t)=>Z("tfra",1,0,[R(i.track.id),R(63),R(i.finalizedChunks.length),i.finalizedChunks.map(r=>[Ft(le(r.samples[0].timestamp,i.timescale)),Ft(r.moofOffset),R(t+1),R(1),R(1)])]),Sp=()=>Z("mfro",0,0,[R(0)]),$d=()=>L("vtte"),Yd=(i,t,e,r,n)=>L("vttc",void 0,[n!==null?L("vsid",[ar(n)]):null,e!==null?L("iden",[...$.encode(e)]):null,t!==null?L("ctim",[...$.encode(so(t))]):null,r!==null?L("sttg",[...$.encode(r)]):null,L("payl",[...$.encode(i)])]),Zd=i=>L("vtta",[...$.encode(i)]),Ap=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=Pp(r);n&&t.push(n)}else if(e==="mdta"){let n=Cp(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&xp(t,i.output._metadataTags);return t.length===0?null:L("udta",void 0,t)},xp=(i,t)=>{for(let{key:e,value:r}of st(t))switch(e){case"title":i.push(Rt("\xA9nam",r));break;case"description":i.push(Rt("\xA9des",r));break;case"artist":i.push(Rt("\xA9ART",r));break;case"album":i.push(Rt("\xA9alb",r));break;case"albumArtist":i.push(Rt("albr",r));break;case"genre":i.push(Rt("\xA9gen",r));break;case"date":i.push(Rt("\xA9day",r.toISOString().slice(0,10)));break;case"comment":i.push(Rt("\xA9cmt",r));break;case"lyrics":i.push(Rt("\xA9lyr",r));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ee(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||i.some(n=>n.type===e)||(typeof r=="string"?i.push(Rt(e,r)):r instanceof Uint8Array&&i.push(L(e,Array.from(r))))}},Rt=(i,t)=>{let e=$.encode(t);return L(i,[W(e.length),W(tm("und")),Array.from(e)])},Nd={"image/jpeg":13,"image/png":14,"image/bmp":27},Jd=(i,t)=>{let e=[];for(let{key:r,value:n}of st(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:kt(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:kt(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:kt(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:kt(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:kt(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:kt(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:kt(n)});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:kt(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:kt(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:L("data",[R(Nd[a.mimeType]??0),R(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();e.push({key:"track",value:kt(a)})}else e.push({key:"trkn",value:L("data",[R(0),R(0),W(0),W(n),W(i.tracksTotal??0),W(0)])});break;case"discNumber":t||e.push({key:"disc",value:L("data",[R(0),R(0),W(0),W(n),W(i.discsTotal??0),W(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ee(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:kt(n)}):n instanceof Uint8Array?e.push({key:r,value:L("data",[R(0),R(0),Array.from(n)])}):n instanceof Qe&&e.push({key:r,value:L("data",[R(Nd[n.mimeType]??0),R(0),Array.from(n.data)])}))}return e},Pp=i=>{let t=Jd(i,!1);return t.length===0?null:Z("meta",0,0,void 0,[su(!1,"mdir","","appl"),L("ilst",void 0,t.map(e=>L(e.key,void 0,[e.value])))])},Cp=i=>{let t=Jd(i,!0);return t.length===0?null:L("meta",void 0,[su(!1,"mdta",""),Z("keys",0,0,[R(t.length)],t.map(e=>L("mdta",[...$.encode(e.key)]))),L("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...R(r+1));return L(n,void 0,[e.value])}))])},kt=i=>L("data",[R(1),R(0),...$.encode(i)]),Ip=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},Ep={avc:Xf,hevc:$f,vp8:zd,vp9:zd,av1:Yf,prores:null},em=(i,t)=>{switch(i){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(i){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(i){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"}},vp=(i,t)=>{switch(i){case"aac":return ru;case"mp3":return ru;case"opus":return tp;case"vorbis":return ru;case"flac":return rp;case"ac3":return ip;case"eac3":return np}if(t)switch(i){case"pcm-s24":return Br;case"pcm-s24be":return Br;case"pcm-s32":return Br;case"pcm-s32be":return Br;case"pcm-f32":return Br;case"pcm-f32be":return Br;case"pcm-f64":return Br;case"pcm-f64be":return Br}else switch(i){case"pcm-s16":return _t;case"pcm-s16be":return _t;case"pcm-s24":return _t;case"pcm-s24be":return _t;case"pcm-s32":return _t;case"pcm-s32be":return _t;case"pcm-f32":return _t;case"pcm-f32be":return _t;case"pcm-f64":return _t;case"pcm-f64be":return _t}return null},_p={webvtt:"wvtt"},Rp={webvtt:sp},tm=i=>{h(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};var Mt=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(){h(!this.started),this.target._start(),this.started=!0}write(t){h(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 h(this.started&&!this.finalized),this.target._flush()}async finalize(){h(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,n=this.trackedWrites.byteLength;for(;n<r;)n*=2;if(n!==this.trackedWrites.byteLength){let a=new Uint8Array(n);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 im=Au(Ec(),1);var nm=typeof im<"u"?im:void 0,xe=class extends Ue{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 ca(this,e)}},cu=2**16,uu=2**32,Or=class extends xe{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(cu,{maxByteLength:uu})}catch{this._buffer=new ArrayBuffer(cu),this._supportsResize=!1}else this._buffer=new ArrayBuffer(cu);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>uu)throw new Error(`ArrayBuffer exceeded maximum size of ${uu} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this._bytes,0),this._buffer=n,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)}},Fp=2**24,Mp=2,nn=class extends xe{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??Fp}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let n=r-this._lastWriteEnd;this._write(new Uint8Array(n),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(h(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((n,a)=>n.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n<r.length;n++){let a=e[e.length-1],s=r[n];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 n of e){n.data=new Uint8Array(n.size);for(let a of this._sections)n.start<=a.start&&a.start<n.start+n.size&&n.data.set(a.data,a.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){let n=this._chunks.findIndex(u=>u.start<=r&&r<u.start+this._chunkSize);n===-1&&(n=this._createChunk(r));let a=this._chunks[n],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>Mp){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 n=0,a=e.written.length-1,s=-1;for(;n<=a;){let o=Math.floor(n+(a-n+1)/2);e.written[o].start<=r.start?(n=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 n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((a,s)=>a.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){h(this._streamWriter);for(let r=0;r<this._chunks.length;r++){let n=this._chunks[r];if(!(!n.shouldFlush&&!e)){for(let a of n.written){let s=n.start+a.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data.subarray(a.start,a.end),position:s}).catch(o=>{this._writeError??=o}),this._lastFlushEnd=n.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;h(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}},co=class extends xe{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new nn(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 h(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,h(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)}},uo=class extends xe{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(!nm.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let n=new WritableStream({start:async()=>{this._fileHandle=await nm.fs.open(e,"w")},write:async a=>{h(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 nn(n,{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)}},Dr=class extends xe{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},ca=class extends xe{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)}},Ke=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,Bp=2082844800,rm=i=>{let t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},le=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},lo=class extends Te{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new Or;this.auxWriter=new Mt(this.auxTarget,!1);this.auxBoxWriter=new oi(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=J();this.creationTime=Math.floor(Date.now()/1e3)+Bp;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 ui,this.isCmaf=r instanceof ci,this.minimumFragmentDuration=r._options.minimumFragmentDuration??(r instanceof ci?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(n=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":n instanceof Or),this.boxWriter=new oi(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Or?"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 n=await this.output._getInitTarget(),a=new Mt(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new oi(a)}let r=this.output._tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(h(n),this.format._options.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(Gd({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:a,start:s}=n.writer.stopTrackingWrites();this.format._options.onFtyp(a,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output._tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(h(this.writer),h(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=oa(!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 Ha({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(f=>f.track===e);if(a)return a;mr(n),h(n),h(n.decoderConfig);let s={...n.decoderConfig};h(s.codedWidth!==void 0),h(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){let f=Ci(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=ol(f),o=!0}else if(e.source._codec==="hevc"&&!s.description){let f=Ii(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=ul(f),o=!0}let c=Du(1/(e.metadata.frameRate??Ze),1e6).den,u=s.displayAspectWidth,l=s.displayAspectHeight,m=u===void 0||l===void 0?{num:1,den:1}:Lt({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,p)=>f.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Re(n),h(n),h(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){let u=He(be.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=xt[u.channelConfiguration];if(l===void 0||m===void 0)throw new Error("Invalid ADTS frame header.");s.description=Si({objectType:u.objectType,sampleRate:l,numberOfChannels:m}),o=!0}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&re.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 n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ea(r),h(r),h(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,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(s.info.requiresAnnexBTransformation){let u=[...gr(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=Ba(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,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let m=He(be.tempFromBytes(o));if(!m)throw new Error("Expected ADTS frame, didn't get one.");let d=m.crcCheck===null?tr:je;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=Se(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 p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+p}}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,n){let a=le(n,e.timescale);if(n=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Se(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,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);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 n=new Set([]);for(let l of e.cueQueue)h(l.timestamp<=r),h(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let a=[...n].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=$d();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;tn.lastIndex=0;let d=tn.test(m.text),f=m.timestamp+m.duration,p=e.cueToSourceId.get(m);if(p===void 0&&o<f&&(p=e.nextSourceId++,e.cueToSourceId.set(m,p)),m.notes){let g=Zd(m.notes);this.auxBoxWriter.writeBox(g)}let b=Yd(m.text,d?s:null,m.identifier??null,m.settings??null,p??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,n,a,s){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:le(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=le(o.duration,e.timescale);a+=c}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:a,sampleDelta:1});else{let s=Y(e.timeToSampleTable);s.sampleCount+=a}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];s.decodeTimestamp=n[a];let o=le(s.timestamp-s.decodeTimestamp,e.timescale),c=le(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){h(e.lastSample);let u=le(s.decodeTimestamp,e.timescale,!1),l=Math.round(u-e.lastTimescaleUnits);if(h(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let m=Y(e.timeToSampleTable);if(h(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=Y(e.compositionTimeOffsetTable);h(d),d.sampleCompositionTimeOffset===o?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=le(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,h(e.lastSample),h(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){h(r.type==="key");let a=le(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(h(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 n=!1;if(!e.currentChunk)n=!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&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),h(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(h(!this.isFragmented),h(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((n,a)=>n+le(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Y(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 n of e.currentChunk.samples)h(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(h(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=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<n&&(r=s,n=s.sampleQueue[0].timestamp)}if(!r)break;let a=r.sampleQueue.shift();await this.addSampleToTrack(r,a)}}async finalizeFragment(e=!this.isCmaf){h(this.isFragmented);let r=this.nextFragmentNumber++;if(r===1){let p=this.initBoxWriter??this.boxWriter;h(p),this.format._options.onMoov&&p.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let b=rn(this);if(p.writeBox(b),this.format._options.onMoov){let{data:g,start:y}=p.writer.stopTrackingWrites();this.format._options.onMoov(g,y)}if(this.isCmaf){h(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new oi(this.writer);let g=this.boxWriter.measureBox(nu()),y=this.boxWriter.measureBox(au(this,0));this.segmentHeaderSize=g+y,this.writer.seek(this.segmentHeaderSize)}}h(this.writer),h(this.boxWriter);let n=this.trackDatas.filter(p=>p.currentChunk),a=ou(r,n),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+lt,u=1/0;for(let p of n){p.currentChunk.offset=c,p.currentChunk.moofOffset=s;for(let b of p.currentChunk.samples)c+=b.size;u=Math.min(u,p.currentChunk.startTimestamp)}let l=c-o,m=l>=2**32;if(m)for(let p of n)p.currentChunk.offset+=jt-lt;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=ou(r,n);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:p,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoof(p,b,u)}h(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=oa(m);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(m?jt:lt));for(let p of n)for(let b of p.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.format._options.onMdat){let{data:p,start:b}=this.writer.stopTrackingWrites();this.format._options.onMdat(p,b)}for(let p of n)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(h(this.writer),h(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let n=rn(this),s=this.boxWriter.measureBox(n)+this.computeSampleTableSizeUpperBound()+4096;h(this.ftypSize!==null),this.writer.seek(this.ftypSize+s),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=oa(!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(){h(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;h(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(a=>a.type===e);if(r.length===0)continue;if(!r.some(a=>a.track.metadata.disposition?.default!==!1)){let a=r[0];a.track.metadata.disposition={...a.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();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),h(r.startTimestampOffset!==null);for(let n=0;n<r.samples.length;n++){let a=r.samples[n];a.timestamp-=r.startTimestampOffset,a.decodeTimestamp-=r.startTimestampOffset}}if(h(this.writer),h(this.boxWriter),this.fastStart==="in-memory"){this.mdat=oa(!1);let r;for(let a=0;a<2;a++){let s=rn(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)h(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 n=rn(this);if(this.boxWriter.writeBox(n),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)h(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(nu()),this.boxWriter.writeBox(au(this,r))}else{let r=this.writer.getPos(),n=Xd(this.trackDatas);this.boxWriter.writeBox(n);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{h(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);h(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=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=rn(this);if(this.fastStart==="reserve"){h(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(Qd(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 Op=-(2**15),Dp=2**15-1,am="Mediabunny",sm=6,om=5,Vp={video:1,audio:2,subtitle:17},mo=class extends Te{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 Ja(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 li?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=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:n},{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 Mi(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:am},{id:22337,data:am},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 n=Fe[r.track.source._codec];h(n);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=X(s),c=br(o);a=Math.round(1e9*(c.preSkip/ct))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:Vp[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??te},{id:134,data:n},r.codecPrivate?{id:25506,data:X(r.codecPrivate)}:null,{id:22186,data:0},{id:22203,data:a},r.track.metadata.name!==void 0?{id:21358,data:new pt(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:n}=e.track.metadata,a=[r?{id:2352003,data:1e9/r}:null],s=n?tt(-n):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,ya(c)?{id:21936,data:[{id:21937,data:at[c.matrix]},{id:21946,data:nt[c.transfer]},{id:21947,data:it[c.primaries]},{id:21945,data:c.fullRange?2:1}]}:null,s?{id:30320,data:[{id:30321,data:0},{id:30325,data:new Fi((s+180)%360-180)}]}:null]};return a.push(u),a}audioSpecificTrackInfo(e){let r=re.includes(e.track.source._codec)?Se(e.track.source._codec):null;return[{id:225,data:[{id:181,data:new Fi(e.info.sampleRate)},{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new pt(s)},typeof o=="string"?{id:17543,data:new pt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of st(n))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=n.tracksTotal!==void 0?`${o}/${n.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${o}/${n.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ee(s)}if(n.raw)for(let s in n.raw){let o=n.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=[],n=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")+(Uu(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&&!n.has(c))break}n.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new pt(s.description)}:null,{id:18030,data:new pt(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 Ht)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&wa(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new pt(o.description)}:null,{id:18030,data:new pt(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:sm,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:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return h(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 is({isWebM:this.format instanceof li,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;mr(n),h(n),h(n.decoderConfig),h(n.decoderConfig.codedWidth!==void 0),h(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,o=n.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:Lt({num:s,den:o}),u={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:!!r.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?u.codecPrivate=new Uint8Array($u(u.info.decoderConfig.codec)):e.source._codec==="av1"?u.codecPrivate=new Uint8Array(Ca(u.info.decoderConfig.codec)):e.source._codec==="prores"&&(u.codecPrivate=$.encode(n.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,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Re(n),h(n),h(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){let u=He(be.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=xt[u.channelConfiguration];if(l===void 0||m===void 0)throw new Error("Invalid ADTS frame header.");s.description=Si({objectType:u.objectType,sampleRate:l,numberOfChannels:m}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??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 n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ea(r),h(r),h(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:$.encode(r.config.description),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,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=r.timestamp,l=r.duration;e.metadata.frameRate!==void 0&&(u=St(u,e.metadata.frameRate),l=St(l,e.metadata.frameRate));let m=s.info.alphaMode?r.sideData.alpha??null:null,d=this.createInternalChunk(o,u,l,r.type,m);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let l=He(be.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let m=l.crcCheck===null?tr:je;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,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);tn.lastIndex=0,o=o.replace(tn,d=>{let p=ao(d.slice(1,-1))-c;return`<${so(p)}>`});let u=$.encode(o),l=`${r.settings??""}
16
16
  ${r.identifier??""}
17
- ${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,n=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<n&&(r=s,n=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 n=new q(r.data);n.skipBits(2);let a=n.readBits(1),o=(n.readBits(1)<<1)+a;if(o===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;o>=2&&n.skipBits(1);let m={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];Pu(r.data,n.pos,n.pos+3,m)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=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{h(this.currentClusterStartMsTimestamp!==null),h(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>Dp}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o<Op)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 Pn(e.lastWrittenMsTimestamp-n)}: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,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:om,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(h(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,om),this.writer.seek(s)}if(this.format._options.onCluster){h(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 n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)h(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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.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(),h(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,sm);let n=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Mi(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),h(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var fo=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,n=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=va[u+g];if(_a(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]=n,this.helper[2]=l,this.helper[3]=m,this.writer.write(this.helper.subarray(0,4));let d=pr(t.mpegVersionId,t.channel);this.writer.seek(e+d),this.writeU32(fr);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 p=va[u+c],b=_a(a,t.layer,1e3*p,t.sampleRate,s);this.writer.seek(e+b)}};var po=class extends Te{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 fo(this.writer),qt(this.output._metadataTags)||new Mr(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 n=await this.mutex.acquire();try{let a=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&a){let s=N(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=$r(o,null).header;if(!c)throw new Error("Invalid MP3 header in sample.");let u=pr(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let l=s.getUint32(u,!1);if(l===fr||l===Pi)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{n()}}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(),n=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/n)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=n,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 Up=8192,ho=class extends Te{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(ls);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,us({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));h(e.source._codec==="vorbis"||e.source._codec==="opus"),Re(r),h(r),h(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?ct: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(h(r.decoderConfig),e.track.source._codec==="vorbis"){h(r.decoderConfig.description);let n=X(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let g=0;for(;;){let y=n[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(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=n.subarray(a,a+=o);a+=c;let m=n.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=kn(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=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:Ua(m).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=X(r.decoderConfig.description),a=new Uint8Array(8),s=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=kn(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:br(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=cs(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 n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=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<n&&(r=o,n=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,n){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,n&&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>=Up||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,vn,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Fu(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=os(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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.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 zp=0,mm=4096,cm=256,Np=224,um=192,lm=new Uint8Array([9,240]),dm=new Uint8Array([70,1]),go=class extends Te{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(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,ys(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;mr(r),h(r?.decoderConfig);let a=e.source._codec;h(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=cm+this.trackDatas.length,c=Np+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 n=this.trackDatas.find(l=>l.track===e);if(n)return n;Re(r),h(r?.decoderConfig);let a=e.source._codec;h(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3");let s,o;switch(a){case"aac":s=15,o=um+this.audioTrackIndex++;break;case"mp3":s=3,o=um+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break}let c=cm+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,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);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,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);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,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=X(s);a==="avc"?e.avcDecoderConfig=Oa(o):e.hevcDecoderConfig=ll(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of gr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Qt(o[0])===9:ut(o[0])===35)||n.push(o)}let a=r==="avc"?lm:dm;return n.unshift(a),gn(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Fa(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Qt(l[0])===9:ut(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="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=n==="avc"?lm:dm;return o.unshift(c),gn(o)}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3")return r.data;if(e.inputIsAdts===null){let u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=Pt(X(u)),m=Aa(l);e.adtsHeader=m.header,e.adtsHeaderBitstream=m.bitstream}}if(e.inputIsAdts)return r.data;h(e.adtsHeader),h(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;xa(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 n=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=n[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,n=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<n&&(r=s,n=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){h(!this.tablesWritten),this.writePsiSection(zp,di),this.writePsiSection(mm,Wp(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let n=0,a=!0;for(;n<r.length;){let o=184-(a?1:0),c=r.length-n,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(n,n+u),1)):l=r.subarray(n,n+u),this.writeTsPacket(e,a,null,l),n+=u,a=!1}}writePesPacket(e,r){let n=e.track.type==="video",a=n?10:5,s=new Uint8Array(9+a),o=N(s),c=new q(s.subarray(9));Hr(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,n?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4);if(c.pos=0,c.writeBits(4,n?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),n){h(r.decodeTimestamp!==null);let p=Math.round(r.decodeTimestamp*9e4);c.writeBits(4,1),c.writeBits(3,p>>>30&7),c.writeBits(1,1),c.writeBits(15,p>>>15&32767),c.writeBits(1,1),c.writeBits(15,p&32767),c.writeBits(1,1)}let m=s.length+r.data.length,d=0,f=!0;for(;d<m;){let p=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),P=this.payloadBuffer.subarray(0,S),C=0;if(d<s.length){let I=Math.min(s.length-d,S);P.set(s.subarray(d,d+I),0),C=I}let x=Math.max(0,d-s.length),A=x+(S-C);C<S&&P.set(r.data.subarray(x,A),C),this.writeTsPacket(e.pid,p,w,P),d+=S,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,n,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=n?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;n&&(this.packetBuffer.set(n,u),u+=n.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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!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()}},Lp=79764919,fm=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Lp:t<<1;fm[i]=t>>>0&4294967295}var pm=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^fm[t>>>24^r])>>>0}return t},di=new Uint8Array(16);{let i=N(di);di[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),di[5]=193,di[6]=0,di[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|mm&8191,!1),i.setUint32(12,pm(di.subarray(0,12)),!1)}var Wp=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=wn.length:c.streamType===135&&(t+=Sn.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=N(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of i)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|wn.length,!1),a+=2,r.set(wn,a),a+=wn.length):c.streamType===135?(n.setUint16(a,61440|Sn.length,!1),a+=2,r.set(Sn,a),a+=Sn.length):(n.setUint16(a,61440,!1),a+=2);let s=pm(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var bo=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 yo=class extends Te{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 bo(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Re(n),h(n),h(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.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 n,a=e.source._codec,s=Se(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=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(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!qt(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ee(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 n=new Set,a=(c,u)=>{if(!rt(u)){V._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)),n.add(c)};for(let{key:c,value:u}of st(e))switch(c){case"title":a("INAM",u),n.add("INAM");break;case"artist":a("IART",u),n.add("IART");break;case"album":a("IPRD",u),n.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),n.add("ITRK")}break;case"genre":a("IGNR",u),n.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",u),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:ee(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||n.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 Mr(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?(h(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),h(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),h(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(h(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),h(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}};var ko=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.startTime=null;this.bufferStartFrame=0;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){h(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,n)=>r[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>r[n*t+a]*+(a<2):t===2&&e===6?this.channelMixer=(r,n,a)=>r[n*t+a]*+(a<2):t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*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,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a<t?r[n*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.startTime=t.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),h(this.startTime!==null);let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(n,{planeIndex:0,format:"f32"});let a=t.timestamp-this.startTime,s=a+t.duration,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;h(l<this.bufferSizeInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,p=Math.floor(f),b=Math.ceil(f),g=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,T=0;p>=0&&p<t.numberOfFrames&&(k=this.channelMixer(n,p,y)),b>=0&&b<t.numberOfFrames&&(T=this.channelMixer(n,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;h(this.startTime!==null);let t=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=new ke({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var mi=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})()}},Bt=class extends mi{constructor(e){super();this._connectedTrack=null;if(!ne.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ne.join(", ")}.`);this._codec=e}},fu=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Vr=class extends Bt{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),fu(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},ua=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.emittedEncoderPackets=0;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 or;this.customEncoderQueueSize=0;this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=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=a.transform?.width,d=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(h(this.outputWidth),h(this.outputHeight),h(s!=="deny"),m=this.outputWidth,d=this.outputHeight,f=s);let p=await t.transform({width:m,height:d,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,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=Ko(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===n&&(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,n;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]),n=a.map(s=>s instanceof Ve?s:typeof VideoFrame<"u"&&s instanceof VideoFrame?new Ve(s):new Ve(s,{timestamp:t.timestamp,duration:t.duration}))}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized),this.closed)break;let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...a.encodeOptions,...e},u={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let l=a.clone(),m=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(d=>this.setError(d)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await m}else{h(this.encoder);let l=a.toVideoFrame(),m=K(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),d=m!==-1?this.preciseTimings[m]:null;if(d&&d.microsecondTimestamp===l.timestamp?(d.timestamp!==a.timestamp&&(d.timestampIsValid=!1),d.duration!==a.duration&&(d.durationIsValid=!1)):(this.preciseTimings.splice(m+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(l,u),l.close();else if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(l,u),l.close();else{this.splitter||(this.splitter=new pu);let{colorFrame:p,alphaFrame:b}=await this.splitter.split(l);this.alphaFrameQueue.push(b),this.encoder.encode(p,u),p.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;h(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let a=1;a<n;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=Wc({...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=ji.find(n=>n.supports(this.encodingConfig.codec,e));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(n,a)=>{if(!(n instanceof j))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.");fu(this.source._connectedTrack,n),this.encodingConfig.onEncodedPacket?.(n,a),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,a).catch(s=>{this.setError(s)})},this.customEncoder.onError=n=>{this.setError(n)},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,p)=>{let b={};if(f){let w=new Uint8Array(f.byteLength);f.copyTo(w),b.alpha=w}let g=j.fromEncodedChunk(d,b),y=K(this.preciseTimings,d.timestamp,w=>w.microsecondTimestamp),k=y!==-1?this.preciseTimings[y]:null,T=null;this.emittedEncoderPackets===0&&g.type==="delta"&&p?.decoderConfig&&(T=yr(this.encodingConfig.codec,p.decoderConfig,g.data)),(k&&k.microsecondTimestamp===d.timestamp||T!==null)&&(g=g.clone({timestamp:k?.timestampIsValid?k.timestamp:void 0,duration:k?.durationIsValid?k.duration:void 0,type:T??void 0})),fu(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,p),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,p).catch(w=>{this.setError(w)}),this.emittedEncoderPackets++},m=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(d,f)=>{if(!this.alphaEncoder){l(d,null,f);return}let p=this.alphaFrameQueue.shift();h(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:d.type==="key"}),u++,p.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.setError(d)}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){let d=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,p)=>{u--;let b=s.shift();for(h(b!==void 0),l(b.chunk,f,b.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=s.shift();h(g!==void 0),l(g.chunk,null,g.meta)}},error:f=>{f.stack=d,this.setError(f)}}),this.alphaEncoder.configure(e)}}h(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=Ko(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,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(),await jr(25)),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.errorSet)throw this.error}},lu=null,pu=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!lu){let n=new Blob([`(${Hp.toString()})()`],{type:"application/javascript"});lu=URL.createObjectURL(n)}this.worker=new Worker(lu),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()})}let e=this.nextRequestId++,r=J();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Hp=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=c*u,m=Math.ceil(c/2),d=Math.ceil(u/2),f=l+m*d*2,p=new Uint8Array(f);for(let k=0,T=3;k<l;k++,T+=4)p[k]=a[T];p.fill(128,l);let b=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),g={format:"I420",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,g);return{colorFrame:b,alphaFrame:y}},n=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),m=s.includes("P12"),d=l||m?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let b=c*u,g=f*p,y=b*d,k=g*d,T=b*d,w=y+k*2,S=s.replace("A",""),P=Math.ceil(c/2),C=Math.ceil(u/2),x=P*C,A=x*d,I=T+2*A,E=new Uint8Array(I),_=w;E.set(a.subarray(_,_+T),0);let v=T,D=l?512:m?2048:128;d===1?E.fill(D,v):new Uint16Array(E.buffer,v,2*x).fill(D);let O=l?"I420P10":m?"I420P12":"I420",z=new VideoFrame(a.subarray(0,w),{format:S,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),H={format:O,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[E.buffer]},ie=new VideoFrame(E,H);return{colorFrame:z,alphaFrame:ie}}},fi=class extends Bt{constructor(t){$s(t),super(t.codec),this._encoder=new ua(this,t)}add(t,e){if(!(t instanceof Ve))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},To=class extends Bt{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");$s(e),super(e.codec),this._encoder=new ua(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");let n=new Ve(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},wo=class extends Bt{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if($s(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new ua(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=0,s=!1,o=null,c=0,u=()=>{if(h(e!==null),!this._lastVideoFrame)return;h(n!==null),h(r!==null);let d=performance.now();for(;d-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});m(p,d)}};e!==null&&(this._timerHandle=Hu(u,4));let l=d=>{if(e===null)m(d);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=d):(m(d.clone(),f),n=f,this._lastVideoFrame=d)}},m=(d,f=performance.now())=>{if(s){d.close();return}a++;let p=d.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}d.close();return}if(r===null){r=p;let g,y=this._options.timestampBase??"synced-zero";if(y==="unix")g=Date.now()/1e3;else if(y==="zero")g=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,g=0):g=f/1e3-k._firstMediaStreamTimestamp}c=g-r}if(o=p,this._encoder.getQueueSize()>=8){d.close();return}let b=new Ve(d,{timestamp:p+c});this._encoder.add(b,!0).catch(g=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(g),this._workerTrackId!==null&&mu({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let d=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});d.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await Qp())this._workerTrackId=Kp++,mu({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},et.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&qu(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(h(this._workerListener),mu({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(h(this._workerListener),et.removeEventListener("message",this._workerListener),et.removeEventListener("message",n),r())};et.addEventListener("message",n)})),await this._encoder.flushAndClose(e)}},Ot=class extends mi{constructor(e){super();this._connectedTrack=null;if(!oe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${oe.join(", ")}.`);this._codec=e}},Ur=class extends Ot{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},la=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new or;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new ko({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&bd(t.format)!==r.transform.sampleFormat){let n=yd(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process){let n=r.transform.process(t);if(n instanceof Promise&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);for(let a of n){if(!(a instanceof ke))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(a,!0)}e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized),this.closed)return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=new ke({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{h(this.encoder);let r=t.toAudioData();this.encoder.encode(r),r.close(),e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){h(this.outputSampleSize),h(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t,o=2048,c=[];for(let d=0;d<n;d+=o){let f=Math.min(o,t.numberOfFrames-d),p=f*r*this.outputSampleSize,b=new ArrayBuffer(p),g=new DataView(b);c.push({frameCount:f,view:g})}let u=t.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let d=0;d<r;d++){t.copyTo(l,{planeIndex:d,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:b}=c[f];for(let g=0;g<p;g++)this.writeOutputValue(b,(g*r+d)*this.outputSampleSize,l[f*o+g])}}e&&t.close();let m={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let d=0;d<c.length;d++){let{frameCount:f,view:p}=c[d],b=p.buffer,g=d*o,y=new j(new Uint8Array(b),"key",s+g/a,f/a);this.encodingConfig.onEncodedPacket?.(y,m),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,m)}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:e,sampleRate:r}=t,n=Hc({numberOfChannels:e,sampleRate:r,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);let a=Xi.find(s=>s.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(s,o)=>{if(!(s instanceof j))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,s,o).catch(c=>{this.setError(c)})},this.customEncoder.onError=s=>{this.setError(s)},await this.customEncoder.init();else if(re.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,u)=>{if(this.encodingConfig.codec==="aac"&&u?.decoderConfig){let m=!1;if(!u.decoderConfig.description||u.decoderConfig.description.byteLength<2?m=!0:m=Pt(X(u.decoderConfig.description)).objectType===0,m){let d=Number(Y(n.codec.split(".")));u.decoderConfig.description=Si({objectType:d,numberOfChannels:u.decoderConfig.numberOfChannels,sampleRate:u.decoderConfig.sampleRate})}}let l=j.fromEncodedChunk(c);l=l.clone({timestamp:St(l.timestamp,n.sampleRate),duration:c.duration!=null?St(l.duration,n.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(l,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u).catch(m=>{this.setError(m)})},error:c=>{c.stack=o,this.setError(c)}}),this.encoder.configure(n)}h(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Se(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ce((o+1)*127.5,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ce(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ce(Math.floor(o*32767),-32768,32767);a.setUint8(s,Rd(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ce(Math.floor(o*32767),-32768,32767);a.setUint8(s,Md(c))}:h(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ce((o+1)*32767.5,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ce(Math.round(o*32767),-32768,32767),n):h(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>Hr(a,s,ce((o+1)*83886075e-1,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Ru(a,s,ce(Math.round(o*8388607),-8388608,8388607),n):h(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ce((o+1)*21474836475e-1,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ce(Math.round(o*2147483647),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):h(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):h(!1);break;default:ee(r),h(!1)}}async flushAndClose(t){t||this.checkForEncoderError(),!t&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},an=class extends Ot{constructor(t){Ys(t),super(t.codec),this._encoder=new la(this,t)}add(t){if(!(t instanceof ke))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},So=class extends Ot{constructor(e){Ys(e);super(e.codec);this._accumulatedTime=0;this._encoder=new la(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=ke._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let n of r)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Ao=class extends Ot{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Ys(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new la(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let m=this._connectedTrack.output;m._firstMediaStreamTimestamp===null?(m._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-m._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new ke(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let u=0;this._scriptProcessorNode.onaudioprocess=l=>{let m=ke._fromAudioBuffer(l.inputBuffer,u);u+=l.inputBuffer.duration;for(let d of m)s(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(h(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}},qp=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:ee(n)}})},Kp=0,et=null,Gp=()=>{let i=new Blob([`(${qp.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);et=new Worker(t)},du=null,Qp=async()=>du!==null?du:(et||Gp(),new Promise(i=>{h(et);let t=e=>{let r=e.data;r.type==="support"&&(du=r.supported,et.removeEventListener("message",t),i(r.supported))};et.addEventListener("message",t)})),mu=(i,t)=>{h(et),t?et.postMessage(i,t):et.postMessage(i)},pi=class extends mi{constructor(e){super();this._connectedTrack=null;if(!Be.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Be.join(", ")}.`);this._codec=e}},xo=class extends pi{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new no({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var Co=class extends Te{constructor(e,r){if(!(e._target instanceof Ke))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(y=>y.metadata.isRelativeToUnixEpoch),n=this.output._tracks.some(y=>!y.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,u=!1;for(let y of this.output._tracks){y.type==="video"&&(o=!0);let k=new Map;for(let T of this.output._tracks){if(y===T||!y.canBePairedWith(T))continue;if(y.type===T.type){c||(V._warn(`Illegal pairing of two ${y.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(y.isVideoTrack()&&y.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){u||(V._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let w=k.get(T.source._codec);w||k.set(T.source._codec,w=[]),w.push(T)}for(let[,T]of k){let w=T.map(C=>C.id).join("-");s.find(C=>C.key===w)||s.push({name:T[0].type+"-"+(s.length+1),key:w,tracks:T,needsEmit:!1,firstNoUri:!1});let P=a.get(y);P||a.set(y,P=[]),P.push(w)}}let l=o?"video":"audio",m=[],d=[],f=[];for(let y of this.output._tracks){let k=a.get(y);if(k){if(h(k.length>0),y.type!==l)continue;for(let T of k){let w=s.find(S=>S.key===T);if(h(w),k.length===1&&w.tracks.length===1){let S=a.get(w.tracks[0]);if(h(S!==void 0),S.length===1){let P=s.find(C=>C.key===S[0]);if(P.tracks.length===1){h(P.tracks[0]===y),m.push({tracks:[y,w.tracks[0]],linkedGroup:null});continue}}}m.push({tracks:[y],linkedGroup:w}),w.needsEmit=!0}}else y.type==="video"?d.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??te}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(d.length>0)if(new Set(d.map(p)).size>1){let k={key:d.map(T=>T.id).join("-"),name:"video-"+(s.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};s.push(k),m.push({tracks:[d[0]],linkedGroup:k})}else for(let k of d)m.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),m.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)m.push({tracks:[k],linkedGroup:null});let b=y=>{let k=[],T=0,w=0,S=!1,P=null,C=-1/0;for(let x of y)x.isVideoTrack()?(T++,S||=(x.metadata.rotation??0)!==0):x.isAudioTrack()&&w++,k.push(x.source._codec);for(let x of Wt(this.format._options.segmentFormat)){let A=x.getSupportedCodecs(),I=x.getSupportedTrackCounts();if(k.some(_=>!A.includes(_))||T<I.video.min||T>I.video.max||w<I.audio.min||w>I.audio.max)continue;let E=0;S&&x.supportsVideoRotationMetadata&&E++,E>C&&(P=x,C=E)}return h(P),P},g=async y=>{if(y.some(P=>this.playlists.some(C=>C.tracks.includes(P))))throw new Error("Internal error: track is already registered in a playlist.");let k=b(y),T=this.playlists.length+1,w=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});jp(w);let S={id:this.playlists.length+1,path:w,tracks:y,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new _e};return this.playlists.push(S),S};for(let y of s)if(y.needsEmit)for(let k=0;k<y.tracks.length;k++){let T=y.tracks[k],w=this.playlists.find(S=>S.tracks[0].id===T.id);w??=await g([T]),this.playlistDeclarations.push({playlist:w,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of m){let k=this.playlists.find(T=>T.tracks[0].id===y.tracks[0].id);k??=await g(y.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:y.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===y.linkedGroup.name):[]})}e()}async getMimeType(){return Ct}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));h(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;mr(r),h(r),h(r?.decoderConfig);let a=this.playlists.filter(s=>s.tracks.includes(e));return h(a.length===1),n={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"video",decoderConfig:r.decoderConfig}},this.trackDatas.push(n),n}getAudioTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Re(r),h(r),h(r?.decoderConfig);let a=this.playlists.filter(s=>s.tracks.includes(e));return h(a.length===1),n={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"audio",decoderConfig:r.decoderConfig}},this.trackDatas.push(n),n}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(h(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}let r=this.trackDatas.filter(s=>e.tracks.includes(s.track)),n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let w=n.packets.every(C=>C.timestamp<s),S=null,P=null;if(w){if(!n.closed)return}else for(let C=0;C<n.packets.length;C++){let x=n.packets[C];if(S!==null&&x.timestamp>s)break;C>0&&x.type==="key"&&(S=x,P=C)}if(P!==null){if(o=P,a){let C=a.packets.findIndex(x=>x.timestamp>=S.timestamp);if(C!==-1)c=C;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let C=Nu(n.packets,A=>A.timestamp),x=n.packets[C];if(h(x),a)if(x.timestamp<s){let A=a.packets.findIndex(I=>I.timestamp>=s);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}else{let A=a.packets.findIndex(I=>I.timestamp>x.timestamp);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(S=>S.timestamp<s))if(a.closed)c=a.packets.length;else return;else{let S=ur(a.packets,P=>P.timestamp<=s);c=Math.max(S,1)}if(o===0&&c===0){r.every(S=>S.closed)&&await this.onPlaylistDone(e);return}let u=null,l,m;h(this.output._target instanceof Ke);let d=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let w={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Po(e)};l=await this.getSegmentPath(w),hm(l),m=he(he(d.rootPath,e.path),l);let S=await this.output._getTarget({path:m,isRoot:!1,mimeType:e.segmentFormat.mimeType});S._start(),e.singleFile={target:S,path:l,nextOffset:0,info:w}}else l=e.singleFile.path,m=he(he(d.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Po(e)},l=await this.getSegmentPath(u),hm(l),m=he(he(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,b=new sr({format:e.segmentFormat,target:new Ke(m,async w=>{let S={...w,isRoot:!1};if(w.isRoot)if(e.singleFile){let P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:C})=>f=Math.max(f,C)),P}else{let P=await this.output._getTarget(S);return p=P,P.on("write",({end:C})=>f=Math.max(f,C)),P}return this.output._getTarget(S)}),initTarget:async()=>{if(e.initSegment)return new Dr;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let w=e.singleFile.target.slice(e.singleFile.nextOffset);return w.on("write",({end:S})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,S)}),w.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),w}else{let w=Po(e),S=await this.getInitPath(w);Xp(S),e.initSegment={path:S,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let P=he(he(d.rootPath,e.path),S),C=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return C.on("write",({end:x})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,x)}),C.on("finalized",()=>{this.format._options.onInit?.(C,w)}),C}}}),g=-1/0;try{let w=null,S=null;if(n&&(w=new Vr(n.track.source._codec),b.addVideoTrack(w,n.track.metadata)),a&&(S=new Ur(a.track.source._codec),b.addAudioTrack(S,a.track.metadata)),await b.start(),n){h(w);let P={decoderConfig:n.info.decoderConfig};for(let C=0;C<o;C++){let x=n.packets[C];await w.add(x,P),g=Math.max(g,x.timestamp+x.duration)}}if(a){h(S);let P={decoderConfig:a.info.decoderConfig};for(let C=0;C<c;C++){let x=a.packets[C];await S.add(x,P),g=Math.max(g,x.timestamp+x.duration)}}await b.finalize()}catch(w){throw await b.cancel(),w}u&&(h(p),this.format._options.onSegment?.(p,u)),o>0&&(h(n),n.packets.splice(0,o)),c>0&&(h(a),a.packets.splice(0,c));let y=1/0;n&&n.packets.length>0&&(y=n.packets[0].timestamp),a&&a.packets.length>0&&(y=Math.min(y,a.packets[0].timestamp));let k=y<1/0?y:g;h(Number.isFinite(k));let T=k-e.currentSegmentStartTimestamp;if(h(T>=0),e.writtenSegments.push({path:l,duration:T,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,T),e.currentSegmentStartTimestamp=k,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let w=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(h(w.info),this.format._options.onSegmentPopped?.(w.path,w.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){h(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let o=0;o<r.length;o++){s+=r[o].duration;let c=0,u=0;for(let l=o;l<r.length&&(c+=r[l].byteSize,u+=r[l].duration,u>=.5*this.globalTargetDuration&&u<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*c/u)),!(u>1.5*this.globalTargetDuration));l++);}if(n===0)for(let o of r){let c=o.duration||1;n=Math.max(n,8*o.byteSize/c)}for(let o of r)a+=8*o.byteSize;e.peakBitrate=n,e.averageBitrate=a/(s||1)}async writePlaylist(e){h(this.output._target instanceof Ke);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let d of e.writtenSegments)n||=d.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=he(r.rootPath,e.path),u=`#EXTM3U
17
+ ${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,n=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<n&&(r=s,n=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 n=new q(r.data);n.skipBits(2);let a=n.readBits(1),o=(n.readBits(1)<<1)+a;if(o===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;o>=2&&n.skipBits(1);let m={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];Pu(r.data,n.pos,n.pos+3,m)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=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{h(this.currentClusterStartMsTimestamp!==null),h(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>Dp}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o<Op)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 Pn(e.lastWrittenMsTimestamp-n)}: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,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:om,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(h(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,om),this.writer.seek(s)}if(this.format._options.onCluster){h(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 n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)h(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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.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(),h(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,sm);let n=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Mi(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),h(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var fo=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,n=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=va[u+g];if(_a(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]=n,this.helper[2]=l,this.helper[3]=m,this.writer.write(this.helper.subarray(0,4));let d=pr(t.mpegVersionId,t.channel);this.writer.seek(e+d),this.writeU32(fr);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 p=va[u+c],b=_a(a,t.layer,1e3*p,t.sampleRate,s);this.writer.seek(e+b)}};var po=class extends Te{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 fo(this.writer),qt(this.output._metadataTags)||new Mr(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 n=await this.mutex.acquire();try{let a=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&a){let s=N(r.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");let o=s.getUint32(0,!1),c=$r(o,null).header;if(!c)throw new Error("Invalid MP3 header in sample.");let u=pr(c.mpegVersionId,c.channel);if(s.byteLength>=u+4){let l=s.getUint32(u,!1);if(l===fr||l===Pi)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{n()}}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(),n=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/n)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=n,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 Up=8192,ho=class extends Te{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(ls);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,us({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));h(e.source._codec==="vorbis"||e.source._codec==="opus"),Re(r),h(r),h(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?ct: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(h(r.decoderConfig),e.track.source._codec==="vorbis"){h(r.decoderConfig.description);let n=X(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let g=0;for(;;){let y=n[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(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=n.subarray(a,a+=o);a+=c;let m=n.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=kn(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=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:Ua(m).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=X(r.decoderConfig.description),a=new Uint8Array(8),s=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=kn(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:br(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=cs(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 n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=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<n&&(r=o,n=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,n){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,n&&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>=Up||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,vn,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Fu(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=os(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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.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 zp=0,mm=4096,cm=256,Np=224,um=192,lm=new Uint8Array([9,240]),dm=new Uint8Array([70,1]),go=class extends Te{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(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,ys(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;mr(r),h(r?.decoderConfig);let a=e.source._codec;h(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=cm+this.trackDatas.length,c=Np+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 n=this.trackDatas.find(l=>l.track===e);if(n)return n;Re(r),h(r?.decoderConfig);let a=e.source._codec;h(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3");let s,o;switch(a){case"aac":s=15,o=um+this.audioTrackIndex++;break;case"mp3":s=3,o=um+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break}let c=cm+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,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);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,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);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,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=X(s);a==="avc"?e.avcDecoderConfig=Oa(o):e.hevcDecoderConfig=ll(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of gr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Qt(o[0])===9:ut(o[0])===35)||n.push(o)}let a=r==="avc"?lm:dm;return n.unshift(a),gn(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Fa(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Qt(l[0])===9:ut(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="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=n==="avc"?lm:dm;return o.unshift(c),gn(o)}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3")return r.data;if(e.inputIsAdts===null){let u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=Pt(X(u)),m=Aa(l);e.adtsHeader=m.header,e.adtsHeaderBitstream=m.bitstream}}if(e.inputIsAdts)return r.data;h(e.adtsHeader),h(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;xa(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 n=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=n[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,n=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<n&&(r=s,n=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){h(!this.tablesWritten),this.writePsiSection(zp,di),this.writePsiSection(mm,Wp(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let n=0,a=!0;for(;n<r.length;){let o=184-(a?1:0),c=r.length-n,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(n,n+u),1)):l=r.subarray(n,n+u),this.writeTsPacket(e,a,null,l),n+=u,a=!1}}writePesPacket(e,r){let n=e.track.type==="video",a=n?10:5,s=new Uint8Array(9+a),o=N(s),c=new q(s.subarray(9));Hr(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,n?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4);if(c.pos=0,c.writeBits(4,n?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),n){h(r.decodeTimestamp!==null);let p=Math.round(r.decodeTimestamp*9e4);c.writeBits(4,1),c.writeBits(3,p>>>30&7),c.writeBits(1,1),c.writeBits(15,p>>>15&32767),c.writeBits(1,1),c.writeBits(15,p&32767),c.writeBits(1,1)}let m=s.length+r.data.length,d=0,f=!0;for(;d<m;){let p=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),P=this.payloadBuffer.subarray(0,S),C=0;if(d<s.length){let I=Math.min(s.length-d,S);P.set(s.subarray(d,d+I),0),C=I}let x=Math.max(0,d-s.length),A=x+(S-C);C<S&&P.set(r.data.subarray(x,A),C),this.writeTsPacket(e.pid,p,w,P),d+=S,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,n,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=n?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;n&&(this.packetBuffer.set(n,u),u+=n.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(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!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()}},Lp=79764919,fm=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Lp:t<<1;fm[i]=t>>>0&4294967295}var pm=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^fm[t>>>24^r])>>>0}return t},di=new Uint8Array(16);{let i=N(di);di[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),di[5]=193,di[6]=0,di[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|mm&8191,!1),i.setUint32(12,pm(di.subarray(0,12)),!1)}var Wp=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=wn.length:c.streamType===135&&(t+=Sn.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=N(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of i)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|wn.length,!1),a+=2,r.set(wn,a),a+=wn.length):c.streamType===135?(n.setUint16(a,61440|Sn.length,!1),a+=2,r.set(Sn,a),a+=Sn.length):(n.setUint16(a,61440,!1),a+=2);let s=pm(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var bo=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 yo=class extends Te{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 bo(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Re(n),h(n),h(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.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 n,a=e.source._codec,s=Se(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=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(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!qt(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ee(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 n=new Set,a=(c,u)=>{if(!rt(u)){V._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)),n.add(c)};for(let{key:c,value:u}of st(e))switch(c){case"title":a("INAM",u),n.add("INAM");break;case"artist":a("IART",u),n.add("IART");break;case"album":a("IPRD",u),n.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),n.add("ITRK")}break;case"genre":a("IGNR",u),n.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",u),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:ee(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||n.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 Mr(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?(h(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),h(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),h(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(h(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),h(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}};var ko=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.startTime=null;this.bufferStartFrame=0;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){h(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,n)=>r[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>r[n*t+a]*+(a<2):t===2&&e===6?this.channelMixer=(r,n,a)=>r[n*t+a]*+(a<2):t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*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,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a<t?r[n*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.startTime=t.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),h(this.startTime!==null);let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(n,{planeIndex:0,format:"f32"});let a=t.timestamp-this.startTime,s=a+t.duration,o=Math.floor((a-1/this.sourceSampleRate)*this.targetSampleRate)+1,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;h(l<this.bufferSizeInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,p=Math.floor(f),b=Math.ceil(f),g=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,T=0;p>=0&&p<t.numberOfFrames&&(k=this.channelMixer(n,p,y)),b>=0&&b<t.numberOfFrames&&(T=this.channelMixer(n,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;h(this.startTime!==null);let t=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=new ke({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}};var mi=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})()}},Bt=class extends mi{constructor(e){super();this._connectedTrack=null;if(!ne.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ne.join(", ")}.`);this._codec=e}},fu=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Vr=class extends Bt{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),fu(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},ua=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.emittedEncoderPackets=0;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 or;this.customEncoderQueueSize=0;this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=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=a.transform?.width,d=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(h(this.outputWidth),h(this.outputHeight),h(s!=="deny"),m=this.outputWidth,d=this.outputHeight,f=s);let p=await t.transform({width:m,height:d,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,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=Ko(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===n&&(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,n;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]),n=a.map(s=>s instanceof Ve?s:typeof VideoFrame<"u"&&s instanceof VideoFrame?new Ve(s):new Ve(s,{timestamp:t.timestamp,duration:t.duration}))}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized),this.closed)break;let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...a.encodeOptions,...e},u={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let l=a.clone(),m=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(d=>this.setError(d)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await m}else{h(this.encoder);let l=a.toVideoFrame(),m=K(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),d=m!==-1?this.preciseTimings[m]:null;if(d&&d.microsecondTimestamp===l.timestamp?(d.timestamp!==a.timestamp&&(d.timestampIsValid=!1),d.duration!==a.duration&&(d.durationIsValid=!1)):(this.preciseTimings.splice(m+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(l,u),l.close();else if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(l,u),l.close();else{this.splitter||(this.splitter=new pu);let{colorFrame:p,alphaFrame:b}=await this.splitter.split(l);this.alphaFrameQueue.push(b),this.encoder.encode(p,u),p.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;h(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let a=1;a<n;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=Wc({...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=ji.find(n=>n.supports(this.encodingConfig.codec,e));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(n,a)=>{if(!(n instanceof j))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.");fu(this.source._connectedTrack,n),this.encodingConfig.onEncodedPacket?.(n,a),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,a).catch(s=>{this.setError(s)})},this.customEncoder.onError=n=>{this.setError(n)},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,p)=>{let b={};if(f){let w=new Uint8Array(f.byteLength);f.copyTo(w),b.alpha=w}let g=j.fromEncodedChunk(d,b),y=K(this.preciseTimings,d.timestamp,w=>w.microsecondTimestamp),k=y!==-1?this.preciseTimings[y]:null,T=null;this.emittedEncoderPackets===0&&g.type==="delta"&&p?.decoderConfig&&(T=yr(this.encodingConfig.codec,p.decoderConfig,g.data)),(k&&k.microsecondTimestamp===d.timestamp||T!==null)&&(g=g.clone({timestamp:k?.timestampIsValid?k.timestamp:void 0,duration:k?.durationIsValid?k.duration:void 0,type:T??void 0})),fu(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,p),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,p).catch(w=>{this.setError(w)}),this.emittedEncoderPackets++},m=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(d,f)=>{if(!this.alphaEncoder){l(d,null,f);return}let p=this.alphaFrameQueue.shift();h(p!==void 0),p?(this.alphaEncoder.encode(p,{keyFrame:d.type==="key"}),u++,p.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.setError(d)}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){let d=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(f,p)=>{u--;let b=s.shift();for(h(b!==void 0),l(b.chunk,f,b.meta),c++;o.length>0&&o[0]===c;){o.shift();let g=s.shift();h(g!==void 0),l(g.chunk,null,g.meta)}},error:f=>{f.stack=d,this.setError(f)}}),this.alphaEncoder.configure(e)}}h(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=Ko(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,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(),await jr(25)),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.errorSet)throw this.error}},lu=null,pu=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!lu){let n=new Blob([`(${Hp.toString()})()`],{type:"application/javascript"});lu=URL.createObjectURL(n)}this.worker=new Worker(lu),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()})}let e=this.nextRequestId++,r=J();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Hp=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=c*u,m=Math.ceil(c/2),d=Math.ceil(u/2),f=l+m*d*2,p=new Uint8Array(f);for(let k=0,T=3;k<l;k++,T+=4)p[k]=a[T];p.fill(128,l);let b=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),g={format:"I420",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},y=new VideoFrame(p,g);return{colorFrame:b,alphaFrame:y}},n=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),m=s.includes("P12"),d=l||m?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let b=c*u,g=f*p,y=b*d,k=g*d,T=b*d,w=y+k*2,S=s.replace("A",""),P=Math.ceil(c/2),C=Math.ceil(u/2),x=P*C,A=x*d,I=T+2*A,E=new Uint8Array(I),_=w;E.set(a.subarray(_,_+T),0);let v=T,D=l?512:m?2048:128;d===1?E.fill(D,v):new Uint16Array(E.buffer,v,2*x).fill(D);let O=l?"I420P10":m?"I420P12":"I420",z=new VideoFrame(a.subarray(0,w),{format:S,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),H={format:O,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[E.buffer]},ie=new VideoFrame(E,H);return{colorFrame:z,alphaFrame:ie}}},fi=class extends Bt{constructor(t){$s(t),super(t.codec),this._encoder=new ua(this,t)}add(t,e){if(!(t instanceof Ve))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},To=class extends Bt{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");$s(e),super(e.codec),this._encoder=new ua(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");let n=new Ve(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},wo=class extends Bt{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if($s(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new ua(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=0,s=!1,o=null,c=0,u=()=>{if(h(e!==null),!this._lastVideoFrame)return;h(n!==null),h(r!==null);let d=performance.now();for(;d-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});m(p,d)}};e!==null&&(this._timerHandle=Hu(u,4));let l=d=>{if(e===null)m(d);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=d):(m(d.clone(),f),n=f,this._lastVideoFrame=d)}},m=(d,f=performance.now())=>{if(s){d.close();return}a++;let p=d.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}d.close();return}if(r===null){r=p;let g,y=this._options.timestampBase??"synced-zero";if(y==="unix")g=Date.now()/1e3;else if(y==="zero")g=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,g=0):g=f/1e3-k._firstMediaStreamTimestamp}c=g-r}if(o=p,this._encoder.getQueueSize()>=8){d.close();return}let b=new Ve(d,{timestamp:p+c});this._encoder.add(b,!0).catch(g=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(g),this._workerTrackId!==null&&mu({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let d=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});d.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await Qp())this._workerTrackId=Kp++,mu({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},et.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&qu(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(h(this._workerListener),mu({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(h(this._workerListener),et.removeEventListener("message",this._workerListener),et.removeEventListener("message",n),r())};et.addEventListener("message",n)})),await this._encoder.flushAndClose(e)}},Ot=class extends mi{constructor(e){super();this._connectedTrack=null;if(!oe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${oe.join(", ")}.`);this._codec=e}},Ur=class extends Ot{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},la=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new or;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new ko({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&bd(t.format)!==r.transform.sampleFormat){let n=yd(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process){let n=r.transform.process(t);if(n instanceof Promise&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);for(let a of n){if(!(a instanceof ke))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(a,!0)}e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),h(this.encoderInitialized),this.closed)return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=new ke({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{h(this.encoder);let r=t.toAudioData();this.encoder.encode(r),r.close(),e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){h(this.outputSampleSize),h(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t,o=2048,c=[];for(let d=0;d<n;d+=o){let f=Math.min(o,t.numberOfFrames-d),p=f*r*this.outputSampleSize,b=new ArrayBuffer(p),g=new DataView(b);c.push({frameCount:f,view:g})}let u=t.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let d=0;d<r;d++){t.copyTo(l,{planeIndex:d,format:"f32-planar"});for(let f=0;f<c.length;f++){let{frameCount:p,view:b}=c[f];for(let g=0;g<p;g++)this.writeOutputValue(b,(g*r+d)*this.outputSampleSize,l[f*o+g])}}e&&t.close();let m={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let d=0;d<c.length;d++){let{frameCount:f,view:p}=c[d],b=p.buffer,g=d*o,y=new j(new Uint8Array(b),"key",s+g/a,f/a);this.encodingConfig.onEncodedPacket?.(y,m),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,m)}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:e,sampleRate:r}=t,n=Hc({numberOfChannels:e,sampleRate:r,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);let a=Xi.find(s=>s.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(s,o)=>{if(!(s instanceof j))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(s,o),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,s,o).catch(c=>{this.setError(c)})},this.customEncoder.onError=s=>{this.setError(s)},await this.customEncoder.init();else if(re.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let o=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(c,u)=>{if(this.encodingConfig.codec==="aac"&&u?.decoderConfig){let m=!1;if(!u.decoderConfig.description||u.decoderConfig.description.byteLength<2?m=!0:m=Pt(X(u.decoderConfig.description)).objectType===0,m){let d=Number(Y(n.codec.split(".")));u.decoderConfig.description=Si({objectType:d,numberOfChannels:u.decoderConfig.numberOfChannels,sampleRate:u.decoderConfig.sampleRate})}}let l=j.fromEncodedChunk(c);l=l.clone({timestamp:St(l.timestamp,n.sampleRate),duration:c.duration!=null?St(l.duration,n.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(l,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u).catch(m=>{this.setError(m)})},error:c=>{c.stack=o,this.setError(c)}}),this.encoder.configure(n)}h(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Se(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ce((o+1)*127.5,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ce(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ce(Math.floor(o*32767),-32768,32767);a.setUint8(s,Rd(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ce(Math.floor(o*32767),-32768,32767);a.setUint8(s,Md(c))}:h(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ce((o+1)*32767.5,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ce(Math.round(o*32767),-32768,32767),n):h(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>Hr(a,s,ce((o+1)*83886075e-1,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Ru(a,s,ce(Math.round(o*8388607),-8388608,8388607),n):h(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ce((o+1)*21474836475e-1,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ce(Math.round(o*2147483647),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):h(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):h(!1);break;default:ee(r),h(!1)}}async flushAndClose(t){t||this.checkForEncoderError(),!t&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},an=class extends Ot{constructor(t){Ys(t),super(t.codec),this._encoder=new la(this,t)}add(t){if(!(t instanceof ke))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},So=class extends Ot{constructor(e){Ys(e);super(e.codec);this._accumulatedTime=0;this._encoder=new la(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=ke._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let n of r)await this._encoder.add(n,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Ao=class extends Ot{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Ys(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new la(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let m=this._connectedTrack.output;m._firstMediaStreamTimestamp===null?(m._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-m._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new ke(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let u=0;this._scriptProcessorNode.onaudioprocess=l=>{let m=ke._fromAudioBuffer(l.inputBuffer,u);u+=l.inputBuffer.duration;for(let d of m)s(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(h(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}},qp=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:ee(n)}})},Kp=0,et=null,Gp=()=>{let i=new Blob([`(${qp.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);et=new Worker(t)},du=null,Qp=async()=>du!==null?du:(et||Gp(),new Promise(i=>{h(et);let t=e=>{let r=e.data;r.type==="support"&&(du=r.supported,et.removeEventListener("message",t),i(r.supported))};et.addEventListener("message",t)})),mu=(i,t)=>{h(et),t?et.postMessage(i,t):et.postMessage(i)},pi=class extends mi{constructor(e){super();this._connectedTrack=null;if(!Be.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Be.join(", ")}.`);this._codec=e}},xo=class extends pi{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new no({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var Co=class extends Te{constructor(e,r){if(!(e._target instanceof Ke))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),r=this.output._tracks.some(y=>y.metadata.isRelativeToUnixEpoch),n=this.output._tracks.some(y=>!y.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,u=!1;for(let y of this.output._tracks){y.type==="video"&&(o=!0);let k=new Map;for(let T of this.output._tracks){if(y===T||!y.canBePairedWith(T))continue;if(y.type===T.type){c||(V._warn(`Illegal pairing of two ${y.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(y.isVideoTrack()&&y.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){u||(V._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let w=k.get(T.source._codec);w||k.set(T.source._codec,w=[]),w.push(T)}for(let[,T]of k){let w=T.map(C=>C.id).join("-");s.find(C=>C.key===w)||s.push({name:T[0].type+"-"+(s.length+1),key:w,tracks:T,needsEmit:!1,firstNoUri:!1});let P=a.get(y);P||a.set(y,P=[]),P.push(w)}}let l=o?"video":"audio",m=[],d=[],f=[];for(let y of this.output._tracks){let k=a.get(y);if(k){if(h(k.length>0),y.type!==l)continue;for(let T of k){let w=s.find(S=>S.key===T);if(h(w),k.length===1&&w.tracks.length===1){let S=a.get(w.tracks[0]);if(h(S!==void 0),S.length===1){let P=s.find(C=>C.key===S[0]);if(P.tracks.length===1){h(P.tracks[0]===y),m.push({tracks:[y,w.tracks[0]],linkedGroup:null});continue}}}m.push({tracks:[y],linkedGroup:w}),w.needsEmit=!0}}else y.type==="video"?d.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??te}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(d.length>0)if(new Set(d.map(p)).size>1){let k={key:d.map(T=>T.id).join("-"),name:"video-"+(s.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};s.push(k),m.push({tracks:[d[0]],linkedGroup:k})}else for(let k of d)m.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),m.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)m.push({tracks:[k],linkedGroup:null});let b=y=>{let k=[],T=0,w=0,S=!1,P=null,C=-1/0;for(let x of y)x.isVideoTrack()?(T++,S||=(x.metadata.rotation??0)!==0):x.isAudioTrack()&&w++,k.push(x.source._codec);for(let x of Wt(this.format._options.segmentFormat)){let A=x.getSupportedCodecs(),I=x.getSupportedTrackCounts();if(k.some(_=>!A.includes(_))||T<I.video.min||T>I.video.max||w<I.audio.min||w>I.audio.max)continue;let E=0;S&&x.supportsVideoRotationMetadata&&E++,E>C&&(P=x,C=E)}return h(P),P},g=async y=>{if(y.some(P=>this.playlists.some(C=>C.tracks.includes(P))))throw new Error("Internal error: track is already registered in a playlist.");let k=b(y),T=this.playlists.length+1,w=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});jp(w);let S={id:this.playlists.length+1,path:w,tracks:y,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new _e};return this.playlists.push(S),S};for(let y of s)if(y.needsEmit)for(let k=0;k<y.tracks.length;k++){let T=y.tracks[k],w=this.playlists.find(S=>S.tracks[0].id===T.id);w??=await g([T]),this.playlistDeclarations.push({playlist:w,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of m){let k=this.playlists.find(T=>T.tracks[0].id===y.tracks[0].id);k??=await g(y.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:y.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===y.linkedGroup.name):[]})}e()}async getMimeType(){return Ct}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));h(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;mr(r),h(r),h(r?.decoderConfig);let a=this.playlists.filter(s=>s.tracks.includes(e));return h(a.length===1),n={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"video",decoderConfig:r.decoderConfig}},this.trackDatas.push(n),n}getAudioTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Re(r),h(r),h(r?.decoderConfig);let a=this.playlists.filter(s=>s.tracks.includes(e));return h(a.length===1),n={track:e,packets:[],playlist:a[0],closed:!1,info:{type:"audio",decoderConfig:r.decoderConfig}},this.trackDatas.push(n),n}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(h(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}let r=this.trackDatas.filter(s=>e.tracks.includes(s.track)),n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let w=n.packets.every(C=>C.timestamp<s),S=null,P=null;if(w){if(!n.closed)return}else for(let C=0;C<n.packets.length;C++){let x=n.packets[C];if(S!==null&&x.timestamp>s)break;C>0&&x.type==="key"&&(S=x,P=C)}if(P!==null){if(o=P,a){let C=a.packets.findIndex(x=>x.timestamp>=S.timestamp);if(C!==-1)c=C;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let C=Nu(n.packets,A=>A.timestamp),x=n.packets[C];if(h(x),a)if(x.timestamp<s){let A=a.packets.findIndex(I=>I.timestamp>=s);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}else{let A=a.packets.findIndex(I=>I.timestamp>x.timestamp);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(S=>S.timestamp<s))if(a.closed)c=a.packets.length;else return;else{let S=ur(a.packets,P=>P.timestamp<=s);c=Math.max(S,1)}if(o===0&&c===0){r.every(S=>S.closed)&&await this.onPlaylistDone(e);return}let u=null,l,m;h(this.output._target instanceof Ke);let d=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let w={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Po(e)};l=await this.getSegmentPath(w),hm(l),m=he(he(d.rootPath,e.path),l);let S=await this.output._getTarget({path:m,isRoot:!1,mimeType:e.segmentFormat.mimeType});S._start(),e.singleFile={target:S,path:l,nextOffset:0,info:w}}else l=e.singleFile.path,m=he(he(d.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Po(e)},l=await this.getSegmentPath(u),hm(l),m=he(he(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,b=new sr({format:e.segmentFormat,target:new Ke(m,async w=>{let S={...w,isRoot:!1};if(w.isRoot)if(e.singleFile){let P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:C})=>f=Math.max(f,C)),P}else{let P=await this.output._getTarget(S);return p=P,P.on("write",({end:C})=>f=Math.max(f,C)),P}return this.output._getTarget(S)}),initTarget:async()=>{if(e.initSegment)return new Dr;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let w=e.singleFile.target.slice(e.singleFile.nextOffset);return w.on("write",({end:S})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,S)}),w.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),w}else{let w=Po(e),S=await this.getInitPath(w);Xp(S),e.initSegment={path:S,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let P=he(he(d.rootPath,e.path),S),C=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return C.on("write",({end:x})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,x)}),C.on("finalized",()=>{this.format._options.onInit?.(C,w)}),C}}}),g=-1/0;try{let w=null,S=null;if(n&&(w=new Vr(n.track.source._codec),b.addVideoTrack(w,n.track.metadata)),a&&(S=new Ur(a.track.source._codec),b.addAudioTrack(S,a.track.metadata)),await b.start(),n){h(w);let P={decoderConfig:n.info.decoderConfig};for(let C=0;C<o;C++){let x=n.packets[C];await w.add(x,P),g=Math.max(g,x.timestamp+x.duration)}}if(a){h(S);let P={decoderConfig:a.info.decoderConfig};for(let C=0;C<c;C++){let x=a.packets[C];await S.add(x,P),g=Math.max(g,x.timestamp+x.duration)}}await b.finalize()}catch(w){throw await b.cancel(),w}u&&(h(p),this.format._options.onSegment?.(p,u)),o>0&&(h(n),n.packets.splice(0,o)),c>0&&(h(a),a.packets.splice(0,c));let y=1/0;n&&n.packets.length>0&&(y=n.packets[0].timestamp),a&&a.packets.length>0&&(y=Math.min(y,a.packets[0].timestamp));let k=y<1/0?y:g;h(Number.isFinite(k));let T=k-e.currentSegmentStartTimestamp;if(h(T>=0),e.writtenSegments.push({path:l,duration:T,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,T),e.currentSegmentStartTimestamp=k,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let w=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(h(w.info),this.format._options.onSegmentPopped?.(w.path,w.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){h(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let o=0;o<r.length;o++){s+=r[o].duration;let c=0,u=0;for(let l=o;l<r.length&&(c+=r[l].byteSize,u+=r[l].duration,u>=.5*this.globalTargetDuration&&u<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*c/u)),!(u>1.5*this.globalTargetDuration));l++);}if(n===0)for(let o of r){let c=o.duration||1;n=Math.max(n,8*o.byteSize/c)}for(let o of r)a+=8*o.byteSize;e.peakBitrate=n,e.averageBitrate=a/(s||1)}async writePlaylist(e){h(this.output._target instanceof Ke);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let d of e.writtenSegments)n||=d.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=he(r.rootPath,e.path),u=`#EXTM3U
18
18
  #EXT-X-VERSION:${s}
19
19
  `+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
20
20
  `)+`#EXT-X-TARGETDURATION:${Math.ceil(o)}