polotno-node 3.1.3 → 3.2.0

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.
@@ -1 +1 @@
1
- import"./rolldown-runtime-QTnfLwEv.js";import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,N as v,O as y,Ot as b,P as ee,Q as te,R as ne,S as re,St as ie,T as ae,Tt as oe,U as x,V as S,W as se,X as ce,Y as le,Z as ue,_ as C,_t as de,a as fe,at as pe,b as me,bt as he,c as ge,ct as w,d as _e,dt as T,et as ve,f as ye,ft as be,g as xe,gt as E,h as Se,ht as Ce,i as we,it as Te,j as Ee,jt as De,k as Oe,l as ke,lt as Ae,m as je,mt as Me,n as Ne,nt as Pe,o as Fe,ot as Ie,p as Le,pt as Re,q as ze,r as Be,rt as Ve,s as He,st as Ue,tt as D,u as We,ut as Ge,v as Ke,vt as O,w as qe,wt as k,x as Je,xt as Ye,y as Xe,yt as Ze,z as Qe}from"./index-BtUscQGT.js";var $e=class{constructor(e){this.mutex=new Pe,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)}}},et=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,tt=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`)},A=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);w(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]]),nt=e=>(M.setInt16(0,e,!1),[j[0],j[1]]),rt=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]]),it=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]]),at=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]]),ot=e=>(M.setInt32(0,2**30*e,!1),[j[0],j[1],j[2],j[3]]),st=(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},ct=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]},lt=ct(0),ut=e=>[R(e[0]),R(e[1]),ot(e[2]),R(e[3]),R(e[4]),ot(e[5]),R(e[6]),R(e[7]),ot(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),rt(n),r??[]],i),dt=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`)]),ft=()=>B(`styp`,[z(`iso5`),F(0),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]),pt=(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}),mt=e=>({type:`free`,size:e}),U=e=>B(`moov`,void 0,[ht(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>gt(t,e.creationTime)),e.isFragmented?tn(e.trackDatas):null,_n(e)]),ht=(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=!E(e)||!E(n),a=i?L:F;return V(`mvhd`,+i,0,[a(e),a(e),F(X),a(n),R(1),at(1),Array(10).fill(0),ut(lt),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},gt=(e,t)=>{let n=Ln(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return B(`trak`,void 0,[_t(e,t),r?vt(e,e.startTimestampOffset):null,yt(e,t),n.name===void 0?null:B(`udta`,void 0,[B(`name`,[...k.encode(n.name)])])])},_t=(e,t)=>{let n=Z(W(e),X)+Z(e.startTimestampOffset??0,X),r=!E(t)||!E(n),i=r?L:F,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=ct(t??0)}else a=lt;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),at(+(e.type===`audio`)),P(0),ut(a),R(e.type===`video`?e.info.width:0),R(e.type===`video`?e.info.height:0)])},vt=(e,t)=>{let n=Z(t,X),r=Z(W(e),X),i=!E(n)||!E(r),a=i?L:F,o=i?it:I;return B(`edts`,void 0,[V(`elst`,+!!i,0,[F(2),a(n),o(-1),R(1),a(r),o(0),R(1)])])},yt=(e,t)=>B(`mdia`,void 0,[bt(e,t),Ct(!0,xt[e.type],St[e.type]),wt(e)]),bt=(e,t)=>{let n=Z(W(e),e.timescale),r=!E(t)||!E(n),i=r?L:F;return V(`mdhd`,+r,0,[i(t),i(t),F(e.timescale),i(n),P(kn(e.track.metadata.languageCode??`und`)),P(0)])},xt={video:`vide`,audio:`soun`,subtitle:`text`},St={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Ct=(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)]),wt=e=>B(`minf`,void 0,[Tt[e.type](),Et(),kt(e)]),Tt={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)},Et=()=>B(`dinf`,void 0,[Dt()]),Dt=()=>V(`dref`,0,0,[F(1)],[Ot()]),Ot=()=>V(`url `,0,1),kt=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B(`stbl`,void 0,[At(e),Jt(e),t?$t(e):null,t?en(e):null,Xt(e),Zt(e),Qt(e),Yt(e)])},At=e=>{let t;if(e.type===`video`)t=jt(Cn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Tn(e.track.source._codec,e.muxer.isQuickTime);w(n),t=Rt(n,e)}else e.type===`subtitle`&&(t=Kt(Dn[e.track.source._codec],e));return w(t),V(`stsd`,0,0,[F(1)],[t])},jt=(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),nt(65535)],[wn[t.track.source._codec]?.(t)??null,Mt(t),be(t.info.decoderConfig.colorSpace)?Nt(t):null]),Mt=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:B(`pasp`,[F(e.info.pixelAspectRatio.num),F(e.info.pixelAspectRatio.den)]),Nt=e=>B(`colr`,[z(e.muxer.isQuickTime?`nclc`:`nclx`),P(Ve[e.info.decoderConfig.colorSpace.primaries]),P(Ue[e.info.decoderConfig.colorSpace.transfer]),P(Ie[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:N(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),Pt=e=>e.info.decoderConfig&&B(`avcC`,[...l(e.info.decoderConfig.description)]),Ft=e=>e.info.decoderConfig&&B(`hvcC`,[...l(e.info.decoderConfig.description)]),It=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?Ve[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Ue[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Ie[t.colorSpace.matrix]:2;return V(`vpcC`,1,0,[N(r),N(i),N(c),N(l),N(u),N(d),P(0)])},Lt=e=>B(`av1C`,f(e.info.decoderConfig.codec)),Rt=(e,t)=>{let n=0,r,i=16,a=Qe.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=x(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)),nt(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,[En(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},zt=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),...rt(0),...F(0),...F(0)];if(e.info.decoderConfig.description){let t=l(e.info.decoderConfig.description);n=[...n,...N(5),...st(t.byteLength),...t]}return n=[...P(1),...N(0),...N(4),...st(n.length),...n,...N(6),...N(1),...N(2)],n=[...N(3),...st(n.length),...n],V(`esds`,0,0,n)},G=e=>B(`wave`,void 0,[Bt(e),Vt(e),B(`\0\0\0\0`)]),Bt=e=>B(`frma`,[z(Tn(e.track.source._codec,e.muxer.isQuickTime))]),Vt=e=>{let{littleEndian:t}=x(e.track.source._codec);return B(`enda`,[P(+t)])},Ht=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){w(s.byteLength>=18);let e=ee(l(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),nt(i),N(a),...o])},Ut=e=>{let t=e.info.decoderConfig?.description;return w(t),V(`dfLa`,0,0,[...l(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=x(e.track.source._codec);return V(`pcmC`,0,0,[N(+t),N(8*n)])},Wt=e=>{let t=_(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 ue(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])},Gt=e=>{let t=v(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 ue(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])},Kt=(e,t)=>B(e,[[,,,,,,].fill(0),P(1)],[On[t.track.source._codec](t)]),qt=e=>B(`vttC`,[...k.encode(e.info.config.description)]),Jt=e=>V(`stts`,0,0,[F(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),Yt=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))])},Xt=e=>V(`stsc`,0,0,[F(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),Zt=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=x(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))])},Qt=e=>e.finalizedChunks.length>0&&O(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))]),$t=e=>V(`ctts`,1,0,[F(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),I(e.sampleCompositionTimeOffset)])]),en=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;w(e.compositionTimeOffsetTable.length>0),w(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)])},tn=e=>B(`mvex`,void 0,e.map(nn)),nn=e=>V(`trex`,0,0,[F(e.track.id),F(1),F(0),F(0),F(0)]),rn=(e,t)=>B(`moof`,void 0,[an(e),...t.map(sn)]),an=e=>V(`mfhd`,0,0,[F(e)]),on=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},sn=e=>B(`traf`,void 0,[cn(e),ln(e),un(e)]),cn=e=>{w(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:on(n)};return V(`tfhd`,0,t,[F(e.track.id),F(r.duration),F(r.size),F(r.flags)])},ln=e=>(w(e.currentChunk),V(`tfdt`,1,0,[L(Z(e.currentChunk.startTimestamp,e.timescale))])),un=e=>{w(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(on),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]):[]])])},dn=e=>B(`mfra`,void 0,[...e.map(fn),pn()]),fn=(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)])]),pn=()=>V(`mfro`,0,0,[F(0)]),mn=()=>B(`vtte`),hn=(e,t,n,r,i)=>B(`vttc`,void 0,[i===null?null:B(`vsid`,[I(i)]),n===null?null:B(`iden`,[...k.encode(n)]),t===null?null:B(`ctim`,[...k.encode(tt(t))]),r===null?null:B(`sttg`,[...k.encode(r)]),B(`payl`,[...k.encode(e)])]),gn=e=>B(`vtta`,[...k.encode(e)]),_n=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=xn(r);e&&t.push(e)}else if(n===`mdta`){let e=Sn(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&vn(t,e.output._metadataTags);return t.length===0?null:B(`udta`,void 0,t)},vn=(e,t)=>{for(let{key:n,value:r}of de(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:Ae(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=k.encode(t);return B(e,[P(n.length),P(kn(`und`)),Array.from(n)])},yn={"image/jpeg":13,"image/png":14,"image/bmp":27},bn=(e,t)=>{let n=[];for(let{key:r,value:i}of de(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(yn[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:Ae(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 te&&n.push({key:r,value:B(`data`,[F(yn[i.mimeType]??0),F(0),Array.from(i.data)])}))}return n},xn=e=>{let t=bn(e,!1);return t.length===0?null:V(`meta`,0,0,void 0,[Ct(!1,`mdir`,``,`appl`),B(`ilst`,void 0,t.map(e=>B(e.key,void 0,[e.value])))])},Sn=e=>{let t=bn(e,!0);return t.length===0?null:B(`meta`,void 0,[Ct(!1,`mdta`,``),V(`keys`,0,0,[F(t.length)],t.map(e=>B(`mdta`,[...k.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),...k.encode(e)]),Cn=(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`;case`prores`:return t}},wn={avc:Pt,hevc:Ft,vp8:It,vp9:It,av1:Lt,prores:null},Tn=(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`}},En=(e,t)=>{switch(e){case`aac`:return zt;case`mp3`:return zt;case`opus`:return Ht;case`vorbis`:return zt;case`flac`:return Ut;case`ac3`:return Wt;case`eac3`:return Gt}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},Dn={webvtt:`wvtt`},On={webvtt:qt},kn=e=>{w(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},An=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(){w(!this.started),this.target._start(),this.started=!0}write(e){w(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 w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(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}};i();var Y=class extends pe{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 Pn(this,e)}},jn=2**16,Mn=2**32,Nn=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(jn,{maxByteLength:Mn})}catch{this._buffer=new ArrayBuffer(jn),this._supportsResize=!1}else this._buffer=new ArrayBuffer(jn);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>Mn)throw Error(`ArrayBuffer exceeded maximum size of ${Mn} 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)}},Pn=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)}},Fn=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,In=2082844800,Ln=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},Rn=class extends $e{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Nn,this.auxWriter=new An(this.auxTarget,!1),this.auxBoxWriter=new A(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ze(),this.creationTime=Math.floor(Date.now()/1e3)+In,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 nr,this.isCmaf=t instanceof tr,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof tr?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 Nn:this.format._options.fastStart===`fragmented`),this.boxWriter=new A(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Nn?`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 An(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new A(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(w(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(dt({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||(w(this.writer),w(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 ae({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;h(r),w(r),w(r.decoderConfig);let o={...r.decoderConfig};w(o.codedWidth!==void 0),w(o.codedHeight!==void 0);let s=!1;if(e.source._codec===`avc`&&!o.description){let e=Oe(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.`);o.description=u(e),s=!0}else if(e.source._codec===`hevc`&&!o.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.`);o.description=p(e),s=!0}let c=Re(1/(e.metadata.frameRate??57600),1e6).den,l=o.displayAspectWidth,d=o.displayAspectHeight,f=l===void 0||d===void 0?{num:1,den:1}:a({num:l*o.codedHeight,den:d*o.codedWidth}),m={muxer:this,track:e,type:`video`,info:{width:o.codedWidth,height:o.codedHeight,pixelAspectRatio:f,decoderConfig:o,requiresAnnexBTransformation:s},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(m),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),m}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;se(n),w(n),w(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=qe(Ne.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=m[e.samplingFrequencyIndex],r=ze[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=le({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&&Qe.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;d(t),w(t),w(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=[...Ee(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=o(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}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=qe(Ne.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=x(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}=x(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)w(r.timestamp<=t),w(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=mn();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;et.lastIndex=0;let r=et.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=gn(n.notes);this.auxBoxWriter.writeBox(e)}let c=hn(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=O(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){w(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(w(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=O(e.timeToSampleTable);if(w(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=O(e.compositionTimeOffsetTable);w(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,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(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(w(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}),w(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(w(!this.isFragmented),w(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||O(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)w(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w(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){w(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;w(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){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new A(this.writer);let e=this.boxWriter.measureBox(ft()),t=this.boxWriter.measureBox(pt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk),r=rn(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=rn(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)}w(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(w(this.writer),w(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let e=U(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;w(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(){w(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w(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),w(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(w(this.writer),w(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)w(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)w(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(ft()),this.boxWriter.writeBox(pt(this,e))}else{let e=this.writer.getPos(),t=dn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{w(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);w(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`){w(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(mt(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()}},zn=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(){w(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()),w(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-1/this.sourceSampleRate)*this.targetSampleRate)+1,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;w(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;w(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new xe({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()}},Bn=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})()}},Vn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!S.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${S.join(`, `)}.`);this._codec=e}},Hn=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Un=class{setError(e){this.errorSet||=(this.error=e,!0)}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 Te,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}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`&&(w(this.outputWidth),w(this.outputHeight),w(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=Me(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 C?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new C(t):new C(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),w(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)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{w(this.encoder);let t=e.toVideoFrame(),n=Ge(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{this.splitter||=new Gn;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n),this.encoder.encode(e,a),e.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;w(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=_e({...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=ge.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 c))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.`);Hn(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(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=c.fromEncodedChunk(e,r),a=Ge(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],s=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(s=y(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||s!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:s??void 0})),Hn(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.setError(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();w(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.setError(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(w(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();w(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.setError(e)}}),this.alphaEncoder.configure(t)}}w(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=Me(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(),await s(25)),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Wn=null,Gn=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Wn){let e=new Blob([`(${Kn.toString()})()`],{type:`application/javascript`});Wn=URL.createObjectURL(e)}this.worker=new Worker(Wn),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=Ze();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}},Kn=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let ee=m,te=a?512:o?2048:128;s===1?y.fill(te,ee):new Uint16Array(y.buffer,ee,2*_).fill(te);let ne=a?`I420P10`:o?`I420P12`:`I420`,re=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),ie={format:ne,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[y.buffer]};return{colorFrame:re,alphaFrame:new VideoFrame(y,ie)}}},qn=class extends Vn{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);Se(t),super(t.codec),this._encoder=new Un(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw TypeError(`timestamp must be a non-negative number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new C(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Jn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!g.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${g.join(`, `)}.`);this._codec=e}},Yn=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Te,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new zn({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Xe(e.format)!==n.transform.sampleFormat){let r=Ke(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process){let r=n.transform.process(e);if(r instanceof Promise&&(r=await r),r===null)return;Array.isArray(r)||(r=[r]);for(let e of r){if(!(e instanceof xe))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);await this.encodeSample(e,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new xe({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){w(this.outputSampleSize),w(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let l=e.allocationSize({planeIndex:0,format:`f32-planar`}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(u,{planeIndex:t,format:`f32-planar`});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,u[e*o+a])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,l=e*o,u=new c(new Uint8Array(r),`key`,a+l/i,t/i);this.encodingConfig.onEncodedPacket?.(u,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=We({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=He.find(e=>e.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof c))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.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(Qe.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(r)).supported)throw Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.numberOfChannels} channels, ${r.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2?!0:ce(l(t.decoderConfig.description)).objectType===0,e){let e=Number(O(r.codec.split(`.`)));t.decoderConfig.description=le({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=c.fromEncodedChunk(e);n=n.clone({timestamp:he(n.timestamp,r.sampleRate),duration:e.duration==null?void 0:he(n.duration,r.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.setError(e)})},error:t=>{t.stack=e,this.setError(t)}}),this.encoder.configure(r)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=x(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,T((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,T(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,Fe(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,fe(r))}:w(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,T((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,T(Math.round(n*32767),-32768,32767),r):w(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>ie(e,t,T((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>Ye(e,t,T(Math.round(n*8388607),-8388608,8388607),r):w(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,T((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,T(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):w(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):w(!1);break;default:Ae(n),w(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!==`closed`&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Xn=class extends Jn{constructor(e){je(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Yn(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=xe._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Zn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!r.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${r.join(`, `)}.`);this._codec=e}},Qn=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>S.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>g.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>r.includes(e))}_codecUnsupportedHint(e){return``}},$n=class extends Qn{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Rn(e,this)}},er=class extends $n{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ne,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...r]}_codecUnsupportedHint(e){return new nr().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},tr=class extends $n{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ne,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...r]}},nr=class extends $n{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...S,...g]}_codecUnsupportedHint(e){return new er().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},rr=[`video`,`audio`,`subtitle`],ir=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=oe(this.metadata.group),r=oe(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},ar=class extends ir{constructor(e,t,n,r){super(e,t,`video`,n,r)}},or=class extends ir{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},sr=class extends ir{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},cr=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},lr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ce(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&ve(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.group!==void 0&&!(e.group instanceof cr)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof cr))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},ur=class extends pe{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new cr,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Pe,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Qn))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof Fn))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Y&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Y)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Y&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof Fn);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w(this._target instanceof Fn);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof Y)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Y)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new An(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Vn))throw TypeError(`source must be a VideoSource.`);if(lr(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ar(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jn))throw TypeError(`source must be an AudioSource.`);lr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new or(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Zn))throw TypeError(`source must be a SubtitleSource.`);lr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new sr(this._tracks.length+1,this,e,n))}setMetadataTags(t){if(e(t),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=t}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this._tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let t of rr){let n=this._tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(D._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=await this._mutex.acquire();try{await this._muxer.start();let e=this._tracks.map(e=>e.source._start());await Promise.all(e)}finally{e()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return D._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&D._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(D._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}finally{e()}})()}},dr=De;function fr(){try{if(typeof DOMException<`u`)return new DOMException(`The operation was aborted.`,`AbortError`);throw Error(`DOMException is not available`)}catch{let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}}function Q(e){return!!e&&typeof e==`object`&&`name`in e&&e.name===`AbortError`}function $(e){if(e?.aborted)throw fr()}function pr(e){return Math.round(e/2)*2}function mr(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function hr(e){let t=0;return e.pages.map(e=>{let n=t,r=e.duration||5e3;return t=n+r,{id:e.id,startTime:n,duration:r}})}function gr(e){let t=e.width,n=e.height;for(let r of e.pages){let i=r.width===`auto`?e.width:r.width,a=r.height===`auto`?e.height:r.height;t=Math.max(t,i),n=Math.max(n,a)}return{width:pr(t),height:pr(n)}}function _r(e){let t=[],n=0;for(let r of e.pages){let e=r.duration||5e3;for(let i of r.children)if(i.type===`video`){let r=i.volume===void 0?1:i.volume;if(r===0)continue;let a=i.startTime||0,o=i.endTime||1,s=i.duration||5e3,c=i.speed||1;t.push({id:i.id,src:i.src,volume:r,startTime:a,endTime:o,duration:s,speed:c,pageStartTime:n,pageDuration:e,animations:i.animations})}n+=e}return t}function vr(e,t){let n=[];for(let r of e.pages)n.push({pageId:r.id,width:r.width,height:r.height}),r.set({width:t.width,height:t.height});return n}function yr(e,t){for(let{pageId:n,width:r,height:i}of t){let t=e.pages.find(e=>e.id===n);t&&t.set({width:r,height:i})}}function br(e,t){let r=n(),i=r.sceneCanvas._canvas;if(i.width=e.width*t,i.height=e.height*t,i.width<=0||i.height<=0)throw dr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${i.width}x${i.height}`,{reason:`invalid-dimensions`});return{canvas:i,canvases:r}}async function xr(e,t){let n=new ur({target:new Nn,format:new er}),r=await Le(n.format.getSupportedVideoCodecs(),{width:e.width,height:e.height});if(!r)throw dr(`VIDEO_FAILED`,`Your browser doesn't support video encoding.`,{reason:`no-encoder`});let i=new qn(e,{codec:r,bitrate:ke});return n.addVideoTrack(i,{frameRate:t}),{output:n,canvasSource:i}}async function Sr(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=_r(t).length>0;if(!r&&!i)return{audioBufferSource:null};let a=e.format.getSupportedAudioCodecs(),o=[`aac`,`mp3`,`flac`],s=[...o.filter(e=>a.includes(e)),...a.filter(e=>!o.includes(e))],c=await ye(s,{numberOfChannels:2,sampleRate:44100});if(!c)return console.warn(`[polotno-video-export] Browser doesn't support audio encoding, video will be generated without audio. Tried codecs: `+s.join(`, `)),{audioBufferSource:null};let l=new Xn({codec:c,bitrate:ke});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function Cr(e,t,n){let r=t[n];return r&&e>=r.startTime&&e<r.startTime+r.duration?n:t.findIndex(t=>e>=t.startTime&&e<t.startTime+t.duration)}async function wr(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function Tr(e,t,n,r,i,a,o,s,c){let l=1e3/a,u=Math.floor(i/1e3*a)||1,d=e.timingPreview;e.setTimingPreview(`playhead`);try{$(c),e.setElementsPixelRatio(o);let d=-1,f=0;for(let p=0;p<u;p++){$(c);let m=Date.now(),h=p/a,g=1/a,_=h*1e3;p===0&&(_=1),p===u-1&&(_=Math.min(i-1,(p+1)*l-1));let v=Cr(_,r,d);if(v!==d&&v>=0&&(e.activePage.set({_rendering:!1}),e.selectPage(e.pages[v].id),e.activePage.set({_rendering:!0}),await e.waitLoading(),$(c),d=v),await wr(e,_,v,o,n),$(c),await t.add(h,g),s){let e=Date.now();if(p===u-1||e-f>=300){let t=e-m;s((p+1)/u*.95,t),f=e}}}}finally{e.pages.forEach(e=>{e.set({_rendering:!1})}),e.setCurrentTime(0),e.setTimingPreview(d)}}async function Er(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw dr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function Dr(e,t){return e.decodeAudioData(t)}function Or(e){return e.startsWith(`data:`)}function kr(e){return e.startsWith(`file://`)}function Ar(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function jr(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}async function Mr(e,t){try{return Ar(e)?new Be({source:new re(e),formats:me}):Or(e)?new Be({source:new Je(jr(e)),formats:me}):(kr(e),new Be({source:new Je(await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer()),formats:me}))}catch(n){return Q(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function Nr(e,t){try{$(t);let n=await Mr(e,t);if(!n)return console.log(`[polotno-video-export] checkVideoAudio: createInputFromSource returned null for ${e.slice(0,80)}`),{hasAudio:!1,input:null};let r=await n.getAudioTracks();if(t?.aborted)throw n.dispose(),fr();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if(Q(n))throw n;if(t?.aborted)throw fr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function Pr(e,t){let n=e.audios||[],r=_r(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:Er(e.src,t).catch(n=>(Q(n)||t?.aborted||console.error(`Failed to download audio ${e.src}:`,n),null))})),videoAudios:r.map(e=>({video:e,inputPromise:Nr(e.src,t).catch(e=>{if(Q(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function Fr(e,t,n){let r=(e.delay||0)/1e3,i=e.volume===void 0?1:e.volume,a=e.startTime||0,o=e.endTime||1,s=e.speed||1,c=e.duration||n.totalDuration,l=a*c/1e3,u=c*(o-a)/1e3,d=r,f=l,p=Math.min(u,t.duration-l);if(d<0){let e=Math.abs(d)*s;f+=e,p-=e,d=0}if(p<=0||f>=t.duration)return;let m=n.offlineContext.createBufferSource();m.buffer=t;let h=n.offlineContext.createGain();h.gain.value=i,m.connect(h),h.connect(n.offlineContext.destination),m.playbackRate.value=s,m.start(d,f,p)}function Ir(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=b(e.animations,e.pageDuration),s=(o-a)/1e3,c=Math.max(0,(e.pageStartTime+a)/1e3),l=Math.max(0,r),u=Math.min(i,t.duration-l);if(u<=0||s<=0||l>=t.duration)return;let d=n.offlineContext.createBufferSource();d.buffer=t,d.playbackRate.value=e.speed,d.loop=!0,d.loopStart=l,d.loopEnd=l+u;let f=n.offlineContext.createGain();f.gain.value=e.volume,d.connect(f),f.connect(n.offlineContext.destination),d.start(c,l),d.stop(c+s)}async function Lr(e,t,n,r,i,a,o){$(o);let s=i||Pr(e,o);if(s.storeAudios.length+s.videoAudios.length===0)return;let c=44100,l=typeof r==`string`?r:typeof r?.codec==`string`?r.codec:void 0,u=l?.includes(`opus`)?960:1024,d=l===`aac`?3:l?.includes(`opus`)?2:0,f=Math.floor(n/1e3*c),p=Math.floor(f/u)*u,m=d*u,h=Math.max(u,p-m),g=new OfflineAudioContext(2,h,c),_={offlineContext:g,sampleRate:c,totalDuration:n};a?.(.95);let[v,y]=await Promise.all([Promise.all(s.storeAudios.map(async({audio:e,bufferPromise:t})=>{try{$(o);let n=await t;return $(o),n?{audio:e,audioBuffer:await Dr(g,n)}:null}catch(t){if(Q(t))throw t;return console.error(`Failed to process audio ${e.src}:`,t),null}})),Promise.all(s.videoAudios.map(async({video:e,inputPromise:t})=>{try{$(o);let{hasAudio:n,input:r}=await t;if($(o),!n||!r)return console.log(`[polotno-video-export] Video ${e.id} has no audio track or input failed. hasAudio=${n}, input=${!!r}`),null;let i=await r.getPrimaryAudioTrack();if(!i)return console.log(`[polotno-video-export] Video ${e.id} getPrimaryAudioTrack returned null`),r.dispose(),null;let a=new we(i),s=[];for await(let e of a.buffers())$(o),s.push(e.buffer);if(r.dispose(),$(o),s.length===0)return console.log(`[polotno-video-export] Video ${e.id} AudioBufferSink returned 0 buffers`),null;let c=s.reduce((e,t)=>e+t.length,0),l=g.createBuffer(s[0].numberOfChannels,c,s[0].sampleRate),u=0;for(let e of s){for(let t=0;t<e.numberOfChannels;t++)l.getChannelData(t).set(e.getChannelData(t),u);u+=e.length}return{video:e,audioBuffer:l}}catch(t){if(Q(t))throw t;return console.error(`Failed to extract video audio ${e.src}:`,t),null}}))]);a?.(.97),$(o);for(let e of v)e&&Fr(e.audio,e.audioBuffer,_);for(let e of y)e&&Ir(e.video,e.audioBuffer,_);$(o);let b=await g.startRendering();a?.(.99),$(o),await t.add(b)}async function Rr({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){let o=gr(e),s=vr(e,o),c=null,l=null,u=null,d=null,f=!1;if(a){$(a);let e=()=>{try{l?.close()}catch{}try{u?.close()}catch{}c?.cancel().catch(()=>{})};a.addEventListener(`abort`,e,{once:!0}),d=()=>a.removeEventListener(`abort`,e)}try{$(a);let s=mr(e);if(s===0)throw dr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let d=hr(e),{canvas:p,canvases:m}=br(o,n),h=await xr(p,t);c=h.output,l=h.canvasSource;let g=await Sr(c,e,i);u=g.audioBufferSource||null;let _=g.audioCodec;$(a),await c.start(),await Tr(e,l,m,d,s,t,n,r,a),l.close();let v=u?Pr(e,a):null;u&&v&&(await Lr(e,u,s,_,v,r,a),u.close()),$(a),await c.finalize();let y=c.target,b=new Blob([y.buffer],{type:c.format.mimeType});return f=!0,b}catch(e){throw Q(e)?e:a?.aborted?fr():e}finally{if(d?.(),!f&&c)try{await c.cancel()}catch{}yr(e,s)}}export{Rr as storeToVideo};
1
+ import"./rolldown-runtime-QTnfLwEv.js";import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,N as v,O as y,Ot as b,P as ee,Q as te,R as ne,S as re,St as ie,T as ae,Tt as oe,U as x,V as S,W as se,X as ce,Y as le,Z as ue,_ as C,_t as de,a as fe,at as pe,b as me,bt as he,c as ge,ct as w,d as _e,dt as T,et as ve,f as ye,ft as be,g as xe,gt as E,h as Se,ht as Ce,i as we,it as Te,j as Ee,jt as De,k as Oe,l as ke,lt as Ae,m as je,mt as Me,n as Ne,nt as Pe,o as Fe,ot as Ie,p as Le,pt as Re,q as ze,r as Be,rt as Ve,s as He,st as Ue,tt as D,u as We,ut as Ge,v as Ke,vt as O,w as qe,wt as k,x as Je,xt as Ye,y as Xe,yt as Ze,z as Qe}from"./index-j-YZMZrC.js";var $e=class{constructor(e){this.mutex=new Pe,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)}}},et=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,tt=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`)},A=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);w(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]]),nt=e=>(M.setInt16(0,e,!1),[j[0],j[1]]),rt=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]]),it=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]]),at=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]]),ot=e=>(M.setInt32(0,2**30*e,!1),[j[0],j[1],j[2],j[3]]),st=(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},ct=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]},lt=ct(0),ut=e=>[R(e[0]),R(e[1]),ot(e[2]),R(e[3]),R(e[4]),ot(e[5]),R(e[6]),R(e[7]),ot(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),rt(n),r??[]],i),dt=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`)]),ft=()=>B(`styp`,[z(`iso5`),F(0),z(`iso5`),z(`iso6`),z(`mp41`),z(`cmfc`),z(`dash`)]),pt=(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}),mt=e=>({type:`free`,size:e}),U=e=>B(`moov`,void 0,[ht(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>gt(t,e.creationTime)),e.isFragmented?tn(e.trackDatas):null,_n(e)]),ht=(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=!E(e)||!E(n),a=i?L:F;return V(`mvhd`,+i,0,[a(e),a(e),F(X),a(n),R(1),at(1),Array(10).fill(0),ut(lt),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},gt=(e,t)=>{let n=Ln(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return B(`trak`,void 0,[_t(e,t),r?vt(e,e.startTimestampOffset):null,yt(e,t),n.name===void 0?null:B(`udta`,void 0,[B(`name`,[...k.encode(n.name)])])])},_t=(e,t)=>{let n=Z(W(e),X)+Z(e.startTimestampOffset??0,X),r=!E(t)||!E(n),i=r?L:F,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=ct(t??0)}else a=lt;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),at(+(e.type===`audio`)),P(0),ut(a),R(e.type===`video`?e.info.width:0),R(e.type===`video`?e.info.height:0)])},vt=(e,t)=>{let n=Z(t,X),r=Z(W(e),X),i=!E(n)||!E(r),a=i?L:F,o=i?it:I;return B(`edts`,void 0,[V(`elst`,+!!i,0,[F(2),a(n),o(-1),R(1),a(r),o(0),R(1)])])},yt=(e,t)=>B(`mdia`,void 0,[bt(e,t),Ct(!0,xt[e.type],St[e.type]),wt(e)]),bt=(e,t)=>{let n=Z(W(e),e.timescale),r=!E(t)||!E(n),i=r?L:F;return V(`mdhd`,+r,0,[i(t),i(t),F(e.timescale),i(n),P(kn(e.track.metadata.languageCode??`und`)),P(0)])},xt={video:`vide`,audio:`soun`,subtitle:`text`},St={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Ct=(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)]),wt=e=>B(`minf`,void 0,[Tt[e.type](),Et(),kt(e)]),Tt={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)},Et=()=>B(`dinf`,void 0,[Dt()]),Dt=()=>V(`dref`,0,0,[F(1)],[Ot()]),Ot=()=>V(`url `,0,1),kt=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B(`stbl`,void 0,[At(e),Jt(e),t?$t(e):null,t?en(e):null,Xt(e),Zt(e),Qt(e),Yt(e)])},At=e=>{let t;if(e.type===`video`)t=jt(Cn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Tn(e.track.source._codec,e.muxer.isQuickTime);w(n),t=Rt(n,e)}else e.type===`subtitle`&&(t=Kt(Dn[e.track.source._codec],e));return w(t),V(`stsd`,0,0,[F(1)],[t])},jt=(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),nt(65535)],[wn[t.track.source._codec]?.(t)??null,Mt(t),be(t.info.decoderConfig.colorSpace)?Nt(t):null]),Mt=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:B(`pasp`,[F(e.info.pixelAspectRatio.num),F(e.info.pixelAspectRatio.den)]),Nt=e=>B(`colr`,[z(e.muxer.isQuickTime?`nclc`:`nclx`),P(Ve[e.info.decoderConfig.colorSpace.primaries]),P(Ue[e.info.decoderConfig.colorSpace.transfer]),P(Ie[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:N(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),Pt=e=>e.info.decoderConfig&&B(`avcC`,[...l(e.info.decoderConfig.description)]),Ft=e=>e.info.decoderConfig&&B(`hvcC`,[...l(e.info.decoderConfig.description)]),It=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?Ve[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Ue[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Ie[t.colorSpace.matrix]:2;return V(`vpcC`,1,0,[N(r),N(i),N(c),N(l),N(u),N(d),P(0)])},Lt=e=>B(`av1C`,f(e.info.decoderConfig.codec)),Rt=(e,t)=>{let n=0,r,i=16,a=Qe.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=x(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)),nt(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,[En(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},zt=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),...rt(0),...F(0),...F(0)];if(e.info.decoderConfig.description){let t=l(e.info.decoderConfig.description);n=[...n,...N(5),...st(t.byteLength),...t]}return n=[...P(1),...N(0),...N(4),...st(n.length),...n,...N(6),...N(1),...N(2)],n=[...N(3),...st(n.length),...n],V(`esds`,0,0,n)},G=e=>B(`wave`,void 0,[Bt(e),Vt(e),B(`\0\0\0\0`)]),Bt=e=>B(`frma`,[z(Tn(e.track.source._codec,e.muxer.isQuickTime))]),Vt=e=>{let{littleEndian:t}=x(e.track.source._codec);return B(`enda`,[P(+t)])},Ht=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){w(s.byteLength>=18);let e=ee(l(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),nt(i),N(a),...o])},Ut=e=>{let t=e.info.decoderConfig?.description;return w(t),V(`dfLa`,0,0,[...l(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=x(e.track.source._codec);return V(`pcmC`,0,0,[N(+t),N(8*n)])},Wt=e=>{let t=_(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 ue(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])},Gt=e=>{let t=v(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 ue(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])},Kt=(e,t)=>B(e,[[,,,,,,].fill(0),P(1)],[On[t.track.source._codec](t)]),qt=e=>B(`vttC`,[...k.encode(e.info.config.description)]),Jt=e=>V(`stts`,0,0,[F(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[F(e.sampleCount),F(e.sampleDelta)])]),Yt=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))])},Xt=e=>V(`stsc`,0,0,[F(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[F(e.firstChunk),F(e.samplesPerChunk),F(1)])]),Zt=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=x(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))])},Qt=e=>e.finalizedChunks.length>0&&O(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))]),$t=e=>V(`ctts`,1,0,[F(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[F(e.sampleCount),I(e.sampleCompositionTimeOffset)])]),en=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;w(e.compositionTimeOffsetTable.length>0),w(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)])},tn=e=>B(`mvex`,void 0,e.map(nn)),nn=e=>V(`trex`,0,0,[F(e.track.id),F(1),F(0),F(0),F(0)]),rn=(e,t)=>B(`moof`,void 0,[an(e),...t.map(sn)]),an=e=>V(`mfhd`,0,0,[F(e)]),on=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},sn=e=>B(`traf`,void 0,[cn(e),ln(e),un(e)]),cn=e=>{w(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:on(n)};return V(`tfhd`,0,t,[F(e.track.id),F(r.duration),F(r.size),F(r.flags)])},ln=e=>(w(e.currentChunk),V(`tfdt`,1,0,[L(Z(e.currentChunk.startTimestamp,e.timescale))])),un=e=>{w(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(on),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]):[]])])},dn=e=>B(`mfra`,void 0,[...e.map(fn),pn()]),fn=(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)])]),pn=()=>V(`mfro`,0,0,[F(0)]),mn=()=>B(`vtte`),hn=(e,t,n,r,i)=>B(`vttc`,void 0,[i===null?null:B(`vsid`,[I(i)]),n===null?null:B(`iden`,[...k.encode(n)]),t===null?null:B(`ctim`,[...k.encode(tt(t))]),r===null?null:B(`sttg`,[...k.encode(r)]),B(`payl`,[...k.encode(e)])]),gn=e=>B(`vtta`,[...k.encode(e)]),_n=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=xn(r);e&&t.push(e)}else if(n===`mdta`){let e=Sn(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&vn(t,e.output._metadataTags);return t.length===0?null:B(`udta`,void 0,t)},vn=(e,t)=>{for(let{key:n,value:r}of de(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:Ae(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=k.encode(t);return B(e,[P(n.length),P(kn(`und`)),Array.from(n)])},yn={"image/jpeg":13,"image/png":14,"image/bmp":27},bn=(e,t)=>{let n=[];for(let{key:r,value:i}of de(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(yn[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:Ae(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 te&&n.push({key:r,value:B(`data`,[F(yn[i.mimeType]??0),F(0),Array.from(i.data)])}))}return n},xn=e=>{let t=bn(e,!1);return t.length===0?null:V(`meta`,0,0,void 0,[Ct(!1,`mdir`,``,`appl`),B(`ilst`,void 0,t.map(e=>B(e.key,void 0,[e.value])))])},Sn=e=>{let t=bn(e,!0);return t.length===0?null:B(`meta`,void 0,[Ct(!1,`mdta`,``),V(`keys`,0,0,[F(t.length)],t.map(e=>B(`mdta`,[...k.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),...k.encode(e)]),Cn=(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`;case`prores`:return t}},wn={avc:Pt,hevc:Ft,vp8:It,vp9:It,av1:Lt,prores:null},Tn=(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`}},En=(e,t)=>{switch(e){case`aac`:return zt;case`mp3`:return zt;case`opus`:return Ht;case`vorbis`:return zt;case`flac`:return Ut;case`ac3`:return Wt;case`eac3`:return Gt}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},Dn={webvtt:`wvtt`},On={webvtt:qt},kn=e=>{w(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},An=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(){w(!this.started),this.target._start(),this.started=!0}write(e){w(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 w(this.started&&!this.finalized),this.target._flush()}async finalize(){w(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}};i();var Y=class extends pe{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 Pn(this,e)}},jn=2**16,Mn=2**32,Nn=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(jn,{maxByteLength:Mn})}catch{this._buffer=new ArrayBuffer(jn),this._supportsResize=!1}else this._buffer=new ArrayBuffer(jn);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>Mn)throw Error(`ArrayBuffer exceeded maximum size of ${Mn} 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)}},Pn=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)}},Fn=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,In=2082844800,Ln=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},Rn=class extends $e{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Nn,this.auxWriter=new An(this.auxTarget,!1),this.auxBoxWriter=new A(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ze(),this.creationTime=Math.floor(Date.now()/1e3)+In,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 nr,this.isCmaf=t instanceof tr,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof tr?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 Nn:this.format._options.fastStart===`fragmented`),this.boxWriter=new A(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Nn?`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 An(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new A(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(w(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(dt({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||(w(this.writer),w(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 ae({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;h(r),w(r),w(r.decoderConfig);let o={...r.decoderConfig};w(o.codedWidth!==void 0),w(o.codedHeight!==void 0);let s=!1;if(e.source._codec===`avc`&&!o.description){let e=Oe(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.`);o.description=u(e),s=!0}else if(e.source._codec===`hevc`&&!o.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.`);o.description=p(e),s=!0}let c=Re(1/(e.metadata.frameRate??57600),1e6).den,l=o.displayAspectWidth,d=o.displayAspectHeight,f=l===void 0||d===void 0?{num:1,den:1}:a({num:l*o.codedHeight,den:d*o.codedWidth}),m={muxer:this,track:e,type:`video`,info:{width:o.codedWidth,height:o.codedHeight,pixelAspectRatio:f,decoderConfig:o,requiresAnnexBTransformation:s},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(m),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),m}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;se(n),w(n),w(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=qe(Ne.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=m[e.samplingFrequencyIndex],r=ze[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=le({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&&Qe.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;d(t),w(t),w(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=[...Ee(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=o(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}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=qe(Ne.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=x(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}=x(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)w(r.timestamp<=t),w(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=mn();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;et.lastIndex=0;let r=et.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=gn(n.notes);this.auxBoxWriter.writeBox(e)}let c=hn(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=O(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){w(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(w(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=O(e.timeToSampleTable);if(w(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=O(e.compositionTimeOffsetTable);w(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,w(e.lastSample),w(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){w(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(w(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}),w(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(w(!this.isFragmented),w(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||O(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)w(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(w(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){w(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;w(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){w(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new A(this.writer);let e=this.boxWriter.measureBox(ft()),t=this.boxWriter.measureBox(pt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}w(this.writer),w(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk),r=rn(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=rn(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)}w(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(w(this.writer),w(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let e=U(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;w(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(){w(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;w(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),w(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(w(this.writer),w(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)w(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)w(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(ft()),this.boxWriter.writeBox(pt(this,e))}else{let e=this.writer.getPos(),t=dn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{w(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);w(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`){w(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(mt(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()}},zn=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(){w(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()),w(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-1/this.sourceSampleRate)*this.targetSampleRate)+1,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;w(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;w(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new xe({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()}},Bn=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})()}},Vn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!S.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${S.join(`, `)}.`);this._codec=e}},Hn=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Un=class{setError(e){this.errorSet||=(this.error=e,!0)}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 Te,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}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`&&(w(this.outputWidth),w(this.outputHeight),w(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=Me(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 C?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new C(t):new C(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),w(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)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{w(this.encoder);let t=e.toVideoFrame(),n=Ge(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{this.splitter||=new Gn;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n),this.encoder.encode(e,a),e.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;w(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=_e({...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=ge.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 c))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.`);Hn(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(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=c.fromEncodedChunk(e,r),a=Ge(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],s=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(s=y(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||s!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:s??void 0})),Hn(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.setError(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();w(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.setError(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(w(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();w(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.setError(e)}}),this.alphaEncoder.configure(t)}}w(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=Me(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(),await s(25)),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Wn=null,Gn=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Wn){let e=new Blob([`(${Kn.toString()})()`],{type:`application/javascript`});Wn=URL.createObjectURL(e)}this.worker=new Worker(Wn),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=Ze();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}},Kn=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let ee=m,te=a?512:o?2048:128;s===1?y.fill(te,ee):new Uint16Array(y.buffer,ee,2*_).fill(te);let ne=a?`I420P10`:o?`I420P12`:`I420`,re=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),ie={format:ne,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[y.buffer]};return{colorFrame:re,alphaFrame:new VideoFrame(y,ie)}}},qn=class extends Vn{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);Se(t),super(t.codec),this._encoder=new Un(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw TypeError(`timestamp must be a non-negative number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new C(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Jn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!g.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${g.join(`, `)}.`);this._codec=e}},Yn=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Te,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new zn({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Xe(e.format)!==n.transform.sampleFormat){let r=Ke(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process){let r=n.transform.process(e);if(r instanceof Promise&&(r=await r),r===null)return;Array.isArray(r)||(r=[r]);for(let e of r){if(!(e instanceof xe))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);await this.encodeSample(e,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),w(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new xe({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{w(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){w(this.outputSampleSize),w(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let l=e.allocationSize({planeIndex:0,format:`f32-planar`}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(u,{planeIndex:t,format:`f32-planar`});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,u[e*o+a])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,l=e*o,u=new c(new Uint8Array(r),`key`,a+l/i,t/i);this.encodingConfig.onEncodedPacket?.(u,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,u,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=We({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=He.find(e=>e.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof c))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.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(Qe.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(r)).supported)throw Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.numberOfChannels} channels, ${r.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2?!0:ce(l(t.decoderConfig.description)).objectType===0,e){let e=Number(O(r.codec.split(`.`)));t.decoderConfig.description=le({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=c.fromEncodedChunk(e);n=n.clone({timestamp:he(n.timestamp,r.sampleRate),duration:e.duration==null?void 0:he(n.duration,r.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.setError(e)})},error:t=>{t.stack=e,this.setError(t)}}),this.encoder.configure(r)}w(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=x(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,T((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,T(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,Fe(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,fe(r))}:w(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,T((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,T(Math.round(n*32767),-32768,32767),r):w(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>ie(e,t,T((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>Ye(e,t,T(Math.round(n*8388607),-8388608,8388607),r):w(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,T((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,T(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):w(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):w(!1);break;default:Ae(n),w(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.closed=!0,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!==`closed`&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Xn=class extends Jn{constructor(e){je(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Yn(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=xe._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Zn=class extends Bn{constructor(e){if(super(),this._connectedTrack=null,!r.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${r.join(`, `)}.`);this._codec=e}},Qn=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>S.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>g.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>r.includes(e))}_codecUnsupportedHint(e){return``}},$n=class extends Qn{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Rn(e,this)}},er=class extends $n{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ne,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...r]}_codecUnsupportedHint(e){return new nr().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},tr=class extends $n{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ne,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...r]}},nr=class extends $n{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...S,...g]}_codecUnsupportedHint(e){return new er().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},rr=[`video`,`audio`,`subtitle`],ir=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=oe(this.metadata.group),r=oe(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},ar=class extends ir{constructor(e,t,n,r){super(e,t,`video`,n,r)}},or=class extends ir{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},sr=class extends ir{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},cr=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},lr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Ce(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&ve(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.group!==void 0&&!(e.group instanceof cr)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof cr))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},ur=class extends pe{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new cr,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Pe,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Qn))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof Fn))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Y&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Y)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Y&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){w(this._target instanceof Fn);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(n):n(t)}async _getTarget(e){w(this._target instanceof Fn);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(w(this._initTarget!==null),this._initTarget instanceof Y)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Y)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new An(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Vn))throw TypeError(`source must be a VideoSource.`);if(lr(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ar(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Jn))throw TypeError(`source must be an AudioSource.`);lr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new or(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Zn))throw TypeError(`source must be a SubtitleSource.`);lr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new sr(this._tracks.length+1,this,e,n))}setMetadataTags(t){if(e(t),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=t}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this._tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let t of rr){let n=this._tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(D._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=await this._mutex.acquire();try{await this._muxer.start();let e=this._tracks.map(e=>e.source._start());await Promise.all(e)}finally{e()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return D._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&D._warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(D._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}finally{e()}})()}},dr=De;function fr(){try{if(typeof DOMException<`u`)return new DOMException(`The operation was aborted.`,`AbortError`);throw Error(`DOMException is not available`)}catch{let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}}function Q(e){return!!e&&typeof e==`object`&&`name`in e&&e.name===`AbortError`}function $(e){if(e?.aborted)throw fr()}function pr(e){return Math.round(e/2)*2}function mr(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function hr(e){let t=0;return e.pages.map(e=>{let n=t,r=e.duration||5e3;return t=n+r,{id:e.id,startTime:n,duration:r}})}function gr(e){let t=e.width,n=e.height;for(let r of e.pages){let i=r.width===`auto`?e.width:r.width,a=r.height===`auto`?e.height:r.height;t=Math.max(t,i),n=Math.max(n,a)}return{width:pr(t),height:pr(n)}}function _r(e){let t=[],n=0;for(let r of e.pages){let e=r.duration||5e3;for(let i of r.children)if(i.type===`video`){let r=i.volume===void 0?1:i.volume;if(r===0)continue;let a=i.startTime||0,o=i.endTime||1,s=i.duration||5e3,c=i.speed||1;t.push({id:i.id,src:i.src,volume:r,startTime:a,endTime:o,duration:s,speed:c,pageStartTime:n,pageDuration:e,animations:i.animations})}n+=e}return t}function vr(e,t){let n=[];for(let r of e.pages)n.push({pageId:r.id,width:r.width,height:r.height}),r.set({width:t.width,height:t.height});return n}function yr(e,t){for(let{pageId:n,width:r,height:i}of t){let t=e.pages.find(e=>e.id===n);t&&t.set({width:r,height:i})}}function br(e,t){let r=n(),i=r.sceneCanvas._canvas;if(i.width=e.width*t,i.height=e.height*t,i.width<=0||i.height<=0)throw dr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${i.width}x${i.height}`,{reason:`invalid-dimensions`});return{canvas:i,canvases:r}}async function xr(e,t){let n=new ur({target:new Nn,format:new er}),r=await Le(n.format.getSupportedVideoCodecs(),{width:e.width,height:e.height});if(!r)throw dr(`VIDEO_FAILED`,`Your browser doesn't support video encoding.`,{reason:`no-encoder`});let i=new qn(e,{codec:r,bitrate:ke});return n.addVideoTrack(i,{frameRate:t}),{output:n,canvasSource:i}}async function Sr(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=_r(t).length>0;if(!r&&!i)return{audioBufferSource:null};let a=e.format.getSupportedAudioCodecs(),o=[`aac`,`mp3`,`flac`],s=[...o.filter(e=>a.includes(e)),...a.filter(e=>!o.includes(e))],c=await ye(s,{numberOfChannels:2,sampleRate:44100});if(!c)return console.warn(`[polotno-video-export] Browser doesn't support audio encoding, video will be generated without audio. Tried codecs: `+s.join(`, `)),{audioBufferSource:null};let l=new Xn({codec:c,bitrate:ke});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function Cr(e,t,n){let r=t[n];return r&&e>=r.startTime&&e<r.startTime+r.duration?n:t.findIndex(t=>e>=t.startTime&&e<t.startTime+t.duration)}async function wr(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function Tr(e,t,n,r,i,a,o,s,c){let l=1e3/a,u=Math.floor(i/1e3*a)||1,d=e.timingPreview;e.setTimingPreview(`playhead`);try{$(c),e.setElementsPixelRatio(o);let d=-1,f=0;for(let p=0;p<u;p++){$(c);let m=Date.now(),h=p/a,g=1/a,_=h*1e3;p===0&&(_=1),p===u-1&&(_=Math.min(i-1,(p+1)*l-1));let v=Cr(_,r,d);if(v!==d&&v>=0&&(e.activePage.set({_rendering:!1}),e.selectPage(e.pages[v].id),e.activePage.set({_rendering:!0}),await e.waitLoading(),$(c),d=v),await wr(e,_,v,o,n),$(c),await t.add(h,g),s){let e=Date.now();if(p===u-1||e-f>=300){let t=e-m;s((p+1)/u*.95,t),f=e}}}}finally{e.pages.forEach(e=>{e.set({_rendering:!1})}),e.setCurrentTime(0),e.setTimingPreview(d)}}async function Er(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw dr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function Dr(e,t){return e.decodeAudioData(t)}function Or(e){return e.startsWith(`data:`)}function kr(e){return e.startsWith(`file://`)}function Ar(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function jr(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}async function Mr(e,t){try{return Ar(e)?new Be({source:new re(e),formats:me}):Or(e)?new Be({source:new Je(jr(e)),formats:me}):(kr(e),new Be({source:new Je(await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer()),formats:me}))}catch(n){return Q(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function Nr(e,t){try{$(t);let n=await Mr(e,t);if(!n)return console.log(`[polotno-video-export] checkVideoAudio: createInputFromSource returned null for ${e.slice(0,80)}`),{hasAudio:!1,input:null};let r=await n.getAudioTracks();if(t?.aborted)throw n.dispose(),fr();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if(Q(n))throw n;if(t?.aborted)throw fr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function Pr(e,t){let n=e.audios||[],r=_r(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:Er(e.src,t).catch(n=>(Q(n)||t?.aborted||console.error(`Failed to download audio ${e.src}:`,n),null))})),videoAudios:r.map(e=>({video:e,inputPromise:Nr(e.src,t).catch(e=>{if(Q(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function Fr(e,t,n){let r=(e.delay||0)/1e3,i=e.volume===void 0?1:e.volume,a=e.startTime||0,o=e.endTime||1,s=e.speed||1,c=e.duration||n.totalDuration,l=a*c/1e3,u=c*(o-a)/1e3,d=r,f=l,p=Math.min(u,t.duration-l);if(d<0){let e=Math.abs(d)*s;f+=e,p-=e,d=0}if(p<=0||f>=t.duration)return;let m=n.offlineContext.createBufferSource();m.buffer=t;let h=n.offlineContext.createGain();h.gain.value=i,m.connect(h),h.connect(n.offlineContext.destination),m.playbackRate.value=s,m.start(d,f,p)}function Ir(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=b(e.animations,e.pageDuration),s=(o-a)/1e3,c=Math.max(0,(e.pageStartTime+a)/1e3),l=Math.max(0,r),u=Math.min(i,t.duration-l);if(u<=0||s<=0||l>=t.duration)return;let d=n.offlineContext.createBufferSource();d.buffer=t,d.playbackRate.value=e.speed,d.loop=!0,d.loopStart=l,d.loopEnd=l+u;let f=n.offlineContext.createGain();f.gain.value=e.volume,d.connect(f),f.connect(n.offlineContext.destination),d.start(c,l),d.stop(c+s)}async function Lr(e,t,n,r,i,a,o){$(o);let s=i||Pr(e,o);if(s.storeAudios.length+s.videoAudios.length===0)return;let c=44100,l=typeof r==`string`?r:typeof r?.codec==`string`?r.codec:void 0,u=l?.includes(`opus`)?960:1024,d=l===`aac`?3:l?.includes(`opus`)?2:0,f=Math.floor(n/1e3*c),p=Math.floor(f/u)*u,m=d*u,h=Math.max(u,p-m),g=new OfflineAudioContext(2,h,c),_={offlineContext:g,sampleRate:c,totalDuration:n};a?.(.95);let[v,y]=await Promise.all([Promise.all(s.storeAudios.map(async({audio:e,bufferPromise:t})=>{try{$(o);let n=await t;return $(o),n?{audio:e,audioBuffer:await Dr(g,n)}:null}catch(t){if(Q(t))throw t;return console.error(`Failed to process audio ${e.src}:`,t),null}})),Promise.all(s.videoAudios.map(async({video:e,inputPromise:t})=>{try{$(o);let{hasAudio:n,input:r}=await t;if($(o),!n||!r)return console.log(`[polotno-video-export] Video ${e.id} has no audio track or input failed. hasAudio=${n}, input=${!!r}`),null;let i=await r.getPrimaryAudioTrack();if(!i)return console.log(`[polotno-video-export] Video ${e.id} getPrimaryAudioTrack returned null`),r.dispose(),null;let a=new we(i),s=[];for await(let e of a.buffers())$(o),s.push(e.buffer);if(r.dispose(),$(o),s.length===0)return console.log(`[polotno-video-export] Video ${e.id} AudioBufferSink returned 0 buffers`),null;let c=s.reduce((e,t)=>e+t.length,0),l=g.createBuffer(s[0].numberOfChannels,c,s[0].sampleRate),u=0;for(let e of s){for(let t=0;t<e.numberOfChannels;t++)l.getChannelData(t).set(e.getChannelData(t),u);u+=e.length}return{video:e,audioBuffer:l}}catch(t){if(Q(t))throw t;return console.error(`Failed to extract video audio ${e.src}:`,t),null}}))]);a?.(.97),$(o);for(let e of v)e&&Fr(e.audio,e.audioBuffer,_);for(let e of y)e&&Ir(e.video,e.audioBuffer,_);$(o);let b=await g.startRendering();a?.(.99),$(o),await t.add(b)}async function Rr({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){let o=gr(e),s=vr(e,o),c=null,l=null,u=null,d=null,f=!1;if(a){$(a);let e=()=>{try{l?.close()}catch{}try{u?.close()}catch{}c?.cancel().catch(()=>{})};a.addEventListener(`abort`,e,{once:!0}),d=()=>a.removeEventListener(`abort`,e)}try{$(a);let s=mr(e);if(s===0)throw dr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let d=hr(e),{canvas:p,canvases:m}=br(o,n),h=await xr(p,t);c=h.output,l=h.canvasSource;let g=await Sr(c,e,i);u=g.audioBufferSource||null;let _=g.audioCodec;$(a),await c.start(),await Tr(e,l,m,d,s,t,n,r,a),l.close();let v=u?Pr(e,a):null;u&&v&&(await Lr(e,u,s,_,v,r,a),u.close()),$(a),await c.finalize();let y=c.target,b=new Blob([y.buffer],{type:c.format.mimeType});return f=!0,b}catch(e){throw Q(e)?e:a?.aborted?fr():e}finally{if(d?.(),!f&&c)try{await c.cancel()}catch{}yr(e,s)}}export{Rr as storeToVideo};
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-BtUscQGT.js"></script>
11
+ <script type="module" crossorigin src="./assets/index-j-YZMZrC.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-QTnfLwEv.js">
13
13
  </head>
14
14
  <body>
package/lib/errors.d.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  * Structured errors, Node.js-style: a plain `Error` with a semver-stable
3
3
  * `code` property (branch on it, like `err.code === 'ENOENT'`) and optional
4
4
  * JSON-serializable `details`. Messages are for humans and may change in any
5
- * release — never match on them. See the error-codes table in the repo root
6
- * CLAUDE.md.
5
+ * release — never match on them. `PolotnoErrorDetailsMap` in
6
+ * `@polotno/core/src/errors.ts` is the canonical list this mirrors.
7
7
  *
8
8
  * polotno-node renders through the polotno browser client inside Chromium, so
9
9
  * besides its own codes this union lists every code that can cross the
@@ -16,8 +16,8 @@ export type PolotnoErrorCode = 'DESIGN_INVALID' | 'EXPORT_FAILED' | 'IMAGE_FAILE
16
16
  * `PolotnoErrorDetailsMap`, kept self-contained for the same
17
17
  * page.evaluate-boundary reason the code union above is (types are erased, but
18
18
  * keeping the whole error surface in one file documents exactly what a
19
- * polotno-node consumer can catch). Keep in sync with the canonical table in
20
- * the repo root CLAUDE.md.
19
+ * polotno-node consumer can catch). Keep in sync with `PolotnoErrorDetailsMap`
20
+ * in `@polotno/core/src/errors.ts`.
21
21
  */
22
22
  interface RenderContext {
23
23
  label?: string;
package/lib/errors.js CHANGED
@@ -2,8 +2,8 @@
2
2
  * Structured errors, Node.js-style: a plain `Error` with a semver-stable
3
3
  * `code` property (branch on it, like `err.code === 'ENOENT'`) and optional
4
4
  * JSON-serializable `details`. Messages are for humans and may change in any
5
- * release — never match on them. See the error-codes table in the repo root
6
- * CLAUDE.md.
5
+ * release — never match on them. `PolotnoErrorDetailsMap` in
6
+ * `@polotno/core/src/errors.ts` is the canonical list this mirrors.
7
7
  *
8
8
  * polotno-node renders through the polotno browser client inside Chromium, so
9
9
  * besides its own codes this union lists every code that can cross the
package/lib/font-cache.js CHANGED
@@ -1,7 +1,7 @@
1
- import fs from "fs";
2
- import os from "os";
3
- import path from "path";
4
- import crypto from "crypto";
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
5
  // Cache Google Fonts responses (CSS + font binaries) for the lifetime of the
6
6
  // process and serve them to every page. Every page starts with an empty HTTP
7
7
  // cache, so without this each render re-downloads the same fonts — and bursts
@@ -13,22 +13,22 @@ import crypto from "crypto";
13
13
  // 1. an in-memory Map for the lifetime of the process, and
14
14
  // 2. a disk cache shared between processes and across runs (e.g. parallel
15
15
  // test workers), so even a cold process doesn't re-download.
16
- const FONT_HOSTS = ["fonts.googleapis.com", "fonts.gstatic.com"];
16
+ const FONT_HOSTS = ['fonts.googleapis.com', 'fonts.gstatic.com'];
17
17
  const isFontUrl = (url) => FONT_HOSTS.some((host) => url.includes(host));
18
18
  const memoryCache = new Map(); // url -> { contentType, body }
19
- const FONT_CACHE_DIR = path.join(os.tmpdir(), "polotno-node-font-cache");
19
+ const FONT_CACHE_DIR = path.join(os.tmpdir(), 'polotno-node-font-cache');
20
20
  const FONT_CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
21
- const fontCacheDiskPath = (url) => path.join(FONT_CACHE_DIR, crypto.createHash("sha1").update(url).digest("hex") + ".json");
21
+ const fontCacheDiskPath = (url) => path.join(FONT_CACHE_DIR, crypto.createHash('sha1').update(url).digest('hex') + '.json');
22
22
  const readFontCacheFromDisk = (url) => {
23
23
  try {
24
24
  const file = fontCacheDiskPath(url);
25
25
  if (Date.now() - fs.statSync(file).mtimeMs > FONT_CACHE_TTL) {
26
26
  return null;
27
27
  }
28
- const data = JSON.parse(fs.readFileSync(file, "utf8"));
28
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
29
29
  return {
30
30
  contentType: data.contentType,
31
- body: Buffer.from(data.body, "base64"),
31
+ body: Buffer.from(data.body, 'base64'),
32
32
  };
33
33
  }
34
34
  catch (e) {
@@ -43,7 +43,7 @@ const writeFontCacheToDisk = (url, entry) => {
43
43
  fs.writeFileSync(tmpFile, JSON.stringify({
44
44
  url,
45
45
  contentType: entry.contentType,
46
- body: entry.body.toString("base64"),
46
+ body: entry.body.toString('base64'),
47
47
  }));
48
48
  fs.renameSync(tmpFile, file);
49
49
  }
@@ -78,7 +78,7 @@ const tryRespond = (request) => {
78
78
  // timeout. Google serves the same `*` for both font hosts. Our own launch
79
79
  // args include `--disable-web-security`, which hides this — it only bites
80
80
  // callers who bring their own `browser`.
81
- headers: { "access-control-allow-origin": "*" },
81
+ headers: { 'access-control-allow-origin': '*' },
82
82
  body: cached.body,
83
83
  })
84
84
  .catch(() => { });
@@ -94,7 +94,7 @@ const capture = async (response) => {
94
94
  }
95
95
  const body = await response.buffer();
96
96
  const entry = {
97
- contentType: response.headers()["content-type"] || "",
97
+ contentType: response.headers()['content-type'] || '',
98
98
  body,
99
99
  };
100
100
  memoryCache.set(url, entry);
package/lib/instance.d.ts CHANGED
@@ -9,12 +9,12 @@ declare global {
9
9
  __polotnoWriteChunk?: (chunk: string) => void;
10
10
  }
11
11
  }
12
- export declare const createPage: (browser: any, url: any, requestInterceptor: any, useFontCache?: boolean) => Promise<any>;
12
+ export declare const createPage: (browser: any, url: any, requestInterceptor: any, useFontCache?: boolean, navigationTimeout?: number) => Promise<any>;
13
13
  export declare const run: (page: any, func: any, args: any) => Promise<any>;
14
14
  export declare const jsonToDataURL: (page: any, json: any, attrs: any) => Promise<any>;
15
15
  export declare const jsonToPDFDataURL: (page: any, json: any, attrs: any) => Promise<any>;
16
16
  export declare const jsonToBlob: (page: any, json: any, attrs: any) => Promise<any>;
17
- export declare const createInstance: ({ key, url, useParallelPages, browser, requestInterceptor, useFontCache, }?: {
17
+ export declare const createInstance: ({ key, url, useParallelPages, browser, requestInterceptor, useFontCache, navigationTimeout, }?: {
18
18
  key?: string;
19
19
  url?: string;
20
20
  useParallelPages?: boolean;
@@ -22,6 +22,7 @@ export declare const createInstance: ({ key, url, useParallelPages, browser, req
22
22
  browserArgs?: string[];
23
23
  requestInterceptor?: (request: any) => void;
24
24
  useFontCache?: boolean;
25
+ navigationTimeout?: number;
25
26
  }) => Promise<{
26
27
  close: () => Promise<void>;
27
28
  firstPage: any;