polotno-node 3.0.1 → 3.0.3
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/dist/assets/{html2canvas-BeKaVBkZ.js → html2canvas-C8a2rCl7.js} +1 -1
- package/dist/assets/{index-DFqP22V0.js → index-nUNsrps4.js} +77 -76
- package/dist/assets/{index.es-DwOGAynS.js → index.es-Cv2hC1UF.js} +1 -1
- package/dist/assets/{jspdf.es.min-BBVOPmzA.js → jspdf.es.min-CAO1hjjP.js} +4 -4
- package/dist/assets/{lib-CuK_SezV.js → lib-BVF9HFUh.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as e,A as t,B as n,C as r,Ct as i,D as a,Dt as o,E as s,Et as c,F as l,G as u,H as d,I as f,J as p,K as m,L as h,M as g,N as _,O as v,P as y,Q as b,R as x,S as ee,St as te,T as ne,Tt as S,U as C,V as w,W as re,X as ie,Y as ae,Z as oe,_ as T,_t as E,a as se,at as ce,b as le,bt as ue,c as de,ct as fe,d as pe,dt as me,et as he,f as ge,ft as _e,g as D,gt as ve,h as ye,ht as O,i as be,it as xe,j as Se,k as Ce,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,s as Le,st as k,tt as Re,u as ze,ut as A,v as Be,vt as Ve,w as He,wt as Ue,x as We,xt as Ge,y as Ke,yt as qe,z as Je}from"./index-DFqP22V0.js";var Ye=class{constructor(e){this.mutex=new Re,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Xe=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ze=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},Qe=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);k(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},j=new Uint8Array(8),M=new DataView(j.buffer),N=e=>[(e%256+256)%256],P=e=>(M.setUint16(0,e,!1),[j[0],j[1]]),$e=e=>(M.setInt16(0,e,!1),[j[0],j[1]]),et=e=>(M.setUint32(0,e,!1),[j[1],j[2],j[3]]),F=e=>(M.setUint32(0,e,!1),[j[0],j[1],j[2],j[3]]),I=e=>(M.setInt32(0,e,!1),[j[0],j[1],j[2],j[3]]),L=e=>(M.setUint32(0,Math.floor(e/2**32),!1),M.setUint32(4,e,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),tt=e=>(M.setInt32(0,Math.floor(e/2**32),!1),M.setUint32(4,e,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),nt=e=>(M.setInt16(0,2**8*e,!1),[j[0],j[1]]),R=e=>(M.setInt32(0,2**16*e,!1),[j[0],j[1],j[2],j[3]]),rt=e=>(M.setInt32(0,2**30*e,!1),[j[0],j[1],j[2],j[3]]),it=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},z=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},at=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},ot=at(0),st=e=>[R(e[0]),R(e[1]),rt(e[2]),R(e[3]),R(e[4]),rt(e[5]),R(e[6]),R(e[7]),rt(e[8])],B=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),V=(e,t,n,r,i)=>B(e,[N(t),et(n),r??[]],i),ct=e=>e.isQuickTime?B(`ftyp`,[z(`qt `),F(512),z(`qt `)]):e.fragmented?e.cmaf?B(`ftyp`,[z(`iso5`),F(512),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]):B(`ftyp`,[z(`iso5`),F(512),z(`iso5`),z(`iso6`),z(`mp41`)]):B(`ftyp`,[z(`isom`),F(512),z(`isom`),e.holdsAvc?z(`avc1`):[],z(`mp41`)]),lt=()=>B(`styp`,[z(`iso5`),F(0),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]),ut=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),V(`sidx`,1,0,[F(1),F(X),L(Z(e.minWrittenTimestamp,X)),L(0),P(0),P(1),F(t&2147483647),F(Z(n,X)),F(0)])},H=e=>({type:`mdat`,largeSize:e}),dt=e=>({type:`free`,size:e}),U=e=>B(`moov`,void 0,[ft(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>pt(t,e.creationTime)),e.isFragmented?Qt(e.trackDatas):null,mn(e)]),ft=(e,t)=>{let n=Math.max(0,...t.map(e=>Z(W(e),X)+Z(e.startTimestampOffset??0,X))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!O(e)||!O(n),a=i?L:F;return V(`mvhd`,+i,0,[a(e),a(e),F(X),a(n),R(1),nt(1),Array(10).fill(0),st(ot),Array(24).fill(0),F(r)])},W=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},pt=(e,t)=>{let n=Pn(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return B(`trak`,void 0,[mt(e,t),r?ht(e,e.startTimestampOffset):null,gt(e,t),n.name===void 0?null:B(`udta`,void 0,[B(`name`,[...i.encode(n.name)])])])},mt=(e,t)=>{let n=Z(W(e),X)+Z(e.startTimestampOffset??0,X),r=!O(t)||!O(n),i=r?L:F,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=at(t??0)}else a=ot;let o=2;return e.track.metadata.disposition?.default!==!1&&(o|=1),V(`tkhd`,+r,o,[i(t),i(t),F(e.track.id),F(0),i(n),Array(8).fill(0),P(0),P(e.track.id),nt(+(e.type===`audio`)),P(0),st(a),R(e.type===`video`?e.info.width:0),R(e.type===`video`?e.info.height:0)])},ht=(e,t)=>{let n=Z(t,X),r=Z(W(e),X),i=!O(n)||!O(r),a=i?L:F,o=i?tt:I;return B(`edts`,void 0,[V(`elst`,+!!i,0,[F(2),a(n),o(-1),R(1),a(r),o(0),R(1)])])},gt=(e,t)=>B(`mdia`,void 0,[_t(e,t),bt(!0,vt[e.type],yt[e.type]),xt(e)]),_t=(e,t)=>{let n=Z(W(e),e.timescale),r=!O(t)||!O(n),i=r?L:F;return V(`mdhd`,+r,0,[i(t),i(t),F(e.timescale),i(n),P(En(e.track.metadata.languageCode??`und`)),P(0)])},vt={video:`vide`,audio:`soun`,subtitle:`text`},yt={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},bt=(e,t,n,r=`\0\0\0\0`)=>V(`hdlr`,0,0,[e?z(`mhlr`):F(0),z(t),z(r),F(0),F(0),z(n,!0)]),xt=e=>B(`minf`,void 0,[St[e.type](),Ct(),Et(e)]),St={video:()=>V(`vmhd`,0,1,[P(0),P(0),P(0),P(0)]),audio:()=>V(`smhd`,0,0,[P(0),P(0)]),subtitle:()=>V(`nmhd`,0,0)},Ct=()=>B(`dinf`,void 0,[wt()]),wt=()=>V(`dref`,0,0,[F(1)],[Tt()]),Tt=()=>V(`url `,0,1),Et=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B(`stbl`,void 0,[Dt(e),Gt(e),t?Xt(e):null,t?Zt(e):null,qt(e),Jt(e),Yt(e),Kt(e)])},Dt=e=>{let t;if(e.type===`video`)t=Ot(bn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Sn(e.track.source._codec,e.muxer.isQuickTime);k(n),t=Ft(n,e)}else e.type===`subtitle`&&(t=Ut(wn[e.track.source._codec],e));return k(t),V(`stsd`,0,0,[F(1)],[t])},Ot=(e,t)=>B(e,[[,,,,,,].fill(0),P(1),P(0),P(0),Array(12).fill(0),P(t.info.width),P(t.info.height),F(4718592),F(4718592),F(0),P(1),Array(32).fill(0),P(24),$e(65535)],[xn[t.track.source._codec](t),kt(t),me(t.info.decoderConfig.colorSpace)?At(t):null]),kt=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:B(`pasp`,[F(e.info.pixelAspectRatio.num),F(e.info.pixelAspectRatio.den)]),At=e=>B(`colr`,[z(e.muxer.isQuickTime?`nclc`:`nclx`),P(ke[e.info.decoderConfig.colorSpace.primaries]),P(je[e.info.decoderConfig.colorSpace.transfer]),P(ce[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:N(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),jt=e=>e.info.decoderConfig&&B(`avcC`,[...S(e.info.decoderConfig.description)]),Mt=e=>e.info.decoderConfig&&B(`hvcC`,[...S(e.info.decoderConfig.description)]),Nt=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?ke[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?je[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ce[t.colorSpace.matrix]:2;return V(`vpcC`,1,0,[N(r),N(i),N(c),N(l),N(u),N(d),P(0)])},Pt=e=>B(`av1C`,d(e.info.decoderConfig.codec)),Ft=(e,t)=>{let n=0,r,i=16,a=Je.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=C(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),P(1),P(n),P(0),F(0),P(t.info.numberOfChannels),P(i),P(0),P(0),P(t.info.sampleRate<2**16?t.info.sampleRate:0),P(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),P(1),P(n),P(0),F(0),P(t.info.numberOfChannels),P(Math.min(i,16)),$e(e),P(0),P(t.info.sampleRate<2**16?t.info.sampleRate:0),P(0),a?[F(1),F(i/8),F(t.info.numberOfChannels*i/8)]:[F(0),F(0),F(0)],F(2)]}return B(e,r,[Cn(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},It=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...N(t),...N(21),...et(0),...F(0),...F(0)];if(e.info.decoderConfig.description){let t=S(e.info.decoderConfig.description);n=[...n,...N(5),...it(t.byteLength),...t]}return n=[...P(1),...N(0),...N(4),...it(n.length),...n,...N(6),...N(1),...N(2)],n=[...N(3),...it(n.length),...n],V(`esds`,0,0,n)},G=e=>B(`wave`,void 0,[Lt(e),Rt(e),B(`\0\0\0\0`)]),Lt=e=>B(`frma`,[z(Sn(e.track.source._codec,e.muxer.isQuickTime))]),Rt=e=>{let{littleEndian:t}=C(e.track.source._codec);return B(`enda`,[P(+t)])},zt=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){k(s.byteLength>=18);let e=y(S(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return B(`dOps`,[N(0),N(t),P(n),F(r),$e(i),N(a),...o])},Bt=e=>{let t=e.info.decoderConfig?.description;return k(t),V(`dfLa`,0,0,[...S(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=C(e.track.source._codec);return V(`pcmC`,0,0,[N(+t),N(8*n)])},Vt=e=>{let t=g(e.info.firstPacket.data);if(!t)throw 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 n=new Uint8Array(3),r=new oe(n);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),B(`dac3`,[...n])},Ht=e=>{let t=_(e.info.firstPacket.data);if(!t)throw 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 n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new oe(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return B(`dec3`,[...i])},Ut=(e,t)=>B(e,[[,,,,,,].fill(0),P(1)],[Tn[t.track.source._codec](t)]),Wt=e=>B(`vttC`,[...i.encode(e.info.config.description)]),Gt=e=>V(`stts`,0,0,[F(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),Kt=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return V(`stss`,0,0,[F(t.length),t.map(([e])=>F(e+1))])},qt=e=>V(`stsc`,0,0,[F(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),Jt=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=C(e.track.source._codec);return V(`stsz`,0,0,[F(t*e.info.numberOfChannels),F(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return V(`stsz`,0,0,[F(0),F(e.samples.length),e.samples.map(e=>F(e.size))])},Yt=e=>e.finalizedChunks.length>0&&E(e.finalizedChunks).offset>=2**32?V(`co64`,0,0,[F(e.finalizedChunks.length),e.finalizedChunks.map(e=>L(e.offset))]):V(`stco`,0,0,[F(e.finalizedChunks.length),e.finalizedChunks.map(e=>F(e.offset))]),Xt=e=>V(`ctts`,1,0,[F(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),I(e.sampleCompositionTimeOffset)])]),Zt=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;k(e.compositionTimeOffsetTable.length>0),k(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:V(`cslg`,0,0,[I(a),I(t),I(n),I(r),I(i)])},Qt=e=>B(`mvex`,void 0,e.map($t)),$t=e=>V(`trex`,0,0,[F(e.track.id),F(1),F(0),F(0),F(0)]),en=(e,t)=>B(`moof`,void 0,[tn(e),...t.map(rn)]),tn=e=>V(`mfhd`,0,0,[F(e)]),nn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},rn=e=>B(`traf`,void 0,[an(e),on(e),sn(e)]),an=e=>{k(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:nn(n)};return V(`tfhd`,0,t,[F(e.track.id),F(r.duration),F(r.size),F(r.flags)])},on=e=>(k(e.currentChunk),V(`tfdt`,1,0,[L(Z(e.currentChunk.startTimestamp,e.timescale))])),sn=e=>{k(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(nn),i=e.currentChunk.samples.map(t=>Z(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,V(`trun`,1,m,[F(e.currentChunk.samples.length),F(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?F(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?F(t[a]):[],d?F(n[a]):[],f?F(r[a]):[],p?I(i[a]):[]])])},cn=e=>B(`mfra`,void 0,[...e.map(ln),un()]),ln=(e,t)=>V(`tfra`,1,0,[F(e.track.id),F(63),F(e.finalizedChunks.length),e.finalizedChunks.map(n=>[L(Z(n.samples[0].timestamp,e.timescale)),L(n.moofOffset),F(t+1),F(1),F(1)])]),un=()=>V(`mfro`,0,0,[F(0)]),dn=()=>B(`vtte`),fn=(e,t,n,r,a)=>B(`vttc`,void 0,[a===null?null:B(`vsid`,[I(a)]),n===null?null:B(`iden`,[...i.encode(n)]),t===null?null:B(`ctim`,[...i.encode(Ze(t))]),r===null?null:B(`sttg`,[...i.encode(r)]),B(`payl`,[...i.encode(e)])]),pn=e=>B(`vtta`,[...i.encode(e)]),mn=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=vn(r);e&&t.push(e)}else if(n===`mdta`){let e=yn(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&hn(t,e.output._metadataTags);return t.length===0?null:B(`udta`,void 0,t)},hn=(e,t)=>{for(let{key:n,value:r}of ve(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:fe(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(q(n,r)):r instanceof Uint8Array&&e.push(B(n,Array.from(r))))}},q=(e,t)=>{let n=i.encode(t);return B(e,[P(n.length),P(En(`und`)),Array.from(n)])},gn={"image/jpeg":13,"image/png":14,"image/bmp":27},_n=(e,t)=>{let n=[];for(let{key:r,value:i}of ve(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:J(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:J(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:J(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:J(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:J(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:J(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:J(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:J(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:B(`data`,[F(gn[e.mimeType]??0),F(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:J(t)})}else n.push({key:`trkn`,value:B(`data`,[F(0),F(0),P(0),P(i),P(e.tracksTotal??0),P(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:B(`data`,[F(0),F(0),P(0),P(i),P(e.discsTotal??0),P(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:fe(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:J(i)}):i instanceof Uint8Array?n.push({key:r,value:B(`data`,[F(0),F(0),Array.from(i)])}):i instanceof b&&n.push({key:r,value:B(`data`,[F(gn[i.mimeType]??0),F(0),Array.from(i.data)])}))}return n},vn=e=>{let t=_n(e,!1);return t.length===0?null:V(`meta`,0,0,void 0,[bt(!1,`mdir`,``,`appl`),B(`ilst`,void 0,t.map(e=>B(e.key,void 0,[e.value])))])},yn=e=>{let t=_n(e,!0);return t.length===0?null:B(`meta`,void 0,[bt(!1,`mdta`,``),V(`keys`,0,0,[F(t.length)],t.map(e=>B(`mdta`,[...i.encode(e.key)]))),B(`ilst`,void 0,t.map((e,t)=>B(String.fromCharCode(...F(t+1)),void 0,[e.value])))])},J=e=>B(`data`,[F(1),F(0),...i.encode(e)]),bn=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},xn={avc:jt,hevc:Mt,vp8:Nt,vp9:Nt,av1:Pt},Sn=(e,t)=>{switch(e){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(e){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(e){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`}},Cn=(e,t)=>{switch(e){case`aac`:return It;case`mp3`:return It;case`opus`:return zt;case`vorbis`:return It;case`flac`:return Bt;case`ac3`:return Vt;case`eac3`:return Ht}if(t)switch(e){case`pcm-s24`:return G;case`pcm-s24be`:return G;case`pcm-s32`:return G;case`pcm-s32be`:return G;case`pcm-f32`:return G;case`pcm-f32be`:return G;case`pcm-f64`:return G;case`pcm-f64be`:return G}else switch(e){case`pcm-s16`:return K;case`pcm-s16be`:return K;case`pcm-s24`:return K;case`pcm-s24be`:return K;case`pcm-s32`:return K;case`pcm-s32be`:return K;case`pcm-f32`:return K;case`pcm-f32be`:return K;case`pcm-f64`:return K;case`pcm-f64be`:return K}return null},wn={webvtt:`wvtt`},Tn={webvtt:Wt},En=e=>{k(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Dn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){k(!this.started),this.target._start(),this.started=!0}write(e){k(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return k(this.started&&!this.finalized),this.target._flush()}async finalize(){k(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw 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}};r();var Y=class extends xe{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new jn(this,e)}},On=2**16,kn=2**32,An=class extends Y{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw 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(On,{maxByteLength:kn})}catch{this._buffer=new ArrayBuffer(On),this._supportsResize=!1}else this._buffer=new ArrayBuffer(On);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>kn)throw Error(`ArrayBuffer exceeded maximum size of ${kn} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},jn=class extends Y{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Mn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},X=57600,Nn=2082844800,Pn=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Fn=class extends Ye{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new An,this.auxWriter=new Dn(this.auxTarget,!1),this.auxBoxWriter=new Qe(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ve(),this.creationTime=Math.floor(Date.now()/1e3)+Nn,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof $n,this.isCmaf=t instanceof Qn,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Qn?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(e=>this.format._options.fastStart===void 0?e instanceof An:this.format._options.fastStart===`fragmented`),this.boxWriter=new Qe(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof An?`in-memory`:!1),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new Dn(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Qe(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(k(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(ct({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(k(this.writer),k(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=H(!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(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ne({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;m(r),k(r),k(r.decoderConfig);let a={...r.decoderConfig};k(a.codedWidth!==void 0),k(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){let e=Ce(n.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=l(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){let e=t(n.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=f(e),o=!0}let s=_e(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,u=a.displayAspectHeight,d=c===void 0||u===void 0?{num:1,den:1}:te({num:c*a.codedHeight,den:u*a.codedWidth}),p={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:d,decoderConfig:a,requiresAnnexBTransformation:o},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(p),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;re(n),k(n),k(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=He(Oe.tempFromBytes(t.data));if(!e)throw 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 n=p[e.samplingFrequencyIndex],r=Pe[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=ae({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Je.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;u(t),k(t),k(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Se(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw 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.`);i=a(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let o=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=He(Oe.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=C(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=C(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)k(r.timestamp<=t),k(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=dn();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;Xe.lastIndex=0;let r=Xe.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=pn(n.notes);this.auxBoxWriter.writeBox(e)}let c=fn(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=E(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){k(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(k(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=E(e.timeToSampleTable);if(k(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=E(e.compositionTimeOffsetTable);k(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,k(e.lastSample),k(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){k(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(k(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),k(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(k(!this.isFragmented),k(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||E(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)k(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(k(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){k(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;k(e),this.format._options.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=U(this);if(e.writeBox(t),this.format._options.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onMoov(t,n)}if(this.isCmaf){k(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Qe(this.writer);let e=this.boxWriter.measureBox(lt()),t=this.boxWriter.measureBox(ut(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}k(this.writer),k(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk),r=en(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=en(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}k(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=H(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(k(this.writer),k(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let e=U(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;k(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=H(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){k(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;k(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 t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e),k(e.startTimestampOffset!==null);for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(k(this.writer),k(this.boxWriter),this.fastStart===`in-memory`){this.mdat=H(!1);let e;for(let t=0;t<2;t++){let t=U(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)k(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=U(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)k(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(lt()),this.boxWriter.writeBox(ut(this,e))}else{let e=this.writer.getPos(),t=cn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{k(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);k(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=U(this);if(this.fastStart===`reserve`){k(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(dt(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},In=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){k(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),k(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor(i*this.targetSampleRate),s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;k(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame===null?this.maxWrittenFrame=n:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;k(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new D({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},Ln=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Rn=class extends Ln{constructor(e){if(super(),this._connectedTrack=null,!w.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${w.join(`, `)}.`);this._codec=e}},zn=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Bn=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.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 Ie,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let i=this.encodingConfig,a=i.sizeChangeBehavior??`deny`,o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(i.transform?.width!==void 0||i.transform?.height!==void 0||i.transform?.rotate!==void 0||i.transform?.crop!==void 0||i.transform?.force===!0||o&&a!==`passThrough`){let n=i.transform?.width,r=i.transform?.height,s=i.transform?.fit??`fill`;o&&a!==`passThrough`&&(k(this.outputWidth),k(this.outputHeight),k(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,fit:s,alpha:i.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else (this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let s=i.transform?.frameRate;if(s!==void 0){let i=e.timestamp+e.duration,a=Ne(e.timestamp,s);if(this.frameRateLastSample!==null)if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=i;return}else await this.padFrameRate(a,n);e===r&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/s),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=i}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,r;if(n.transform?.process){let t=n.transform.process(e);if(t instanceof Promise&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]),r=t.map(t=>t instanceof T?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new T(t):new T(t,{timestamp:e.timestamp,duration:e.duration}))}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),k(this.encoderInitialized),this.closed)break;let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{k(this.encoder);let t=e.toVideoFrame(),n=Te(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),r=n===-1?null:this.preciseTimings[n];if(r&&r.microsecondTimestamp===t.timestamp?(r.timestamp!==e.timestamp&&(r.timestampIsValid=!1),r.duration!==e.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(t,a),t.close();else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(t,a),t.close();else{let e=t.displayWidth,n=t.displayHeight;this.splitter||=new Hn(e,n);let{colorFrame:r,alphaFrame:i}=await this.splitter.update(t);this.alphaFrameQueue.push(i),this.encoder.encode(r,a),r.close()}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;k(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r=this.frameRateLastSample.clone();r.setTimestamp(this.frameRateLastTimestamp+e/n),r.setDuration(1/n),await this.processAndEncode(r,t),r.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=pe({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=de.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof s))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);zn(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=s.fromEncodedChunk(e,r),a=Te(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],c=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(c=v(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||c!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:c??void 0})),zn(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e}),this.emittedEncoderPackets++},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();k(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(k(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();k(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}k(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,t=Ne(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Vn=!1,Hn=class e{constructor(t,n){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let r=typeof OffscreenCanvas<`u`||typeof document<`u`&&typeof document.createElement==`function`;if(!e.forceCpu&&r&&!Vn)try{typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(t,n):(this.canvas=document.createElement(`canvas`),this.canvas.width=t,this.canvas.height=n);let e=this.canvas.getContext(`webgl2`,{alpha:!0});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}catch(e){this.gl=null,this.canvas=null,Vn=!0,console.warn(`Falling back to CPU for color/alpha splitting.`,e)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){k(this.gl),k(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return k(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
1
|
+
import{$ as e,A as t,B as n,C as r,Ct as i,D as a,Dt as o,E as s,Et as c,F as l,G as u,H as d,I as f,J as p,K as m,L as h,M as g,N as _,O as v,P as y,Q as b,R as x,S as ee,St as te,T as ne,Tt as S,U as C,V as w,W as re,X as ie,Y as ae,Z as oe,_ as T,_t as E,a as se,at as ce,b as le,bt as ue,c as de,ct as fe,d as pe,dt as me,et as he,f as ge,ft as _e,g as D,gt as ve,h as ye,ht as O,i as be,it as xe,j as Se,k as Ce,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,s as Le,st as k,tt as Re,u as ze,ut as A,v as Be,vt as Ve,w as He,wt as Ue,x as We,xt as Ge,y as Ke,yt as qe,z as Je}from"./index-nUNsrps4.js";var Ye=class{constructor(e){this.mutex=new Re,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Xe=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ze=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},Qe=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);k(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},j=new Uint8Array(8),M=new DataView(j.buffer),N=e=>[(e%256+256)%256],P=e=>(M.setUint16(0,e,!1),[j[0],j[1]]),$e=e=>(M.setInt16(0,e,!1),[j[0],j[1]]),et=e=>(M.setUint32(0,e,!1),[j[1],j[2],j[3]]),F=e=>(M.setUint32(0,e,!1),[j[0],j[1],j[2],j[3]]),I=e=>(M.setInt32(0,e,!1),[j[0],j[1],j[2],j[3]]),L=e=>(M.setUint32(0,Math.floor(e/2**32),!1),M.setUint32(4,e,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),tt=e=>(M.setInt32(0,Math.floor(e/2**32),!1),M.setUint32(4,e,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),nt=e=>(M.setInt16(0,2**8*e,!1),[j[0],j[1]]),R=e=>(M.setInt32(0,2**16*e,!1),[j[0],j[1],j[2],j[3]]),rt=e=>(M.setInt32(0,2**30*e,!1),[j[0],j[1],j[2],j[3]]),it=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},z=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},at=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},ot=at(0),st=e=>[R(e[0]),R(e[1]),rt(e[2]),R(e[3]),R(e[4]),rt(e[5]),R(e[6]),R(e[7]),rt(e[8])],B=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),V=(e,t,n,r,i)=>B(e,[N(t),et(n),r??[]],i),ct=e=>e.isQuickTime?B(`ftyp`,[z(`qt `),F(512),z(`qt `)]):e.fragmented?e.cmaf?B(`ftyp`,[z(`iso5`),F(512),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]):B(`ftyp`,[z(`iso5`),F(512),z(`iso5`),z(`iso6`),z(`mp41`)]):B(`ftyp`,[z(`isom`),F(512),z(`isom`),e.holdsAvc?z(`avc1`):[],z(`mp41`)]),lt=()=>B(`styp`,[z(`iso5`),F(0),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]),ut=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),V(`sidx`,1,0,[F(1),F(X),L(Z(e.minWrittenTimestamp,X)),L(0),P(0),P(1),F(t&2147483647),F(Z(n,X)),F(0)])},H=e=>({type:`mdat`,largeSize:e}),dt=e=>({type:`free`,size:e}),U=e=>B(`moov`,void 0,[ft(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>pt(t,e.creationTime)),e.isFragmented?Qt(e.trackDatas):null,mn(e)]),ft=(e,t)=>{let n=Math.max(0,...t.map(e=>Z(W(e),X)+Z(e.startTimestampOffset??0,X))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!O(e)||!O(n),a=i?L:F;return V(`mvhd`,+i,0,[a(e),a(e),F(X),a(n),R(1),nt(1),Array(10).fill(0),st(ot),Array(24).fill(0),F(r)])},W=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},pt=(e,t)=>{let n=Pn(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return B(`trak`,void 0,[mt(e,t),r?ht(e,e.startTimestampOffset):null,gt(e,t),n.name===void 0?null:B(`udta`,void 0,[B(`name`,[...i.encode(n.name)])])])},mt=(e,t)=>{let n=Z(W(e),X)+Z(e.startTimestampOffset??0,X),r=!O(t)||!O(n),i=r?L:F,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=at(t??0)}else a=ot;let o=2;return e.track.metadata.disposition?.default!==!1&&(o|=1),V(`tkhd`,+r,o,[i(t),i(t),F(e.track.id),F(0),i(n),Array(8).fill(0),P(0),P(e.track.id),nt(+(e.type===`audio`)),P(0),st(a),R(e.type===`video`?e.info.width:0),R(e.type===`video`?e.info.height:0)])},ht=(e,t)=>{let n=Z(t,X),r=Z(W(e),X),i=!O(n)||!O(r),a=i?L:F,o=i?tt:I;return B(`edts`,void 0,[V(`elst`,+!!i,0,[F(2),a(n),o(-1),R(1),a(r),o(0),R(1)])])},gt=(e,t)=>B(`mdia`,void 0,[_t(e,t),bt(!0,vt[e.type],yt[e.type]),xt(e)]),_t=(e,t)=>{let n=Z(W(e),e.timescale),r=!O(t)||!O(n),i=r?L:F;return V(`mdhd`,+r,0,[i(t),i(t),F(e.timescale),i(n),P(En(e.track.metadata.languageCode??`und`)),P(0)])},vt={video:`vide`,audio:`soun`,subtitle:`text`},yt={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},bt=(e,t,n,r=`\0\0\0\0`)=>V(`hdlr`,0,0,[e?z(`mhlr`):F(0),z(t),z(r),F(0),F(0),z(n,!0)]),xt=e=>B(`minf`,void 0,[St[e.type](),Ct(),Et(e)]),St={video:()=>V(`vmhd`,0,1,[P(0),P(0),P(0),P(0)]),audio:()=>V(`smhd`,0,0,[P(0),P(0)]),subtitle:()=>V(`nmhd`,0,0)},Ct=()=>B(`dinf`,void 0,[wt()]),wt=()=>V(`dref`,0,0,[F(1)],[Tt()]),Tt=()=>V(`url `,0,1),Et=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B(`stbl`,void 0,[Dt(e),Gt(e),t?Xt(e):null,t?Zt(e):null,qt(e),Jt(e),Yt(e),Kt(e)])},Dt=e=>{let t;if(e.type===`video`)t=Ot(bn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Sn(e.track.source._codec,e.muxer.isQuickTime);k(n),t=Ft(n,e)}else e.type===`subtitle`&&(t=Ut(wn[e.track.source._codec],e));return k(t),V(`stsd`,0,0,[F(1)],[t])},Ot=(e,t)=>B(e,[[,,,,,,].fill(0),P(1),P(0),P(0),Array(12).fill(0),P(t.info.width),P(t.info.height),F(4718592),F(4718592),F(0),P(1),Array(32).fill(0),P(24),$e(65535)],[xn[t.track.source._codec](t),kt(t),me(t.info.decoderConfig.colorSpace)?At(t):null]),kt=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:B(`pasp`,[F(e.info.pixelAspectRatio.num),F(e.info.pixelAspectRatio.den)]),At=e=>B(`colr`,[z(e.muxer.isQuickTime?`nclc`:`nclx`),P(ke[e.info.decoderConfig.colorSpace.primaries]),P(je[e.info.decoderConfig.colorSpace.transfer]),P(ce[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:N(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),jt=e=>e.info.decoderConfig&&B(`avcC`,[...S(e.info.decoderConfig.description)]),Mt=e=>e.info.decoderConfig&&B(`hvcC`,[...S(e.info.decoderConfig.description)]),Nt=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?ke[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?je[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ce[t.colorSpace.matrix]:2;return V(`vpcC`,1,0,[N(r),N(i),N(c),N(l),N(u),N(d),P(0)])},Pt=e=>B(`av1C`,d(e.info.decoderConfig.codec)),Ft=(e,t)=>{let n=0,r,i=16,a=Je.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=C(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),P(1),P(n),P(0),F(0),P(t.info.numberOfChannels),P(i),P(0),P(0),P(t.info.sampleRate<2**16?t.info.sampleRate:0),P(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),P(1),P(n),P(0),F(0),P(t.info.numberOfChannels),P(Math.min(i,16)),$e(e),P(0),P(t.info.sampleRate<2**16?t.info.sampleRate:0),P(0),a?[F(1),F(i/8),F(t.info.numberOfChannels*i/8)]:[F(0),F(0),F(0)],F(2)]}return B(e,r,[Cn(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},It=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...N(t),...N(21),...et(0),...F(0),...F(0)];if(e.info.decoderConfig.description){let t=S(e.info.decoderConfig.description);n=[...n,...N(5),...it(t.byteLength),...t]}return n=[...P(1),...N(0),...N(4),...it(n.length),...n,...N(6),...N(1),...N(2)],n=[...N(3),...it(n.length),...n],V(`esds`,0,0,n)},G=e=>B(`wave`,void 0,[Lt(e),Rt(e),B(`\0\0\0\0`)]),Lt=e=>B(`frma`,[z(Sn(e.track.source._codec,e.muxer.isQuickTime))]),Rt=e=>{let{littleEndian:t}=C(e.track.source._codec);return B(`enda`,[P(+t)])},zt=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){k(s.byteLength>=18);let e=y(S(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return B(`dOps`,[N(0),N(t),P(n),F(r),$e(i),N(a),...o])},Bt=e=>{let t=e.info.decoderConfig?.description;return k(t),V(`dfLa`,0,0,[...S(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=C(e.track.source._codec);return V(`pcmC`,0,0,[N(+t),N(8*n)])},Vt=e=>{let t=g(e.info.firstPacket.data);if(!t)throw 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 n=new Uint8Array(3),r=new oe(n);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),B(`dac3`,[...n])},Ht=e=>{let t=_(e.info.firstPacket.data);if(!t)throw 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 n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new oe(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return B(`dec3`,[...i])},Ut=(e,t)=>B(e,[[,,,,,,].fill(0),P(1)],[Tn[t.track.source._codec](t)]),Wt=e=>B(`vttC`,[...i.encode(e.info.config.description)]),Gt=e=>V(`stts`,0,0,[F(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),Kt=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return V(`stss`,0,0,[F(t.length),t.map(([e])=>F(e+1))])},qt=e=>V(`stsc`,0,0,[F(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),Jt=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=C(e.track.source._codec);return V(`stsz`,0,0,[F(t*e.info.numberOfChannels),F(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return V(`stsz`,0,0,[F(0),F(e.samples.length),e.samples.map(e=>F(e.size))])},Yt=e=>e.finalizedChunks.length>0&&E(e.finalizedChunks).offset>=2**32?V(`co64`,0,0,[F(e.finalizedChunks.length),e.finalizedChunks.map(e=>L(e.offset))]):V(`stco`,0,0,[F(e.finalizedChunks.length),e.finalizedChunks.map(e=>F(e.offset))]),Xt=e=>V(`ctts`,1,0,[F(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),I(e.sampleCompositionTimeOffset)])]),Zt=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;k(e.compositionTimeOffsetTable.length>0),k(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:V(`cslg`,0,0,[I(a),I(t),I(n),I(r),I(i)])},Qt=e=>B(`mvex`,void 0,e.map($t)),$t=e=>V(`trex`,0,0,[F(e.track.id),F(1),F(0),F(0),F(0)]),en=(e,t)=>B(`moof`,void 0,[tn(e),...t.map(rn)]),tn=e=>V(`mfhd`,0,0,[F(e)]),nn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},rn=e=>B(`traf`,void 0,[an(e),on(e),sn(e)]),an=e=>{k(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:nn(n)};return V(`tfhd`,0,t,[F(e.track.id),F(r.duration),F(r.size),F(r.flags)])},on=e=>(k(e.currentChunk),V(`tfdt`,1,0,[L(Z(e.currentChunk.startTimestamp,e.timescale))])),sn=e=>{k(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(nn),i=e.currentChunk.samples.map(t=>Z(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,V(`trun`,1,m,[F(e.currentChunk.samples.length),F(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?F(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?F(t[a]):[],d?F(n[a]):[],f?F(r[a]):[],p?I(i[a]):[]])])},cn=e=>B(`mfra`,void 0,[...e.map(ln),un()]),ln=(e,t)=>V(`tfra`,1,0,[F(e.track.id),F(63),F(e.finalizedChunks.length),e.finalizedChunks.map(n=>[L(Z(n.samples[0].timestamp,e.timescale)),L(n.moofOffset),F(t+1),F(1),F(1)])]),un=()=>V(`mfro`,0,0,[F(0)]),dn=()=>B(`vtte`),fn=(e,t,n,r,a)=>B(`vttc`,void 0,[a===null?null:B(`vsid`,[I(a)]),n===null?null:B(`iden`,[...i.encode(n)]),t===null?null:B(`ctim`,[...i.encode(Ze(t))]),r===null?null:B(`sttg`,[...i.encode(r)]),B(`payl`,[...i.encode(e)])]),pn=e=>B(`vtta`,[...i.encode(e)]),mn=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=vn(r);e&&t.push(e)}else if(n===`mdta`){let e=yn(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&hn(t,e.output._metadataTags);return t.length===0?null:B(`udta`,void 0,t)},hn=(e,t)=>{for(let{key:n,value:r}of ve(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:fe(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(q(n,r)):r instanceof Uint8Array&&e.push(B(n,Array.from(r))))}},q=(e,t)=>{let n=i.encode(t);return B(e,[P(n.length),P(En(`und`)),Array.from(n)])},gn={"image/jpeg":13,"image/png":14,"image/bmp":27},_n=(e,t)=>{let n=[];for(let{key:r,value:i}of ve(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:J(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:J(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:J(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:J(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:J(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:J(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:J(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:J(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:B(`data`,[F(gn[e.mimeType]??0),F(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:J(t)})}else n.push({key:`trkn`,value:B(`data`,[F(0),F(0),P(0),P(i),P(e.tracksTotal??0),P(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:B(`data`,[F(0),F(0),P(0),P(i),P(e.discsTotal??0),P(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:fe(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:J(i)}):i instanceof Uint8Array?n.push({key:r,value:B(`data`,[F(0),F(0),Array.from(i)])}):i instanceof b&&n.push({key:r,value:B(`data`,[F(gn[i.mimeType]??0),F(0),Array.from(i.data)])}))}return n},vn=e=>{let t=_n(e,!1);return t.length===0?null:V(`meta`,0,0,void 0,[bt(!1,`mdir`,``,`appl`),B(`ilst`,void 0,t.map(e=>B(e.key,void 0,[e.value])))])},yn=e=>{let t=_n(e,!0);return t.length===0?null:B(`meta`,void 0,[bt(!1,`mdta`,``),V(`keys`,0,0,[F(t.length)],t.map(e=>B(`mdta`,[...i.encode(e.key)]))),B(`ilst`,void 0,t.map((e,t)=>B(String.fromCharCode(...F(t+1)),void 0,[e.value])))])},J=e=>B(`data`,[F(1),F(0),...i.encode(e)]),bn=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},xn={avc:jt,hevc:Mt,vp8:Nt,vp9:Nt,av1:Pt},Sn=(e,t)=>{switch(e){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(e){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(e){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`}},Cn=(e,t)=>{switch(e){case`aac`:return It;case`mp3`:return It;case`opus`:return zt;case`vorbis`:return It;case`flac`:return Bt;case`ac3`:return Vt;case`eac3`:return Ht}if(t)switch(e){case`pcm-s24`:return G;case`pcm-s24be`:return G;case`pcm-s32`:return G;case`pcm-s32be`:return G;case`pcm-f32`:return G;case`pcm-f32be`:return G;case`pcm-f64`:return G;case`pcm-f64be`:return G}else switch(e){case`pcm-s16`:return K;case`pcm-s16be`:return K;case`pcm-s24`:return K;case`pcm-s24be`:return K;case`pcm-s32`:return K;case`pcm-s32be`:return K;case`pcm-f32`:return K;case`pcm-f32be`:return K;case`pcm-f64`:return K;case`pcm-f64be`:return K}return null},wn={webvtt:`wvtt`},Tn={webvtt:Wt},En=e=>{k(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Dn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){k(!this.started),this.target._start(),this.started=!0}write(e){k(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return k(this.started&&!this.finalized),this.target._flush()}async finalize(){k(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw 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}};r();var Y=class extends xe{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new jn(this,e)}},On=2**16,kn=2**32,An=class extends Y{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw 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(On,{maxByteLength:kn})}catch{this._buffer=new ArrayBuffer(On),this._supportsResize=!1}else this._buffer=new ArrayBuffer(On);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>kn)throw Error(`ArrayBuffer exceeded maximum size of ${kn} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},jn=class extends Y{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Mn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},X=57600,Nn=2082844800,Pn=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Fn=class extends Ye{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new An,this.auxWriter=new Dn(this.auxTarget,!1),this.auxBoxWriter=new Qe(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ve(),this.creationTime=Math.floor(Date.now()/1e3)+Nn,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof $n,this.isCmaf=t instanceof Qn,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Qn?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(e=>this.format._options.fastStart===void 0?e instanceof An:this.format._options.fastStart===`fragmented`),this.boxWriter=new Qe(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof An?`in-memory`:!1),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new Dn(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Qe(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(k(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(ct({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(k(this.writer),k(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=H(!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(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ne({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;m(r),k(r),k(r.decoderConfig);let a={...r.decoderConfig};k(a.codedWidth!==void 0),k(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){let e=Ce(n.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=l(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){let e=t(n.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=f(e),o=!0}let s=_e(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,u=a.displayAspectHeight,d=c===void 0||u===void 0?{num:1,den:1}:te({num:c*a.codedHeight,den:u*a.codedWidth}),p={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:d,decoderConfig:a,requiresAnnexBTransformation:o},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(p),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;re(n),k(n),k(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=He(Oe.tempFromBytes(t.data));if(!e)throw 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 n=p[e.samplingFrequencyIndex],r=Pe[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=ae({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Je.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;u(t),k(t),k(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Se(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw 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.`);i=a(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let o=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=He(Oe.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=C(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=C(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)k(r.timestamp<=t),k(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=dn();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;Xe.lastIndex=0;let r=Xe.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=pn(n.notes);this.auxBoxWriter.writeBox(e)}let c=fn(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=E(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){k(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(k(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=E(e.timeToSampleTable);if(k(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=E(e.compositionTimeOffsetTable);k(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,k(e.lastSample),k(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){k(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(k(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),k(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(k(!this.isFragmented),k(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||E(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)k(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(k(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){k(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;k(e),this.format._options.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=U(this);if(e.writeBox(t),this.format._options.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onMoov(t,n)}if(this.isCmaf){k(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Qe(this.writer);let e=this.boxWriter.measureBox(lt()),t=this.boxWriter.measureBox(ut(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}k(this.writer),k(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk),r=en(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=en(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}k(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=H(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(k(this.writer),k(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let e=U(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;k(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=H(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){k(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;k(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 t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e),k(e.startTimestampOffset!==null);for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(k(this.writer),k(this.boxWriter),this.fastStart===`in-memory`){this.mdat=H(!1);let e;for(let t=0;t<2;t++){let t=U(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)k(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=U(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)k(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(lt()),this.boxWriter.writeBox(ut(this,e))}else{let e=this.writer.getPos(),t=cn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{k(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);k(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=U(this);if(this.fastStart===`reserve`){k(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(dt(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},In=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){k(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),k(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor(i*this.targetSampleRate),s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;k(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame===null?this.maxWrittenFrame=n:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;k(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new D({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},Ln=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Rn=class extends Ln{constructor(e){if(super(),this._connectedTrack=null,!w.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${w.join(`, `)}.`);this._codec=e}},zn=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Bn=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.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 Ie,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let i=this.encodingConfig,a=i.sizeChangeBehavior??`deny`,o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(i.transform?.width!==void 0||i.transform?.height!==void 0||i.transform?.rotate!==void 0||i.transform?.crop!==void 0||i.transform?.force===!0||o&&a!==`passThrough`){let n=i.transform?.width,r=i.transform?.height,s=i.transform?.fit??`fill`;o&&a!==`passThrough`&&(k(this.outputWidth),k(this.outputHeight),k(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,fit:s,alpha:i.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else (this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let s=i.transform?.frameRate;if(s!==void 0){let i=e.timestamp+e.duration,a=Ne(e.timestamp,s);if(this.frameRateLastSample!==null)if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=i;return}else await this.padFrameRate(a,n);e===r&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/s),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=i}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,r;if(n.transform?.process){let t=n.transform.process(e);if(t instanceof Promise&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]),r=t.map(t=>t instanceof T?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new T(t):new T(t,{timestamp:e.timestamp,duration:e.duration}))}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),k(this.encoderInitialized),this.closed)break;let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{k(this.encoder);let t=e.toVideoFrame(),n=Te(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),r=n===-1?null:this.preciseTimings[n];if(r&&r.microsecondTimestamp===t.timestamp?(r.timestamp!==e.timestamp&&(r.timestampIsValid=!1),r.duration!==e.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(t,a),t.close();else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(t,a),t.close();else{let e=t.displayWidth,n=t.displayHeight;this.splitter||=new Hn(e,n);let{colorFrame:r,alphaFrame:i}=await this.splitter.update(t);this.alphaFrameQueue.push(i),this.encoder.encode(r,a),r.close()}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;k(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r=this.frameRateLastSample.clone();r.setTimestamp(this.frameRateLastTimestamp+e/n),r.setDuration(1/n),await this.processAndEncode(r,t),r.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=pe({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=de.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof s))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);zn(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=s.fromEncodedChunk(e,r),a=Te(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],c=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(c=v(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||c!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:c??void 0})),zn(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e}),this.emittedEncoderPackets++},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();k(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(k(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();k(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}k(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,t=Ne(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Vn=!1,Hn=class e{constructor(t,n){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let r=typeof OffscreenCanvas<`u`||typeof document<`u`&&typeof document.createElement==`function`;if(!e.forceCpu&&r&&!Vn)try{typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(t,n):(this.canvas=document.createElement(`canvas`),this.canvas.width=t,this.canvas.height=n);let e=this.canvas.getContext(`webgl2`,{alpha:!0});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}catch(e){this.gl=null,this.canvas=null,Vn=!0,console.warn(`Falling back to CPU for color/alpha splitting.`,e)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){k(this.gl),k(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return k(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
2
2
|
in vec2 a_position;
|
|
3
3
|
in vec2 a_texCoord;
|
|
4
4
|
out vec2 v_texCoord;
|
package/dist/index.html
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
}
|
|
9
9
|
</style>
|
|
10
10
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
11
|
-
<script type="module" crossorigin src="./assets/index-
|
|
11
|
+
<script type="module" crossorigin src="./assets/index-nUNsrps4.js"></script>
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|
|
14
14
|
<div id="root"></div>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno-node",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.3",
|
|
4
4
|
"description": "Polotno workflow from NodeJS",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"vite": "^8.0.16",
|
|
43
43
|
"vitest": "^4.1.9",
|
|
44
44
|
"web-audio-api": "^1.5.1",
|
|
45
|
-
"polotno": "
|
|
46
|
-
"
|
|
45
|
+
"@polotno/video-export": "0.1.0",
|
|
46
|
+
"polotno": "4.2.2"
|
|
47
47
|
},
|
|
48
48
|
"overrides": {
|
|
49
49
|
"@polotno/video-export": {
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"@sparticuz/chromium": "^149.0.0",
|
|
57
57
|
"puppeteer": "25.1.0",
|
|
58
58
|
"puppeteer-core": "25.1.0",
|
|
59
|
-
"@polotno/schema": "0.1.
|
|
59
|
+
"@polotno/schema": "0.1.6"
|
|
60
60
|
},
|
|
61
61
|
"bugs": {
|
|
62
62
|
"url": "https://github.com/polotno-project/polotno-node/issues"
|