polotno-node 3.0.4 → 3.1.1

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,65 +0,0 @@
1
- import{$ as e,A as t,B as n,C as r,Ct as i,D as a,Dt as o,E as s,Et as c,F as l,G as u,H as d,I as f,J as p,K as m,L as h,M as g,N as _,O as v,P as y,Q as b,R as x,S as ee,St as te,T as ne,Tt as S,U as C,V as w,W as re,X as ie,Y as ae,Z as oe,_ as T,_t as E,a as se,at as ce,b as le,bt as ue,c as de,ct as fe,d as pe,dt as me,et as he,f as ge,ft as _e,g as D,gt as ve,h as ye,ht as O,i as be,it as xe,j as Se,k as Ce,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,s as Le,st as k,tt as Re,u as ze,ut as A,v as Be,vt as Ve,w as He,wt as Ue,x as We,xt as Ge,y as Ke,yt as qe,z as Je}from"./index-Del05vQF.js";var Ye=class{constructor(e){this.mutex=new Re,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Xe=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ze=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},j=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);k(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},M=new Uint8Array(8),N=new DataView(M.buffer),P=e=>[(e%256+256)%256],F=e=>(N.setUint16(0,e,!1),[M[0],M[1]]),Qe=e=>(N.setInt16(0,e,!1),[M[0],M[1]]),$e=e=>(N.setUint32(0,e,!1),[M[1],M[2],M[3]]),I=e=>(N.setUint32(0,e,!1),[M[0],M[1],M[2],M[3]]),L=e=>(N.setInt32(0,e,!1),[M[0],M[1],M[2],M[3]]),R=e=>(N.setUint32(0,Math.floor(e/2**32),!1),N.setUint32(4,e,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),et=e=>(N.setInt32(0,Math.floor(e/2**32),!1),N.setUint32(4,e,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),tt=e=>(N.setInt16(0,2**8*e,!1),[M[0],M[1]]),z=e=>(N.setInt32(0,2**16*e,!1),[M[0],M[1],M[2],M[3]]),nt=e=>(N.setInt32(0,2**30*e,!1),[M[0],M[1],M[2],M[3]]),rt=(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()},B=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},it=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]},at=it(0),ot=e=>[z(e[0]),z(e[1]),nt(e[2]),z(e[3]),z(e[4]),nt(e[5]),z(e[6]),z(e[7]),nt(e[8])],V=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),H=(e,t,n,r,i)=>V(e,[P(t),$e(n),r??[]],i),st=e=>e.isQuickTime?V(`ftyp`,[B(`qt `),I(512),B(`qt `)]):e.fragmented?e.cmaf?V(`ftyp`,[B(`iso5`),I(512),B(`iso5`),B(`iso6`),B(`mp41`),B(`cmfc`),B(`dash`)]):V(`ftyp`,[B(`iso5`),I(512),B(`iso5`),B(`iso6`),B(`mp41`)]):V(`ftyp`,[B(`isom`),I(512),B(`isom`),e.holdsAvc?B(`avc1`):[],B(`mp41`)]),ct=()=>V(`styp`,[B(`iso5`),I(0),B(`iso5`),B(`iso6`),B(`mp41`),B(`cmfc`),B(`dash`)]),lt=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),H(`sidx`,1,0,[I(1),I(X),R(Z(e.minWrittenTimestamp,X)),R(0),F(0),F(1),I(t&2147483647),I(Z(n,X)),I(0)])},U=e=>({type:`mdat`,largeSize:e}),ut=e=>({type:`free`,size:e}),W=e=>V(`moov`,void 0,[dt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>pt(t,e.creationTime)),e.isFragmented?Qt(e.trackDatas):null,mn(e)]),dt=(e,t)=>{let n=Math.max(0,...t.map(e=>Z(ft(e),X)+Z(e.startTimestampOffset??0,X))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!O(e)||!O(n),a=i?R:I;return H(`mvhd`,+i,0,[a(e),a(e),I(X),a(n),z(1),tt(1),Array(10).fill(0),ot(at),Array(24).fill(0),I(r)])},ft=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},pt=(e,t)=>{let n=Pn(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return V(`trak`,void 0,[mt(e,t),r?ht(e,e.startTimestampOffset):null,gt(e,t),n.name===void 0?null:V(`udta`,void 0,[V(`name`,[...i.encode(n.name)])])])},mt=(e,t)=>{let n=Z(ft(e),X)+Z(e.startTimestampOffset??0,X),r=!O(t)||!O(n),i=r?R:I,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=it(t??0)}else a=at;let o=2;return e.track.metadata.disposition?.default!==!1&&(o|=1),H(`tkhd`,+r,o,[i(t),i(t),I(e.track.id),I(0),i(n),Array(8).fill(0),F(0),F(e.track.id),tt(+(e.type===`audio`)),F(0),ot(a),z(e.type===`video`?e.info.width:0),z(e.type===`video`?e.info.height:0)])},ht=(e,t)=>{let n=Z(t,X),r=Z(ft(e),X),i=!O(n)||!O(r),a=i?R:I,o=i?et:L;return V(`edts`,void 0,[H(`elst`,+!!i,0,[I(2),a(n),o(-1),z(1),a(r),o(0),z(1)])])},gt=(e,t)=>V(`mdia`,void 0,[_t(e,t),bt(!0,vt[e.type],yt[e.type]),xt(e)]),_t=(e,t)=>{let n=Z(ft(e),e.timescale),r=!O(t)||!O(n),i=r?R:I;return H(`mdhd`,+r,0,[i(t),i(t),I(e.timescale),i(n),F(En(e.track.metadata.languageCode??`und`)),F(0)])},vt={video:`vide`,audio:`soun`,subtitle:`text`},yt={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},bt=(e,t,n,r=`\0\0\0\0`)=>H(`hdlr`,0,0,[e?B(`mhlr`):I(0),B(t),B(r),I(0),I(0),B(n,!0)]),xt=e=>V(`minf`,void 0,[St[e.type](),Ct(),Et(e)]),St={video:()=>H(`vmhd`,0,1,[F(0),F(0),F(0),F(0)]),audio:()=>H(`smhd`,0,0,[F(0),F(0)]),subtitle:()=>H(`nmhd`,0,0)},Ct=()=>V(`dinf`,void 0,[wt()]),wt=()=>H(`dref`,0,0,[I(1)],[Tt()]),Tt=()=>H(`url `,0,1),Et=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return V(`stbl`,void 0,[Dt(e),Gt(e),t?Xt(e):null,t?Zt(e):null,qt(e),Jt(e),Yt(e),Kt(e)])},Dt=e=>{let t;if(e.type===`video`)t=Ot(bn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Sn(e.track.source._codec,e.muxer.isQuickTime);k(n),t=Ft(n,e)}else e.type===`subtitle`&&(t=Ut(wn[e.track.source._codec],e));return k(t),H(`stsd`,0,0,[I(1)],[t])},Ot=(e,t)=>V(e,[[,,,,,,].fill(0),F(1),F(0),F(0),Array(12).fill(0),F(t.info.width),F(t.info.height),I(4718592),I(4718592),I(0),F(1),Array(32).fill(0),F(24),Qe(65535)],[xn[t.track.source._codec](t),kt(t),me(t.info.decoderConfig.colorSpace)?At(t):null]),kt=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:V(`pasp`,[I(e.info.pixelAspectRatio.num),I(e.info.pixelAspectRatio.den)]),At=e=>V(`colr`,[B(e.muxer.isQuickTime?`nclc`:`nclx`),F(ke[e.info.decoderConfig.colorSpace.primaries]),F(je[e.info.decoderConfig.colorSpace.transfer]),F(ce[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:P(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),jt=e=>e.info.decoderConfig&&V(`avcC`,[...S(e.info.decoderConfig.description)]),Mt=e=>e.info.decoderConfig&&V(`hvcC`,[...S(e.info.decoderConfig.description)]),Nt=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?ke[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?je[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?ce[t.colorSpace.matrix]:2;return H(`vpcC`,1,0,[P(r),P(i),P(c),P(l),P(u),P(d),F(0)])},Pt=e=>V(`av1C`,d(e.info.decoderConfig.codec)),Ft=(e,t)=>{let n=0,r,i=16,a=Je.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=C(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),F(1),F(n),F(0),I(0),F(t.info.numberOfChannels),F(i),F(0),F(0),F(t.info.sampleRate<2**16?t.info.sampleRate:0),F(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),F(1),F(n),F(0),I(0),F(t.info.numberOfChannels),F(Math.min(i,16)),Qe(e),F(0),F(t.info.sampleRate<2**16?t.info.sampleRate:0),F(0),a?[I(1),I(i/8),I(t.info.numberOfChannels*i/8)]:[I(0),I(0),I(0)],I(2)]}return V(e,r,[Cn(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},It=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...P(t),...P(21),...$e(0),...I(0),...I(0)];if(e.info.decoderConfig.description){let t=S(e.info.decoderConfig.description);n=[...n,...P(5),...rt(t.byteLength),...t]}return n=[...F(1),...P(0),...P(4),...rt(n.length),...n,...P(6),...P(1),...P(2)],n=[...P(3),...rt(n.length),...n],H(`esds`,0,0,n)},G=e=>V(`wave`,void 0,[Lt(e),Rt(e),V(`\0\0\0\0`)]),Lt=e=>V(`frma`,[B(Sn(e.track.source._codec,e.muxer.isQuickTime))]),Rt=e=>{let{littleEndian:t}=C(e.track.source._codec);return V(`enda`,[F(+t)])},zt=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){k(s.byteLength>=18);let e=y(S(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return V(`dOps`,[P(0),P(t),F(n),I(r),Qe(i),P(a),...o])},Bt=e=>{let t=e.info.decoderConfig?.description;return k(t),H(`dfLa`,0,0,[...S(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=C(e.track.source._codec);return H(`pcmC`,0,0,[P(+t),P(8*n)])},Vt=e=>{let t=g(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new oe(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),V(`dac3`,[...n])},Ht=e=>{let t=_(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new oe(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return V(`dec3`,[...i])},Ut=(e,t)=>V(e,[[,,,,,,].fill(0),F(1)],[Tn[t.track.source._codec](t)]),Wt=e=>V(`vttC`,[...i.encode(e.info.config.description)]),Gt=e=>H(`stts`,0,0,[I(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[I(e.sampleCount),I(e.sampleDelta)])]),Kt=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return H(`stss`,0,0,[I(t.length),t.map(([e])=>I(e+1))])},qt=e=>H(`stsc`,0,0,[I(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[I(e.firstChunk),I(e.samplesPerChunk),I(1)])]),Jt=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=C(e.track.source._codec);return H(`stsz`,0,0,[I(t*e.info.numberOfChannels),I(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return H(`stsz`,0,0,[I(0),I(e.samples.length),e.samples.map(e=>I(e.size))])},Yt=e=>e.finalizedChunks.length>0&&E(e.finalizedChunks).offset>=2**32?H(`co64`,0,0,[I(e.finalizedChunks.length),e.finalizedChunks.map(e=>R(e.offset))]):H(`stco`,0,0,[I(e.finalizedChunks.length),e.finalizedChunks.map(e=>I(e.offset))]),Xt=e=>H(`ctts`,1,0,[I(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[I(e.sampleCount),L(e.sampleCompositionTimeOffset)])]),Zt=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;k(e.compositionTimeOffsetTable.length>0),k(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:H(`cslg`,0,0,[L(a),L(t),L(n),L(r),L(i)])},Qt=e=>V(`mvex`,void 0,e.map($t)),$t=e=>H(`trex`,0,0,[I(e.track.id),I(1),I(0),I(0),I(0)]),en=(e,t)=>V(`moof`,void 0,[tn(e),...t.map(rn)]),tn=e=>H(`mfhd`,0,0,[I(e)]),nn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},rn=e=>V(`traf`,void 0,[an(e),on(e),sn(e)]),an=e=>{k(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:nn(n)};return H(`tfhd`,0,t,[I(e.track.id),I(r.duration),I(r.size),I(r.flags)])},on=e=>(k(e.currentChunk),H(`tfdt`,1,0,[R(Z(e.currentChunk.startTimestamp,e.timescale))])),sn=e=>{k(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(nn),i=e.currentChunk.samples.map(t=>Z(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,H(`trun`,1,m,[I(e.currentChunk.samples.length),I(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?I(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?I(t[a]):[],d?I(n[a]):[],f?I(r[a]):[],p?L(i[a]):[]])])},cn=e=>V(`mfra`,void 0,[...e.map(ln),un()]),ln=(e,t)=>H(`tfra`,1,0,[I(e.track.id),I(63),I(e.finalizedChunks.length),e.finalizedChunks.map(n=>[R(Z(n.samples[0].timestamp,e.timescale)),R(n.moofOffset),I(t+1),I(1),I(1)])]),un=()=>H(`mfro`,0,0,[I(0)]),dn=()=>V(`vtte`),fn=(e,t,n,r,a)=>V(`vttc`,void 0,[a===null?null:V(`vsid`,[L(a)]),n===null?null:V(`iden`,[...i.encode(n)]),t===null?null:V(`ctim`,[...i.encode(Ze(t))]),r===null?null:V(`sttg`,[...i.encode(r)]),V(`payl`,[...i.encode(e)])]),pn=e=>V(`vtta`,[...i.encode(e)]),mn=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=vn(r);e&&t.push(e)}else if(n===`mdta`){let e=yn(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&hn(t,e.output._metadataTags);return t.length===0?null:V(`udta`,void 0,t)},hn=(e,t)=>{for(let{key:n,value:r}of ve(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:fe(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(q(n,r)):r instanceof Uint8Array&&e.push(V(n,Array.from(r))))}},q=(e,t)=>{let n=i.encode(t);return V(e,[F(n.length),F(En(`und`)),Array.from(n)])},gn={"image/jpeg":13,"image/png":14,"image/bmp":27},_n=(e,t)=>{let n=[];for(let{key:r,value:i}of ve(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:J(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:J(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:J(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:J(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:J(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:J(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:J(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:J(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:V(`data`,[I(gn[e.mimeType]??0),I(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:V(`data`,[I(0),I(0),F(0),F(i),F(e.tracksTotal??0),F(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:V(`data`,[I(0),I(0),F(0),F(i),F(e.discsTotal??0),F(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:fe(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:J(i)}):i instanceof Uint8Array?n.push({key:r,value:V(`data`,[I(0),I(0),Array.from(i)])}):i instanceof b&&n.push({key:r,value:V(`data`,[I(gn[i.mimeType]??0),I(0),Array.from(i.data)])}))}return n},vn=e=>{let t=_n(e,!1);return t.length===0?null:H(`meta`,0,0,void 0,[bt(!1,`mdir`,``,`appl`),V(`ilst`,void 0,t.map(e=>V(e.key,void 0,[e.value])))])},yn=e=>{let t=_n(e,!0);return t.length===0?null:V(`meta`,void 0,[bt(!1,`mdta`,``),H(`keys`,0,0,[I(t.length)],t.map(e=>V(`mdta`,[...i.encode(e.key)]))),V(`ilst`,void 0,t.map((e,t)=>V(String.fromCharCode(...I(t+1)),void 0,[e.value])))])},J=e=>V(`data`,[I(1),I(0),...i.encode(e)]),bn=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},xn={avc:jt,hevc:Mt,vp8:Nt,vp9:Nt,av1:Pt},Sn=(e,t)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`}if(t)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Cn=(e,t)=>{switch(e){case`aac`:return It;case`mp3`:return It;case`opus`:return zt;case`vorbis`:return It;case`flac`:return Bt;case`ac3`:return Vt;case`eac3`:return Ht}if(t)switch(e){case`pcm-s24`:return G;case`pcm-s24be`:return G;case`pcm-s32`:return G;case`pcm-s32be`:return G;case`pcm-f32`:return G;case`pcm-f32be`:return G;case`pcm-f64`:return G;case`pcm-f64be`:return G}else switch(e){case`pcm-s16`:return K;case`pcm-s16be`:return K;case`pcm-s24`:return K;case`pcm-s24be`:return K;case`pcm-s32`:return K;case`pcm-s32be`:return K;case`pcm-f32`:return K;case`pcm-f32be`:return K;case`pcm-f64`:return K;case`pcm-f64be`:return K}return null},wn={webvtt:`wvtt`},Tn={webvtt:Wt},En=e=>{k(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Dn=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){k(!this.started),this.target._start(),this.started=!0}write(e){k(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return k(this.started&&!this.finalized),this.target._flush()}async finalize(){k(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};r();var Y=class extends xe{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new jn(this,e)}},On=2**16,kn=2**32,An=class extends Y{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(On,{maxByteLength:kn})}catch{this._buffer=new ArrayBuffer(On),this._supportsResize=!1}else this._buffer=new ArrayBuffer(On);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>kn)throw Error(`ArrayBuffer exceeded maximum size of ${kn} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},jn=class extends Y{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},Mn=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},X=57600,Nn=2082844800,Pn=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Fn=class extends Ye{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new An,this.auxWriter=new Dn(this.auxTarget,!1),this.auxBoxWriter=new j(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Ve(),this.creationTime=Math.floor(Date.now()/1e3)+Nn,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof $n,this.isCmaf=t instanceof Qn,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Qn?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.format._options.fastStart===void 0?e instanceof An:this.format._options.fastStart===`fragmented`),this.boxWriter=new j(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof An?`in-memory`:!1),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new Dn(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new j(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(k(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(st({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(k(this.writer),k(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=U(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ne({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,n,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;m(r),k(r),k(r.decoderConfig);let a={...r.decoderConfig};k(a.codedWidth!==void 0),k(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){let e=Ce(n.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=l(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){let e=t(n.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=f(e),o=!0}let s=_e(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,u=a.displayAspectHeight,d=c===void 0||u===void 0?{num:1,den:1}:te({num:c*a.codedHeight,den:u*a.codedWidth}),p={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:d,decoderConfig:a,requiresAnnexBTransformation:o},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(p),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;re(n),k(n),k(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=He(Oe.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=p[e.samplingFrequencyIndex],r=Pe[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=ae({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Je.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;u(t),k(t),k(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Se(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=a(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let o=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=He(Oe.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=C(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=C(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)k(r.timestamp<=t),k(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=dn();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;Xe.lastIndex=0;let r=Xe.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=pn(n.notes);this.auxBoxWriter.writeBox(e)}let c=fn(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=E(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){k(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(k(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=E(e.timeToSampleTable);if(k(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=E(e.compositionTimeOffsetTable);k(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,k(e.lastSample),k(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){k(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(k(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),k(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(k(!this.isFragmented),k(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||E(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)k(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(k(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){k(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;k(e),this.format._options.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W(this);if(e.writeBox(t),this.format._options.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onMoov(t,n)}if(this.isCmaf){k(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new j(this.writer);let e=this.boxWriter.measureBox(ct()),t=this.boxWriter.measureBox(lt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}k(this.writer),k(this.boxWriter);let n=this.trackDatas.filter(e=>e.currentChunk),r=en(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=en(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}k(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=U(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(k(this.writer),k(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();let e=W(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;k(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=U(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){k(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;k(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e),k(e.startTimestampOffset!==null);for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(k(this.writer),k(this.boxWriter),this.fastStart===`in-memory`){this.mdat=U(!1);let e;for(let t=0;t<2;t++){let t=W(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)k(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=W(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)k(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(ct()),this.boxWriter.writeBox(lt(this,e))}else{let e=this.writer.getPos(),t=cn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{k(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);k(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=W(this);if(this.fastStart===`reserve`){k(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(ut(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},In=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){k(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),k(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor(i*this.targetSampleRate),s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;k(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame===null?this.maxWrittenFrame=n:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;k(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new D({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},Ln=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Rn=class extends Ln{constructor(e){if(super(),this._connectedTrack=null,!w.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${w.join(`, `)}.`);this._codec=e}},zn=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Bn=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Ie,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.closed=!1,this.lastMuxerPromise=Promise.resolve()}async add(e,t,n){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let i=this.encodingConfig,a=i.sizeChangeBehavior??`deny`,o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(i.transform?.width!==void 0||i.transform?.height!==void 0||i.transform?.rotate!==void 0||i.transform?.crop!==void 0||i.transform?.force===!0||o&&a!==`passThrough`){let n=i.transform?.width,r=i.transform?.height,s=i.transform?.fit??`fill`;o&&a!==`passThrough`&&(k(this.outputWidth),k(this.outputHeight),k(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,fit:s,alpha:i.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else (this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let s=i.transform?.frameRate;if(s!==void 0){let i=e.timestamp+e.duration,a=Ne(e.timestamp,s);if(this.frameRateLastSample!==null)if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=i;return}else await this.padFrameRate(a,n);e===r&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/s),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=i}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,r;if(n.transform?.process){let t=n.transform.process(e);if(t instanceof Promise&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]),r=t.map(t=>t instanceof T?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new T(t):new T(t,{timestamp:e.timestamp,duration:e.duration}))}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),k(this.encoderInitialized),this.closed)break;let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{k(this.encoder);let t=e.toVideoFrame(),n=Te(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),r=n===-1?null:this.preciseTimings[n];if(r&&r.microsecondTimestamp===t.timestamp?(r.timestamp!==e.timestamp&&(r.timestampIsValid=!1),r.duration!==e.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(t,a),t.close();else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(t,a),t.close();else{let e=t.displayWidth,n=t.displayHeight;this.splitter||=new Hn(e,n);let{colorFrame:r,alphaFrame:i}=await this.splitter.update(t);this.alphaFrameQueue.push(i),this.encoder.encode(r,a),r.close()}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;k(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r=this.frameRateLastSample.clone();r.setTimestamp(this.frameRateLastTimestamp+e/n),r.setDuration(1/n),await this.processAndEncode(r,t),r.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=pe({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=de.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof s))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);zn(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=s.fromEncodedChunk(e,r),a=Te(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],c=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(c=v(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||c!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:c??void 0})),zn(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e}),this.emittedEncoderPackets++},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();k(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(k(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();k(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}k(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,t=Ne(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Vn=!1,Hn=class e{constructor(t,n){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let r=typeof OffscreenCanvas<`u`||typeof document<`u`&&typeof document.createElement==`function`;if(!e.forceCpu&&r&&!Vn)try{typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(t,n):(this.canvas=document.createElement(`canvas`),this.canvas.width=t,this.canvas.height=n);let e=this.canvas.getContext(`webgl2`,{alpha:!0});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}catch(e){this.gl=null,this.canvas=null,Vn=!0,console.warn(`Falling back to CPU for color/alpha splitting.`,e)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){k(this.gl),k(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),n=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:n}}createVertexShader(){return k(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2
- in vec2 a_position;
3
- in vec2 a_texCoord;
4
- out vec2 v_texCoord;
5
-
6
- void main() {
7
- gl_Position = vec4(a_position, 0.0, 1.0);
8
- v_texCoord = a_texCoord;
9
- }
10
- `)}createColorProgram(){k(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
11
- precision highp float;
12
-
13
- uniform sampler2D u_sourceTexture;
14
- in vec2 v_texCoord;
15
- out vec4 fragColor;
16
-
17
- void main() {
18
- vec4 source = texture(u_sourceTexture, v_texCoord);
19
- fragColor = vec4(source.rgb, 1.0);
20
- }
21
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createAlphaProgram(){k(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
22
- precision highp float;
23
-
24
- uniform sampler2D u_sourceTexture;
25
- uniform vec2 u_resolution; // The width and height of the canvas
26
- in vec2 v_texCoord;
27
- out vec4 fragColor;
28
-
29
- // This function determines the value for a single byte in the YUV stream
30
- float getByteValue(float byteOffset) {
31
- float width = u_resolution.x;
32
- float height = u_resolution.y;
33
-
34
- float yPlaneSize = width * height;
35
-
36
- if (byteOffset < yPlaneSize) {
37
- // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
38
- float y = floor(byteOffset / width);
39
- float x = mod(byteOffset, width);
40
-
41
- // Add 0.5 to sample the center of the texel
42
- vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
43
-
44
- // The luma value is the alpha from the source texture
45
- return texture(u_sourceTexture, sampleCoord).a;
46
- } else {
47
- // Write a fixed value for chroma and beyond
48
- return 128.0 / 255.0;
49
- }
50
- }
51
-
52
- void main() {
53
- // Each fragment writes 4 bytes (R, G, B, A)
54
- float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
55
- float baseByteOffset = pixelIndex * 4.0;
56
-
57
- vec4 result;
58
- for (int i = 0; i < 4; i++) {
59
- float currentByteOffset = baseByteOffset + float(i);
60
- result[i] = getByteValue(currentByteOffset);
61
- }
62
-
63
- fragColor = result;
64
- }
65
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){k(this.gl);let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error(`Shader compile error:`,this.gl.getShaderInfoLog(n)),n}createVAO(){k(this.gl),k(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.colorProgram,`a_position`),i=this.gl.getAttribLocation(this.colorProgram,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){k(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return k(this.gl),k(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:`discard`})}runAlphaProgram(e){k(this.gl),k(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:n}=this.canvas,r=Math.ceil(t/2)*Math.ceil(n/2),i=t*n+r*2,a=Math.ceil(i/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,i),k(o[t*n]===128),k(o[o.length-1]===128);let s={format:`I420`,codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,s)}updateCpu(e){if(!this.worker){let e=new Blob([`(${Un.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),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=Ve();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.gl?.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null,this.canvas=null,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()}};Hn.forceCpu=!0;var Un=()=>{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.codedWidth,o=t.codedHeight,s=t.allocationSize();if((!e||e.byteLength!==s)&&(e=new Uint8Array(s)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,a,o,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,a,o,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n,r,i)=>{let a=t*n,o=a+Math.ceil(t/2)*Math.ceil(n/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:r===`RGBA`?`RGBX`:`BGRX`,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),l={format:`I420`,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n,r,i)=>{let a=r.includes(`P10`),o=r.includes(`P12`),s=a||o?2:1,c,l;r.startsWith(`I420`)?(c=Math.ceil(t/2),l=Math.ceil(n/2)):r.startsWith(`I422`)?(c=Math.ceil(t/2),l=n):(c=t,l=n);let u=t*n,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=r.replace(`A`,``),_=Math.ceil(t/2)*Math.ceil(n/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,ee=a?512:o?2048:128;s===1?y.fill(ee,x):new Uint16Array(y.buffer,x,2*_).fill(ee);let te=a?`I420P10`:o?`I420P12`:`I420`,ne=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),S={format:te,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[y.buffer]};return{colorFrame:ne,alphaFrame:new VideoFrame(y,S)}}},Wn=class extends Rn{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.`);ye(t),super(t.codec),this._encoder=new Bn(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 T(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Gn=class extends Ln{constructor(e){if(super(),this._connectedTrack=null,!h.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${h.join(`, `)}.`);this._codec=e}},Kn=class{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 Ie,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,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 In({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&&Ke(e.format)!==n.transform.sampleFormat){let r=Be(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 D))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),k(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 D({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)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{k(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){k(this.outputSampleSize),k(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,c=[];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),s=new DataView(a);c.push({frameCount:r,view:s})}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<c.length;e++){let{frameCount:r,view:i}=c[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<c.length;e++){let{frameCount:t,view:n}=c[e],r=n.buffer,l=e*o,u=new s(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=ze({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=Le.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 s))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(Je.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:ie(S(t.decoderConfig.description)).objectType===0,e){let e=Number(E(r.codec.split(`.`)));t.decoderConfig.description=ae({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=s.fromEncodedChunk(e);n=n.clone({timestamp:qe(n.timestamp,r.sampleRate),duration:e.duration==null?void 0:qe(n.duration,r.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(r)}k(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}=C(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,A((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,A(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=A(Math.floor(n*32767),-32768,32767);e.setUint8(t,Ae(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=A(Math.floor(n*32767),-32768,32767);e.setUint8(t,se(r))}:k(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,A((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,A(Math.round(n*32767),-32768,32767),r):k(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>Ge(e,t,A((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>ue(e,t,A(Math.round(n*8388607),-8388608,8388607),r):k(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,A((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,A(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):k(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):k(!1);break;default:fe(n),k(!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.error)throw this.error}},qn=class extends Gn{constructor(e){Ee(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Kn(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=D._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)}},Jn=class extends Ln{constructor(e){if(super(),this._connectedTrack=null,!n.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${n.join(`, `)}.`);this._codec=e}},Yn=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>w.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>h.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>n.includes(e))}_codecUnsupportedHint(e){return``}},Xn=class extends Yn{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 Fn(e,this)}},Zn=class extends Xn{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...w,...x,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...n]}_codecUnsupportedHint(e){return new $n().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Qn=class extends Xn{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...w,...x,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...n]}},$n=class extends Xn{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...w,...h]}_codecUnsupportedHint(e){return new Zn().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},er=[`video`,`audio`,`subtitle`],tr=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=Ue(this.metadata.group),r=Ue(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}},nr=class extends tr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},rr=class extends tr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},ir=class extends tr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},ar=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)}},or=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!De(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&&he(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 ar)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof ar))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},sr=class extends xe{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 ar,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Re,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 Yn))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof Mn))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){k(this._target instanceof Mn);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){k(this._target instanceof Mn);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(k(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 Dn(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Rn))throw TypeError(`source must be a VideoSource.`);if(or(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 nr(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Gn))throw TypeError(`source must be an AudioSource.`);or(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new rr(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Jn))throw TypeError(`source must be a SubtitleSource.`);or(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new ir(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 er){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?(console.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 console.warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&console.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?(console.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()}})()}};function cr(e,t,n,r){let i=Error(t);return i.code=e,n!==void 0&&(i.details=n),r!==void 0&&(i.cause=r),i}function lr(){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 lr()}function ur(e){return Math.round(e/2)*2}function dr(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function fr(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 pr(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:ur(t),height:ur(n)}}function mr(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 hr(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 gr(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 _r(e,t){let n=o(),r=n.sceneCanvas._canvas;if(r.width=e.width*t,r.height=e.height*t,r.width<=0||r.height<=0)throw cr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}async function vr(e,t){let n=new sr({target:new An,format:new Zn}),r=await Me(n.format.getSupportedVideoCodecs(),{width:e.width,height:e.height});if(!r)throw cr(`VIDEO_FAILED`,`Your browser doesn't support video encoding.`,{reason:`no-encoder`});let i=new Wn(e,{codec:r,bitrate:we});return n.addVideoTrack(i,{frameRate:t}),{output:n,canvasSource:i}}async function yr(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=mr(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 ge(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 qn({codec:c,bitrate:we});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function br(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 xr(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function Sr(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=br(_,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 xr(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 Cr(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw cr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function wr(e,t){return e.decodeAudioData(t)}function Tr(e){return e.startsWith(`data:`)}function Er(e){return e.startsWith(`file://`)}function Dr(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function Or(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 kr(e,t){try{return Dr(e)?new Fe({source:new ee(e),formats:le}):Tr(e)?new Fe({source:new We(Or(e)),formats:le}):(Er(e),new Fe({source:new We(await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer()),formats:le}))}catch(n){return Q(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function Ar(e,t){try{$(t);let n=await kr(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(),lr();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 lr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function jr(e,t){let n=e.audios||[],r=mr(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:Cr(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:Ar(e.src,t).catch(e=>{if(Q(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function Mr(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 Nr(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=c(e.animations,e.pageDuration),s=(o-a)/1e3,l=Math.max(0,(e.pageStartTime+a)/1e3),u=Math.max(0,r),d=Math.min(i,t.duration-u);if(d<=0||s<=0||u>=t.duration)return;let f=n.offlineContext.createBufferSource();f.buffer=t,f.playbackRate.value=e.speed,f.loop=!0,f.loopStart=u,f.loopEnd=u+d;let p=n.offlineContext.createGain();p.gain.value=e.volume,f.connect(p),p.connect(n.offlineContext.destination),f.start(l,u),f.stop(l+s)}async function Pr(e,t,n,r,i,a,o){$(o);let s=i||jr(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 wr(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 be(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&&Mr(e.audio,e.audioBuffer,_);for(let e of y)e&&Nr(e.video,e.audioBuffer,_);$(o);let b=await g.startRendering();a?.(.99),$(o),await t.add(b)}async function Fr({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){let o=pr(e),s=hr(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=dr(e);if(s===0)throw cr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let d=fr(e),{canvas:p,canvases:m}=_r(o,n),h=await vr(p,t);c=h.output,l=h.canvasSource;let g=await yr(c,e,i);u=g.audioBufferSource||null;let _=g.audioCodec;$(a),await c.start(),await Sr(e,l,m,d,s,t,n,r,a),l.close();let v=u?jr(e,a):null;u&&v&&(await Pr(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?lr():e}finally{if(d?.(),!f&&c)try{await c.cancel()}catch{}gr(e,s)}}export{Fr as storeToVideo};