polotno-node 2.15.1 → 2.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{A as Ve,a as f,t as I,i as J,k as Ne,b as _e,R as yt,U as Ct,p as D,l as Q,c as Et,P as ee,g as vt,C as $e,T as Le,M as He,d as te,e as St,f as _t,h as xt,v as kt,j as At,s as Pt,m as Mt,n as Ot,o as zt,q as Bt,r as Ft,u as It,w as Rt,x as ze,y as le,V as $,N as Ut,S as ce,z as q,B as be,D as ye,E as Ce,F as Qe,G as Wt,H as Vt,I as Nt,J as $t,K as qe,L as je,O as Ge,Q as re,W as Lt,X as Ht,Y as z,Z as Qt,_ as qt,$ as jt,a0 as Gt,a1 as Kt,a2 as Xt,a3 as Yt,a4 as Zt,a5 as Jt,a6 as ne,a7 as oe,a8 as Dt,a9 as he}from"./index-Ca74A7-l.js";class es{constructor(e){this.mutex=new Ve,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,s,i){s+=e.source._timestampOffset;let r=this.trackTimestampInfo.get(e);if(!r){if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:s,maxTimestampBeforeLastKeyPacket:s},this.trackTimestampInfo.set(e,r)}if(s<0)throw new Error(`Timestamps must be non-negative (got ${s}s).`);if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),s<r.maxTimestampBeforeLastKeyPacket)throw new 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 ${s}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,s),s}}const Be=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ts=t=>{const e=Math.floor(t/36e5),s=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),r=t%1e3;return e.toString().padStart(2,"0")+":"+s.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+r.toString().padStart(3,"0")};class Fe{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 s=0;s<e.length;s++)this.helperView.setUint8(s%8,e.charCodeAt(s)),s%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{const s=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const n of e.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=e.size??i-s;this.writer.seek(s),this.writeBoxHeader(e,r),this.writer.seek(i)}}writeBoxHeader(e,s){this.writeU32(e.largeSize?1:s),this.writeAscii(e.type),e.largeSize&&this.writeU64(s)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const s=this.offsets.get(e);f(s!==void 0);const i=this.writer.getPos();this.writer.seek(s),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let s=this.measureBoxHeader(e);if(e.contents&&(s+=e.contents.byteLength),e.children)for(const i of e.children)i&&(s+=this.measureBox(i));return s}}}const b=new Uint8Array(8),R=new DataView(b.buffer),v=t=>[(t%256+256)%256],w=t=>(R.setUint16(0,t,!1),[b[0],b[1]]),Ke=t=>(R.setInt16(0,t,!1),[b[0],b[1]]),Xe=t=>(R.setUint32(0,t,!1),[b[1],b[2],b[3]]),l=t=>(R.setUint32(0,t,!1),[b[0],b[1],b[2],b[3]]),N=t=>(R.setInt32(0,t,!1),[b[0],b[1],b[2],b[3]]),j=t=>(R.setUint32(0,Math.floor(t/2**32),!1),R.setUint32(4,t,!1),[b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]]),Ye=t=>(R.setInt16(0,2**8*t,!1),[b[0],b[1]]),W=t=>(R.setInt32(0,2**16*t,!1),[b[0],b[1],b[2],b[3]]),fe=t=>(R.setInt32(0,2**30*t,!1),[b[0],b[1],b[2],b[3]]),me=(t,e)=>{const s=[];let i=t;do{let r=i&127;i>>=7,s.length>0&&(r|=128),s.push(r)}while(i>0||e);return s.reverse()},k=(t,e=!1)=>{const s=Array(t.length).fill(null).map((i,r)=>t.charCodeAt(r));return e&&s.push(0),s},xe=t=>{let e=null;for(const s of t)(!e||s.timestamp>e.timestamp)&&(e=s);return e},Ze=t=>{const e=t*(Math.PI/180),s=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[s,i,0,-i,s,0,0,0,1]},Je=Ze(0),De=t=>[W(t[0]),W(t[1]),fe(t[2]),W(t[3]),W(t[4]),fe(t[5]),W(t[6]),W(t[7]),fe(t[8])],T=(t,e,s)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:s}),C=(t,e,s,i,r)=>T(t,[v(e),Xe(s),i??[]],r),ss=t=>t.isQuickTime?T("ftyp",[k("qt "),l(512),k("qt ")]):t.fragmented?T("ftyp",[k("iso5"),l(512),k("iso5"),k("iso6"),k("mp41")]):T("ftyp",[k("isom"),l(512),k("isom"),t.holdsAvc?k("avc1"):[],k("mp41")]),ae=t=>({type:"mdat",largeSize:t}),is=t=>({type:"free",size:t}),ie=t=>T("moov",void 0,[rs(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>ns(e,t.creationTime)),t.isFragmented?Ns(t.trackDatas):null,Ds(t)]),rs=(t,e)=>{const s=_(Math.max(0,...e.filter(o=>o.samples.length>0).map(o=>{const a=xe(o.samples);return a.timestamp+a.duration})),Ee),i=Math.max(0,...e.map(o=>o.track.id))+1,r=!J(t)||!J(s),n=r?j:l;return C("mvhd",+r,0,[n(t),n(t),l(Ee),n(s),W(1),Ye(1),Array(10).fill(0),De(Je),Array(24).fill(0),l(i)])},ns=(t,e)=>{const s=di(t);return T("trak",void 0,[os(t,e),as(t,e),s.name!==void 0?T("udta",void 0,[T("name",[...I.encode(s.name)])]):null])},os=(t,e)=>{const s=xe(t.samples),i=_(s?s.timestamp+s.duration:0,Ee),r=!J(e)||!J(i),n=r?j:l;let o;if(t.type==="video"){const u=t.track.metadata.rotation;o=Ze(u??0)}else o=Je;let a=2;return t.track.metadata.disposition?.default!==!1&&(a|=1),C("tkhd",+r,a,[n(e),n(e),l(t.track.id),l(0),n(i),Array(8).fill(0),w(0),w(t.track.id),Ye(t.type==="audio"?1:0),w(0),De(o),W(t.type==="video"?t.info.width:0),W(t.type==="video"?t.info.height:0)])},as=(t,e)=>T("mdia",void 0,[cs(t,e),ke(!0,us[t.type],ds[t.type]),ls(t)]),cs=(t,e)=>{const s=xe(t.samples),i=_(s?s.timestamp+s.duration:0,t.timescale),r=!J(e)||!J(i),n=r?j:l;return C("mdhd",+r,0,[n(e),n(e),l(t.timescale),n(i),w(it(t.track.metadata.languageCode??Ct)),w(0)])},us={video:"vide",audio:"soun",subtitle:"text"},ds={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ke=(t,e,s,i="\0\0\0\0")=>C("hdlr",0,0,[t?k("mhlr"):l(0),k(e),k(i),l(0),l(0),k(s,!0)]),ls=t=>T("minf",void 0,[ps[t.type](),gs(),bs(t)]),hs=()=>C("vmhd",0,1,[w(0),w(0),w(0),w(0)]),fs=()=>C("smhd",0,0,[w(0),w(0)]),ms=()=>C("nmhd",0,0),ps={video:hs,audio:fs,subtitle:ms},gs=()=>T("dinf",void 0,[ws()]),ws=()=>C("dref",0,0,[l(1)],[Ts()]),Ts=()=>C("url ",0,1),bs=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(s=>s.sampleCompositionTimeOffset!==0);return T("stbl",void 0,[ys(t),Bs(t),e?Ws(t):null,e?Vs(t):null,Is(t),Rs(t),Us(t),Fs(t)])},ys=t=>{let e;if(t.type==="video")e=Cs(ii(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const s=st(t.track.source._codec,t.muxer.isQuickTime);f(s),e=xs(s,t)}else t.type==="subtitle"&&(e=Os(oi[t.track.source._codec],t));return f(e),C("stsd",0,0,[l(1)],[e])},Cs=(t,e)=>T(t,[Array(6).fill(0),w(1),w(0),w(0),Array(12).fill(0),w(e.info.width),w(e.info.height),l(4718592),l(4718592),l(0),w(1),Array(32).fill(0),w(24),Ke(65535)],[ri[e.track.source._codec](e),Et(e.info.decoderConfig.colorSpace)?Es(e):null]),Es=t=>T("colr",[k("nclx"),w($e[t.info.decoderConfig.colorSpace.primaries]),w(Le[t.info.decoderConfig.colorSpace.transfer]),w(He[t.info.decoderConfig.colorSpace.matrix]),v((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),vs=t=>t.info.decoderConfig&&T("avcC",[...te(t.info.decoderConfig.description)]),Ss=t=>t.info.decoderConfig&&T("hvcC",[...te(t.info.decoderConfig.description)]),Ie=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,s=e.codec.split("."),i=Number(s[1]),r=Number(s[2]),n=Number(s[3]),o=s[4]?Number(s[4]):1,a=s[8]?Number(s[8]):Number(e.colorSpace?.fullRange??0),u=(n<<4)+(o<<1)+a,c=s[5]?Number(s[5]):e.colorSpace?.primaries?$e[e.colorSpace.primaries]:2,d=s[6]?Number(s[6]):e.colorSpace?.transfer?Le[e.colorSpace.transfer]:2,p=s[7]?Number(s[7]):e.colorSpace?.matrix?He[e.colorSpace.matrix]:2;return C("vpcC",1,0,[v(i),v(r),v(u),v(c),v(d),v(p),w(0)])},_s=t=>T("av1C",vt(t.info.decoderConfig.codec)),xs=(t,e)=>{let s=0,i,r=16;if(ee.includes(e.track.source._codec)){const n=e.track.source._codec,{sampleSize:o}=D(n);r=8*o,r>16&&(s=1)}return s===0?i=[Array(6).fill(0),w(1),w(s),w(0),l(0),w(e.info.numberOfChannels),w(r),w(0),w(0),w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0)]:i=[Array(6).fill(0),w(1),w(s),w(0),l(0),w(e.info.numberOfChannels),w(Math.min(r,16)),w(0),w(0),w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0),l(1),l(r/8),l(e.info.numberOfChannels*r/8),l(2)],T(t,i,[ni(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},pe=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let s=[...v(e),...v(21),...Xe(0),...l(0),...l(0)];if(t.info.decoderConfig.description){const i=te(t.info.decoderConfig.description);s=[...s,...v(5),...me(i.byteLength),...i]}return s=[...w(1),...v(0),...v(4),...me(s.length),...s,...v(6),...v(1),...v(2)],s=[...v(3),...me(s.length),...s],C("esds",0,0,s)},V=t=>T("wave",void 0,[ks(t),As(t),T("\0\0\0\0")]),ks=t=>T("frma",[k(st(t.track.source._codec,t.muxer.isQuickTime))]),As=t=>{const{littleEndian:e}=D(t.track.source._codec);return T("enda",[w(+e)])},Ps=t=>{let e=t.info.numberOfChannels,s=3840,i=t.info.sampleRate,r=0,n=0,o=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){f(a.byteLength>=18);const u=te(a),c=St(u);e=c.outputChannelCount,s=c.preSkip,i=c.inputSampleRate,r=c.outputGain,n=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return T("dOps",[v(0),v(e),w(s),l(i),Ke(r),v(n),...o])},Ms=t=>{const e=t.info.decoderConfig?.description;f(e);const s=te(e);return C("dfLa",0,0,[...s.subarray(4)])},B=t=>{const{littleEndian:e,sampleSize:s}=D(t.track.source._codec),i=+e;return C("pcmC",0,0,[v(i),v(8*s)])},Os=(t,e)=>T(t,[Array(6).fill(0),w(1)],[ai[e.track.source._codec](e)]),zs=t=>T("vttC",[...I.encode(t.info.config.description)]),Bs=t=>C("stts",0,0,[l(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[l(e.sampleCount),l(e.sampleDelta)])]),Fs=t=>{if(t.samples.every(s=>s.type==="key"))return null;const e=[...t.samples.entries()].filter(([,s])=>s.type==="key");return C("stss",0,0,[l(e.length),e.map(([s])=>l(s+1))])},Is=t=>C("stsc",0,0,[l(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[l(e.firstChunk),l(e.samplesPerChunk),l(1)])]),Rs=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=D(t.track.source._codec);return C("stsz",0,0,[l(e*t.info.numberOfChannels),l(t.samples.reduce((s,i)=>s+_(i.duration,t.timescale),0))])}return C("stsz",0,0,[l(0),l(t.samples.length),t.samples.map(e=>l(e.size))])},Us=t=>t.finalizedChunks.length>0&&Q(t.finalizedChunks).offset>=2**32?C("co64",0,0,[l(t.finalizedChunks.length),t.finalizedChunks.map(e=>j(e.offset))]):C("stco",0,0,[l(t.finalizedChunks.length),t.finalizedChunks.map(e=>l(e.offset))]),Ws=t=>C("ctts",1,0,[l(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[l(e.sampleCount),N(e.sampleCompositionTimeOffset)])]),Vs=t=>{let e=1/0,s=-1/0,i=1/0,r=-1/0;f(t.compositionTimeOffsetTable.length>0),f(t.samples.length>0);for(let o=0;o<t.compositionTimeOffsetTable.length;o++){const a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),s=Math.max(s,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){const a=t.samples[o];i=Math.min(i,_(a.timestamp,t.timescale)),r=Math.max(r,_(a.timestamp+a.duration,t.timescale))}const n=Math.max(-e,0);return r>=2**31?null:C("cslg",0,0,[N(n),N(e),N(s),N(i),N(r)])},Ns=t=>T("mvex",void 0,t.map($s)),$s=t=>C("trex",0,0,[l(t.track.id),l(1),l(0),l(0),l(0)]),Re=(t,e)=>T("moof",void 0,[Ls(t),...e.map(Hs)]),Ls=t=>C("mfhd",0,0,[l(t)]),et=t=>{let e=0,s=0;const i=0,r=0,n=t.type==="delta";return s|=+n,n?e|=1:e|=2,e<<24|s<<16|i<<8|r},Hs=t=>T("traf",void 0,[Qs(t),qs(t),js(t)]),Qs=t=>{f(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const s=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:s.timescaleUnitsToNextSample,size:s.size,flags:et(s)};return C("tfhd",0,e,[l(t.track.id),l(i.duration),l(i.size),l(i.flags)])},qs=t=>(f(t.currentChunk),C("tfdt",1,0,[j(_(t.currentChunk.startTimestamp,t.timescale))])),js=t=>{f(t.currentChunk);const e=t.currentChunk.samples.map(y=>y.timescaleUnitsToNextSample),s=t.currentChunk.samples.map(y=>y.size),i=t.currentChunk.samples.map(et),r=t.currentChunk.samples.map(y=>_(y.timestamp-y.decodeTimestamp,t.timescale)),n=new Set(e),o=new Set(s),a=new Set(i),u=new Set(r),c=a.size===2&&i[0]!==i[1],d=n.size>1,p=o.size>1,h=!c&&a.size>1,m=u.size>1||[...u].some(y=>y!==0);let g=0;return g|=1,g|=4*+c,g|=256*+d,g|=512*+p,g|=1024*+h,g|=2048*+m,C("trun",1,g,[l(t.currentChunk.samples.length),l(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?l(i[0]):[],t.currentChunk.samples.map((y,E)=>[d?l(e[E]):[],p?l(s[E]):[],h?l(i[E]):[],m?N(r[E]):[]])])},Gs=t=>T("mfra",void 0,[...t.map(Ks),Xs()]),Ks=(t,e)=>C("tfra",1,0,[l(t.track.id),l(63),l(t.finalizedChunks.length),t.finalizedChunks.map(i=>[j(_(i.samples[0].timestamp,t.timescale)),j(i.moofOffset),l(e+1),l(1),l(1)])]),Xs=()=>C("mfro",0,0,[l(0)]),Ys=()=>T("vtte"),Zs=(t,e,s,i,r)=>T("vttc",void 0,[r!==null?T("vsid",[N(r)]):null,s!==null?T("iden",[...I.encode(s)]):null,e!==null?T("ctim",[...I.encode(ts(e))]):null,i!==null?T("sttg",[...I.encode(i)]):null,T("payl",[...I.encode(t)])]),Js=t=>T("vtta",[...I.encode(t)]),Ds=t=>{const e=[],s=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(s==="mdir"||s==="auto"&&!t.isQuickTime){const r=ti(i);r&&e.push(r)}else if(s==="mdta"){const r=si(i);r&&e.push(r)}else(s==="udta"||s==="auto"&&t.isQuickTime)&&ei(e,t.output._metadataTags);return e.length===0?null:T("udta",void 0,e)},ei=(t,e)=>{for(const{key:s,value:i}of Ne(e))switch(s){case"title":t.push(F("©nam",i));break;case"description":t.push(F("©des",i));break;case"artist":t.push(F("©ART",i));break;case"album":t.push(F("©alb",i));break;case"albumArtist":t.push(F("albr",i));break;case"genre":t.push(F("©gen",i));break;case"date":t.push(F("©day",i.toISOString().slice(0,10)));break;case"comment":t.push(F("©cmt",i));break;case"lyrics":t.push(F("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:_e(s)}if(e.raw)for(const s in e.raw){const i=e.raw[s];i==null||s.length!==4||t.some(r=>r.type===s)||(typeof i=="string"?t.push(F(s,i)):i instanceof Uint8Array&&t.push(T(s,Array.from(i))))}},F=(t,e)=>{const s=I.encode(e);return T(t,[w(s.length),w(it("und")),Array.from(s)])},Ue={"image/jpeg":13,"image/png":14,"image/bmp":27},tt=(t,e)=>{const s=[];for(const{key:i,value:r}of Ne(t))switch(i){case"title":s.push({key:e?"title":"©nam",value:M(r)});break;case"description":s.push({key:e?"description":"©des",value:M(r)});break;case"artist":s.push({key:e?"artist":"©ART",value:M(r)});break;case"album":s.push({key:e?"album":"©alb",value:M(r)});break;case"albumArtist":s.push({key:e?"album_artist":"aART",value:M(r)});break;case"comment":s.push({key:e?"comment":"©cmt",value:M(r)});break;case"genre":s.push({key:e?"genre":"©gen",value:M(r)});break;case"lyrics":s.push({key:e?"lyrics":"©lyr",value:M(r)});break;case"date":s.push({key:e?"date":"©day",value:M(r.toISOString().slice(0,10))});break;case"images":for(const n of r)n.kind==="coverFront"&&s.push({key:"covr",value:T("data",[l(Ue[n.mimeType]??0),l(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=t.tracksTotal!==void 0?`${r}/${t.tracksTotal}`:r.toString();s.push({key:"track",value:M(n)})}else s.push({key:"trkn",value:T("data",[l(0),l(0),w(0),w(r),w(t.tracksTotal??0),w(0)])});break;case"discNumber":e||s.push({key:"disc",value:T("data",[l(0),l(0),w(0),w(r),w(t.discsTotal??0),w(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:_e(i)}if(t.raw)for(const i in t.raw){const r=t.raw[i];r==null||!e&&i.length!==4||s.some(n=>n.key===i)||(typeof r=="string"?s.push({key:i,value:M(r)}):r instanceof Uint8Array?s.push({key:i,value:T("data",[l(0),l(0),Array.from(r)])}):r instanceof yt&&s.push({key:i,value:T("data",[l(Ue[r.mimeType]??0),l(0),Array.from(r.data)])}))}return s},ti=t=>{const e=tt(t,!1);return e.length===0?null:C("meta",0,0,void 0,[ke(!1,"mdir","","appl"),T("ilst",void 0,e.map(s=>T(s.key,void 0,[s.value])))])},si=t=>{const e=tt(t,!0);return e.length===0?null:T("meta",void 0,[ke(!1,"mdta",""),C("keys",0,0,[l(e.length)],e.map(s=>T("mdta",[...I.encode(s.key)]))),T("ilst",void 0,e.map((s,i)=>{const r=String.fromCharCode(...l(i+1));return T(r,void 0,[s.value])}))])},M=t=>T("data",[l(1),l(0),...I.encode(t)]),ii=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},ri={avc:vs,hevc:Ss,vp8:Ie,vp9:Ie,av1:_s},st=(t,e)=>{switch(t){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"}if(e)switch(t){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(t){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"}},ni=(t,e)=>{switch(t){case"aac":return pe;case"mp3":return pe;case"opus":return Ps;case"vorbis":return pe;case"flac":return Ms}if(e)switch(t){case"pcm-s24":return V;case"pcm-s24be":return V;case"pcm-s32":return V;case"pcm-s32be":return V;case"pcm-f32":return V;case"pcm-f32be":return V;case"pcm-f64":return V;case"pcm-f64be":return V}else switch(t){case"pcm-s16":return B;case"pcm-s16be":return B;case"pcm-s24":return B;case"pcm-s24be":return B;case"pcm-s32":return B;case"pcm-s32be":return B;case"pcm-f32":return B;case"pcm-f32be":return B;case"pcm-f64":return B;case"pcm-f64be":return B}return null},oi={webvtt:"wvtt"},ai={webvtt:zs},it=t=>{f(t.length===3);let e=0;for(let s=0;s<3;s++)e<<=5,e+=t.charCodeAt(s)-96;return e};class ci{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let s=this.getPos();if(s<this.trackedStart){if(s+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-s),s=0}const i=s+e.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const n=new Uint8Array(r);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,s-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,s+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const s={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,s}}const ge=2**16,we=2**32;class rt extends ci{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(ge,{maxByteLength:we})}catch{this.buffer=new ArrayBuffer(ge),this.supportsResize=!1}else this.buffer=new ArrayBuffer(ge);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let s=this.buffer.byteLength;for(;s<e;)s*=2;if(s!==this.buffer.byteLength){if(s>we)throw new Error(`ArrayBuffer exceeded maximum size of ${we} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(s);else{const i=new ArrayBuffer(s),r=new Uint8Array(i);r.set(this.bytes,0),this.buffer=i,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,s){return this.bytes.slice(e,s)}}class nt{constructor(){this._output=null,this.onwrite=null}}class ot extends nt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new rt(this)}}const Ee=1e3,ui=2082844800,di=t=>{const e={},s=t.track;return s.metadata.name!==void 0&&(e.name=s.metadata.name),e},_=(t,e,s=!0)=>{const i=t*e;return s?Math.round(i):i};class li extends es{constructor(e,s){super(e),this.auxTarget=new ot,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Fe(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_t(),this.creationTime=Math.floor(Date.now()/1e3)+ui,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=s,this.writer=e._writer,this.boxWriter=new Fe(this.writer),this.isQuickTime=s instanceof dt;const i=this.writer instanceof rt?"in-memory":!1;this.fastStart=s._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=s._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),s=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(ss({isQuickTime:this.isQuickTime,holdsAvc:s,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:r}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,r)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ae(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(s=>s.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(s=>s.type==="video"||s.type==="audio"?s.info.decoderConfig.codec:{webvtt:"wvtt"}[s.track.source._codec]);return xt({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(s=>s.type==="video"),hasAudio:this.trackDatas.some(s=>s.type==="audio"),codecStrings:e})}getVideoTrackData(e,s,i){const r=this.trackDatas.find(c=>c.track===e);if(r)return r;kt(i),f(i),f(i.decoderConfig);const n={...i.decoderConfig};f(n.codedWidth!==void 0),f(n.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!n.description){const c=At(s.data);if(!c)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=Pt(c),o=!0}else if(e.source._codec==="hevc"&&!n.description){const c=Mt(s.data);if(!c)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Ot(c),o=!0}const a=zt(1/(e.metadata.frameRate??57600),1e6).denominator,u={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:o},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,s){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Bt(s),f(s),f(s.decoderConfig);const r={muxer:this,track:e,type:"audio",info:{numberOfChannels:s.decoderConfig.numberOfChannels,sampleRate:s.decoderConfig.sampleRate,decoderConfig:s.decoderConfig,requiresPcmTransformation:!this.isFragmented&&ee.includes(e.source._codec)},timescale:s.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}getSubtitleTrackData(e,s){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Ft(s),f(s),f(s.config);const r={muxer:this,track:e,type:"subtitle",info:{config:s.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,s,i){const r=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,s,i);let o=s.data;if(n.info.requiresAnnexBTransformation){const c=It(o);if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Rt(c,4)}const a=this.validateAndNormalizeTimestamp(n.track,s.timestamp,s.type==="key"),u=this.createSampleForTrack(n,o,a,s.duration,s.type);await this.registerSample(n,u)}finally{r()}}async addEncodedAudioPacket(e,s,i){const r=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i),o=this.validateAndNormalizeTimestamp(n.track,s.timestamp,s.type==="key"),a=this.createSampleForTrack(n,s.data,o,s.duration,s.type);n.info.requiresPcmTransformation&&await this.maybePadWithSilence(n,o),await this.registerSample(n,a)}finally{r()}}async maybePadWithSilence(e,s){const i=Q(e.samples),r=i?i.timestamp+i.duration:0,n=s-r,o=_(n,e.timescale);if(o>0){const{sampleSize:a,silentValue:u}=D(e.info.decoderConfig.codec),c=o*e.info.numberOfChannels,d=new Uint8Array(a*c).fill(u),p=this.createSampleForTrack(e,new Uint8Array(d.buffer),r,n,"key");await this.registerSample(e,p)}}async addSubtitleCue(e,s,i){const r=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,s.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(s),await this.processWebVTTCues(n,s.timestamp))}finally{r()}}async processWebVTTCues(e,s){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)f(c.timestamp<=s),f(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const r=[...i].sort((c,d)=>c-d),n=r[0],o=r[1]??n;if(s<o)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const c=Ys();this.auxBoxWriter.writeBox(c);const d=this.auxWriter.getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,p),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const d=e.cueQueue[c];if(d.timestamp>=o)break;Be.lastIndex=0;const p=Be.test(d.text),h=d.timestamp+d.duration;let m=e.cueToSourceId.get(d);if(m===void 0&&o<h&&(m=e.nextSourceId++,e.cueToSourceId.set(d,m)),d.notes){const y=Js(d.notes);this.auxBoxWriter.writeBox(y)}const g=Zs(d.text,p?n:null,d.identifier??null,d.settings??null,m??null);this.auxBoxWriter.writeBox(g),h===o&&e.cueQueue.splice(c--,1)}const a=this.auxWriter.getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,a,n,o-n,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=o}}createSampleForTrack(e,s,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:s,size:s.byteLength,type:n,timescaleUnitsToNextSample:_(r,e.timescale)}}processTimestamps(e,s){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let r=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const o=e.timestampProcessingQueue[n],a=_(o.duration,e.timescale);r+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:r,sampleDelta:1});else{const n=Q(e.timeToSampleTable);n.sampleCount+=r}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(r=>r.timestamp).sort((r,n)=>r-n);for(let r=0;r<e.timestampProcessingQueue.length;r++){const n=e.timestampProcessingQueue[r];n.decodeTimestamp=i[r],!this.isFragmented&&e.lastTimescaleUnits===null&&(n.decodeTimestamp=0);const o=_(n.timestamp-n.decodeTimestamp,e.timescale),a=_(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){f(e.lastSample);const u=_(n.decodeTimestamp,e.timescale,!1),c=Math.round(u-e.lastTimescaleUnits);if(f(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let d=Q(e.timeToSampleTable);if(f(d),d.sampleCount===1){d.sampleDelta=c;const h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===c&&(h.sampleCount++,e.timeToSampleTable.pop(),d=h)}else d.sampleDelta!==c&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:c}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const p=Q(e.compositionTimeOffsetTable);f(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=_(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,f(e.lastSample),f(e.lastTimescaleUnits!==null),s!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){f(s.type==="key");const r=_(s.timestamp,e.timescale,!1),n=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,s){s.type==="key"&&this.processTimestamps(e,s),e.timestampProcessingQueue.push(s),this.isFragmented?(e.sampleQueue.push(s),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,s):await this.addSampleToTrack(e,s)}async addSampleToTrack(e,s){if(!this.isFragmented&&(e.samples.push(s),this.fastStart==="reserve")){const r=e.track.metadata.maximumPacketCount;if(f(r!==void 0),e.samples.length>r)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${r}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,s.timestamp);const r=s.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(o=>{if(e===o)return s.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.track.source._closed});r>=this.minimumFragmentDuration&&n&&s.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:s.timestamp,samples:[],offset:null,moofOffset:null}),f(e.currentChunk),e.currentChunk.samples.push(s),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,s.timestamp))}async finalizeCurrentChunk(e){if(f(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let s=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(s=e.currentChunk.samples.reduce((i,r)=>i+_(r.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Q(e.compactlyCodedChunkTable).samplesPerChunk!==s)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:s}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)f(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(f(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let s=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.track.source._closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(s=n,i=n.sampleQueue[0].timestamp)}if(!s)break;const r=s.sampleQueue.shift();await this.addSampleToTrack(s,r)}}async finalizeFragment(e=!0){f(this.isFragmented);const s=this.nextFragmentNumber++;if(s===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const m=ie(this);if(this.boxWriter.writeBox(m),this.format._options.onMoov){const{data:g,start:y}=this.writer.stopTrackingWrites();this.format._options.onMoov(g,y)}}const i=this.trackDatas.filter(m=>m.currentChunk),r=Re(s,i),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let a=o+le,u=1/0;for(const m of i){m.currentChunk.offset=a,m.currentChunk.moofOffset=n;for(const g of m.currentChunk.samples)a+=g.size;u=Math.min(u,m.currentChunk.startTimestamp)}const c=a-o,d=c>=2**32;if(d)for(const m of i)m.currentChunk.offset+=ze-le;this.format._options.onMoof&&this.writer.startTrackingWrites();const p=Re(s,i);if(this.boxWriter.writeBox(p),this.format._options.onMoof){const{data:m,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,g,u)}f(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=ae(d);h.size=c,this.boxWriter.writeBox(h),this.writer.seek(o+(d?ze:le));for(const m of i)for(const g of m.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){const{data:m,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,g)}for(const m of i)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,s){if(this.allTracksAreKnown()){if(!this.mdat){const i=ie(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;f(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ae(!0),this.boxWriter.writeBox(this.mdat);for(const o of this.trackDatas){for(const a of o.sampleQueue)await this.addSampleToTrack(o,a);o.sampleQueue.length=0}}await this.addSampleToTrack(e,s)}else e.sampleQueue.push(s)}computeSampleTableSizeUpperBound(){f(this.fastStart==="reserve");let e=0;for(const s of this.trackDatas){const i=s.track.metadata.maximumPacketCount;f(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const s=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(r=>r.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),s()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const s of this.trackDatas)s.type==="subtitle"&&s.track.source._codec==="webvtt"&&await this.processWebVTTCues(s,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const s of this.trackDatas)this.processTimestamps(s);await this.finalizeFragment(!1)}else for(const s of this.trackDatas)this.processTimestamps(s),await this.finalizeCurrentChunk(s);if(this.fastStart==="in-memory"){this.mdat=ae(!1);let s;for(let r=0;r<2;r++){const n=ie(this),o=this.boxWriter.measureBox(n);s=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+s;for(const u of this.finalizedChunks){u.offset=a;for(const{data:c}of u.samples)f(c),a+=c.byteLength,s+=c.byteLength}if(a<2**32)break;s>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=ie(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(r,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=s,this.boxWriter.writeBox(this.mdat);for(const r of this.finalizedChunks)for(const n of r.samples)f(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(r,n)}}else if(this.isFragmented){const s=this.writer.getPos(),i=Gs(this.trackDatas);this.boxWriter.writeBox(i);const r=this.writer.getPos()-s;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{f(this.mdat);const s=this.boxWriter.offsets.get(this.mdat);f(s!==void 0);const i=this.writer.getPos()-s;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,o)}const r=ie(this);if(this.fastStart==="reserve"){f(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(is(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,o)}}e()}}class at{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>$.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>q.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ce.includes(e))}_codecUnsupportedHint(e){return""}}class ct extends at{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new 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 new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new li(e,this)}}class ut extends ct{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...$,...Ut,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ce]}_codecUnsupportedHint(e){return new dt().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class dt extends ct{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...$,...q]}_codecUnsupportedHint(e){return new ut().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const hi=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!$.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${$.join(", ")}.`);if(!(t.bitrate instanceof K)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");lt(t.codec,t)},lt=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Qe(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},ve=t=>{const e=t.bitrate instanceof K?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??Vt(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...Wt(t.codec)}},fi=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!q.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${q.join(", ")}.`);if(t.bitrate===void 0&&(!ee.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof K)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ht(t.codec,t)},ht=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Qe(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},Se=t=>{const e=t.bitrate instanceof K?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??$t(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...Nt(t.codec)}};class K{constructor(e){this._factor=e}_toVideoBitrate(e,s,i){const r=s*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},o=1920*1080,a=3e6,u=Math.pow(r/o,.95),p=a*u*n[e]*this._factor;return Math.ceil(p/1e3)*1e3}_toAudioBitrate(e){if(ee.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let r=i*this._factor;return e==="aac"?r=[96e3,128e3,16e4,192e3].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o):e==="opus"||e==="vorbis"?r=Math.max(6e3,r):e==="mp3"&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o)),Math.round(r/1e3)*1e3}}const ft=new K(2),mi=async(t,e={})=>{const{width:s=1280,height:i=720,bitrate:r=1e6,...n}=e;if(!$.includes(t))return!1;if(!Number.isInteger(s)||s<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");lt(t,n);let o=null;return be.length>0&&(o??=ve({codec:t,width:s,height:i,bitrate:r,framerate:void 0,...n}),be.some(c=>c.supports(t,o)))?!0:typeof VideoEncoder>"u"||(s%2===1||i%2===1)&&(t==="avc"||t==="hevc")||(o??=ve({codec:t,width:s,height:i,bitrate:r,framerate:void 0,...n,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:ye()?new Promise(async c=>{try{const d=new VideoEncoder({output:()=>{},error:()=>c(!1)});d.configure(o);const p=new Uint8Array(s*i*4),h=new VideoFrame(p,{format:"RGBA",codedWidth:s,codedHeight:i,timestamp:0});d.encode(h),h.close(),await d.flush(),c(!0)}catch{c(!1)}}):!0},pi=async(t,e={})=>{const{numberOfChannels:s=2,sampleRate:i=48e3,bitrate:r=128e3,...n}=e;if(!q.includes(t))return!1;if(!Number.isInteger(s)||s<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");ht(t,n);let o=null;return Ce.length>0&&(o??=Se({codec:t,numberOfChannels:s,sampleRate:i,bitrate:r,...n}),Ce.some(u=>u.supports(t,o)))||ee.includes(t)?!0:typeof AudioEncoder>"u"?!1:(o??=Se({codec:t,numberOfChannels:s,sampleRate:i,bitrate:r,...n}),(await AudioEncoder.isConfigSupported(o)).supported===!0)},gi=async(t,e)=>{for(const s of t)if(await mi(s,e))return s;return null},wi=async(t,e)=>{for(const s of t)if(await pi(s,e))return s;return null};class Ae{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new 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?this._closingPromise:this._flushAndClose(e)}}class mt extends Ae{constructor(e){if(super(),this._connectedTrack=null,!$.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${$.join(", ")}.`);this._codec=e}}class Ti{constructor(e,s){this.source=e,this.encodingConfig=s,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Ge,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,s,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const a=this.encodingConfig.sizeChangeBehavior??"deny";if(a!=="passThrough"){if(a==="deny")throw new 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 'strict' in the encoding options.`);{let u=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),u=!0);const c=this.resizeCanvas.getContext("2d",{alpha:ye()});f(c),u||(ye()?(c.fillStyle="black",c.fillRect(0,0,this.codedWidth,this.codedHeight)):c.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(c,{fit:a}),s&&e.close(),e=new qe(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),s=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),f(this.encoderInitialized);const r=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/r),o={...i,keyFrame:i?.keyFrame||r===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;const a=e.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(a,o)).then(()=>this.customEncoderQueueSize--).catch(c=>this.error??=c).finally(()=>{a.close()});this.customEncoderQueueSize>=4&&await u}else{f(this.encoder);const a=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(a,o),a.close();else if(!!a.format&&!a.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close();else{const c=a.displayWidth,d=a.displayHeight;if(!this.splitter)try{this.splitter=new bi(c,d)}catch(p){console.error("Due to an error, only color data will be encoded.",p),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close()}if(this.splitter){const p=this.splitter.extractColor(a),h=this.splitter.extractAlpha(a);this.alphaFrameQueue.push(h),this.encoder.encode(p,o),p.close(),a.close()}}s&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(u=>this.encoder.addEventListener("dequeue",u,{once:!0}))}await this.muxer.mutex.currentPromise}finally{s&&e.close()}}ensureEncoder(e){const s=new Error;this.ensureEncoderPromise=(async()=>{const i=ve({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const r=be.find(n=>n.supports(this.encodingConfig.codec,i));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(n,o)=>{if(!(n instanceof re))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,o),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,o).catch(a=>{this.error??=a,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.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(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const a=[],u=[];let c=0,d=0;const p=(h,m,g)=>{const y={};if(m){const x=new Uint8Array(m.byteLength);m.copyTo(x),y.alpha=x}const E=re.fromEncodedChunk(h,y);this.encodingConfig.onEncodedPacket?.(E,g),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,E,g).catch(x=>{this.error??=x,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(h,m)=>{if(!this.alphaEncoder){p(h,null,m);return}const g=this.alphaFrameQueue.shift();f(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:h.type==="key"}),d++,g.close(),a.push({chunk:h,meta:m})):d===0?p(h,null,m):(u.push(c+d),a.push({chunk:h,meta:m}))},error:h=>{h.stack=s.stack,this.error??=h}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(h,m)=>{d--;const g=a.shift();for(f(g!==void 0),p(g.chunk,h,g.meta),c++;u.length>0&&u[0]===c;){u.shift();const y=a.shift();f(y!==void 0),p(y.chunk,null,y.meta)}},error:h=>{h.stack=s.stack,this.error??=h}}),this.alphaEncoder.configure(i))}f(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),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(s=>s?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class bi{constructor(e,s){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,s):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=s);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
1
+ import{A as Ve,a as f,t as I,i as J,k as Ne,b as _e,R as yt,U as Ct,p as D,l as Q,c as Et,P as ee,g as vt,C as $e,T as Le,M as He,d as te,e as St,f as _t,h as xt,v as kt,j as At,s as Pt,m as Mt,n as Ot,o as zt,q as Bt,r as Ft,u as It,w as Rt,x as ze,y as le,V as $,N as Ut,S as ce,z as q,B as be,D as ye,E as Ce,F as Qe,G as Wt,H as Vt,I as Nt,J as $t,K as qe,L as je,O as Ge,Q as re,W as Lt,X as Ht,Y as z,Z as Qt,_ as qt,$ as jt,a0 as Gt,a1 as Kt,a2 as Xt,a3 as Yt,a4 as Zt,a5 as Jt,a6 as ne,a7 as oe,a8 as Dt,a9 as he}from"./index-Dhxj876I.js";class es{constructor(e){this.mutex=new Ve,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,s,i){s+=e.source._timestampOffset;let r=this.trackTimestampInfo.get(e);if(!r){if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:s,maxTimestampBeforeLastKeyPacket:s},this.trackTimestampInfo.set(e,r)}if(s<0)throw new Error(`Timestamps must be non-negative (got ${s}s).`);if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),s<r.maxTimestampBeforeLastKeyPacket)throw new 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 ${s}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,s),s}}const Be=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ts=t=>{const e=Math.floor(t/36e5),s=Math.floor(t%(3600*1e3)/(60*1e3)),i=Math.floor(t%(60*1e3)/1e3),r=t%1e3;return e.toString().padStart(2,"0")+":"+s.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+r.toString().padStart(3,"0")};class Fe{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 s=0;s<e.length;s++)this.helperView.setUint8(s%8,e.charCodeAt(s)),s%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{const s=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const n of e.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=e.size??i-s;this.writer.seek(s),this.writeBoxHeader(e,r),this.writer.seek(i)}}writeBoxHeader(e,s){this.writeU32(e.largeSize?1:s),this.writeAscii(e.type),e.largeSize&&this.writeU64(s)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const s=this.offsets.get(e);f(s!==void 0);const i=this.writer.getPos();this.writer.seek(s),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let s=this.measureBoxHeader(e);if(e.contents&&(s+=e.contents.byteLength),e.children)for(const i of e.children)i&&(s+=this.measureBox(i));return s}}}const b=new Uint8Array(8),R=new DataView(b.buffer),v=t=>[(t%256+256)%256],w=t=>(R.setUint16(0,t,!1),[b[0],b[1]]),Ke=t=>(R.setInt16(0,t,!1),[b[0],b[1]]),Xe=t=>(R.setUint32(0,t,!1),[b[1],b[2],b[3]]),l=t=>(R.setUint32(0,t,!1),[b[0],b[1],b[2],b[3]]),N=t=>(R.setInt32(0,t,!1),[b[0],b[1],b[2],b[3]]),j=t=>(R.setUint32(0,Math.floor(t/2**32),!1),R.setUint32(4,t,!1),[b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7]]),Ye=t=>(R.setInt16(0,2**8*t,!1),[b[0],b[1]]),W=t=>(R.setInt32(0,2**16*t,!1),[b[0],b[1],b[2],b[3]]),fe=t=>(R.setInt32(0,2**30*t,!1),[b[0],b[1],b[2],b[3]]),me=(t,e)=>{const s=[];let i=t;do{let r=i&127;i>>=7,s.length>0&&(r|=128),s.push(r)}while(i>0||e);return s.reverse()},k=(t,e=!1)=>{const s=Array(t.length).fill(null).map((i,r)=>t.charCodeAt(r));return e&&s.push(0),s},xe=t=>{let e=null;for(const s of t)(!e||s.timestamp>e.timestamp)&&(e=s);return e},Ze=t=>{const e=t*(Math.PI/180),s=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[s,i,0,-i,s,0,0,0,1]},Je=Ze(0),De=t=>[W(t[0]),W(t[1]),fe(t[2]),W(t[3]),W(t[4]),fe(t[5]),W(t[6]),W(t[7]),fe(t[8])],T=(t,e,s)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:s}),C=(t,e,s,i,r)=>T(t,[v(e),Xe(s),i??[]],r),ss=t=>t.isQuickTime?T("ftyp",[k("qt "),l(512),k("qt ")]):t.fragmented?T("ftyp",[k("iso5"),l(512),k("iso5"),k("iso6"),k("mp41")]):T("ftyp",[k("isom"),l(512),k("isom"),t.holdsAvc?k("avc1"):[],k("mp41")]),ae=t=>({type:"mdat",largeSize:t}),is=t=>({type:"free",size:t}),ie=t=>T("moov",void 0,[rs(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>ns(e,t.creationTime)),t.isFragmented?Ns(t.trackDatas):null,Ds(t)]),rs=(t,e)=>{const s=_(Math.max(0,...e.filter(o=>o.samples.length>0).map(o=>{const a=xe(o.samples);return a.timestamp+a.duration})),Ee),i=Math.max(0,...e.map(o=>o.track.id))+1,r=!J(t)||!J(s),n=r?j:l;return C("mvhd",+r,0,[n(t),n(t),l(Ee),n(s),W(1),Ye(1),Array(10).fill(0),De(Je),Array(24).fill(0),l(i)])},ns=(t,e)=>{const s=di(t);return T("trak",void 0,[os(t,e),as(t,e),s.name!==void 0?T("udta",void 0,[T("name",[...I.encode(s.name)])]):null])},os=(t,e)=>{const s=xe(t.samples),i=_(s?s.timestamp+s.duration:0,Ee),r=!J(e)||!J(i),n=r?j:l;let o;if(t.type==="video"){const u=t.track.metadata.rotation;o=Ze(u??0)}else o=Je;let a=2;return t.track.metadata.disposition?.default!==!1&&(a|=1),C("tkhd",+r,a,[n(e),n(e),l(t.track.id),l(0),n(i),Array(8).fill(0),w(0),w(t.track.id),Ye(t.type==="audio"?1:0),w(0),De(o),W(t.type==="video"?t.info.width:0),W(t.type==="video"?t.info.height:0)])},as=(t,e)=>T("mdia",void 0,[cs(t,e),ke(!0,us[t.type],ds[t.type]),ls(t)]),cs=(t,e)=>{const s=xe(t.samples),i=_(s?s.timestamp+s.duration:0,t.timescale),r=!J(e)||!J(i),n=r?j:l;return C("mdhd",+r,0,[n(e),n(e),l(t.timescale),n(i),w(it(t.track.metadata.languageCode??Ct)),w(0)])},us={video:"vide",audio:"soun",subtitle:"text"},ds={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ke=(t,e,s,i="\0\0\0\0")=>C("hdlr",0,0,[t?k("mhlr"):l(0),k(e),k(i),l(0),l(0),k(s,!0)]),ls=t=>T("minf",void 0,[ps[t.type](),gs(),bs(t)]),hs=()=>C("vmhd",0,1,[w(0),w(0),w(0),w(0)]),fs=()=>C("smhd",0,0,[w(0),w(0)]),ms=()=>C("nmhd",0,0),ps={video:hs,audio:fs,subtitle:ms},gs=()=>T("dinf",void 0,[ws()]),ws=()=>C("dref",0,0,[l(1)],[Ts()]),Ts=()=>C("url ",0,1),bs=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(s=>s.sampleCompositionTimeOffset!==0);return T("stbl",void 0,[ys(t),Bs(t),e?Ws(t):null,e?Vs(t):null,Is(t),Rs(t),Us(t),Fs(t)])},ys=t=>{let e;if(t.type==="video")e=Cs(ii(t.track.source._codec,t.info.decoderConfig.codec),t);else if(t.type==="audio"){const s=st(t.track.source._codec,t.muxer.isQuickTime);f(s),e=xs(s,t)}else t.type==="subtitle"&&(e=Os(oi[t.track.source._codec],t));return f(e),C("stsd",0,0,[l(1)],[e])},Cs=(t,e)=>T(t,[Array(6).fill(0),w(1),w(0),w(0),Array(12).fill(0),w(e.info.width),w(e.info.height),l(4718592),l(4718592),l(0),w(1),Array(32).fill(0),w(24),Ke(65535)],[ri[e.track.source._codec](e),Et(e.info.decoderConfig.colorSpace)?Es(e):null]),Es=t=>T("colr",[k("nclx"),w($e[t.info.decoderConfig.colorSpace.primaries]),w(Le[t.info.decoderConfig.colorSpace.transfer]),w(He[t.info.decoderConfig.colorSpace.matrix]),v((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),vs=t=>t.info.decoderConfig&&T("avcC",[...te(t.info.decoderConfig.description)]),Ss=t=>t.info.decoderConfig&&T("hvcC",[...te(t.info.decoderConfig.description)]),Ie=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,s=e.codec.split("."),i=Number(s[1]),r=Number(s[2]),n=Number(s[3]),o=s[4]?Number(s[4]):1,a=s[8]?Number(s[8]):Number(e.colorSpace?.fullRange??0),u=(n<<4)+(o<<1)+a,c=s[5]?Number(s[5]):e.colorSpace?.primaries?$e[e.colorSpace.primaries]:2,d=s[6]?Number(s[6]):e.colorSpace?.transfer?Le[e.colorSpace.transfer]:2,p=s[7]?Number(s[7]):e.colorSpace?.matrix?He[e.colorSpace.matrix]:2;return C("vpcC",1,0,[v(i),v(r),v(u),v(c),v(d),v(p),w(0)])},_s=t=>T("av1C",vt(t.info.decoderConfig.codec)),xs=(t,e)=>{let s=0,i,r=16;if(ee.includes(e.track.source._codec)){const n=e.track.source._codec,{sampleSize:o}=D(n);r=8*o,r>16&&(s=1)}return s===0?i=[Array(6).fill(0),w(1),w(s),w(0),l(0),w(e.info.numberOfChannels),w(r),w(0),w(0),w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0)]:i=[Array(6).fill(0),w(1),w(s),w(0),l(0),w(e.info.numberOfChannels),w(Math.min(r,16)),w(0),w(0),w(e.info.sampleRate<2**16?e.info.sampleRate:0),w(0),l(1),l(r/8),l(e.info.numberOfChannels*r/8),l(2)],T(t,i,[ni(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},pe=t=>{let e;switch(t.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source._codec}`)}let s=[...v(e),...v(21),...Xe(0),...l(0),...l(0)];if(t.info.decoderConfig.description){const i=te(t.info.decoderConfig.description);s=[...s,...v(5),...me(i.byteLength),...i]}return s=[...w(1),...v(0),...v(4),...me(s.length),...s,...v(6),...v(1),...v(2)],s=[...v(3),...me(s.length),...s],C("esds",0,0,s)},V=t=>T("wave",void 0,[ks(t),As(t),T("\0\0\0\0")]),ks=t=>T("frma",[k(st(t.track.source._codec,t.muxer.isQuickTime))]),As=t=>{const{littleEndian:e}=D(t.track.source._codec);return T("enda",[w(+e)])},Ps=t=>{let e=t.info.numberOfChannels,s=3840,i=t.info.sampleRate,r=0,n=0,o=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){f(a.byteLength>=18);const u=te(a),c=St(u);e=c.outputChannelCount,s=c.preSkip,i=c.inputSampleRate,r=c.outputGain,n=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return T("dOps",[v(0),v(e),w(s),l(i),Ke(r),v(n),...o])},Ms=t=>{const e=t.info.decoderConfig?.description;f(e);const s=te(e);return C("dfLa",0,0,[...s.subarray(4)])},B=t=>{const{littleEndian:e,sampleSize:s}=D(t.track.source._codec),i=+e;return C("pcmC",0,0,[v(i),v(8*s)])},Os=(t,e)=>T(t,[Array(6).fill(0),w(1)],[ai[e.track.source._codec](e)]),zs=t=>T("vttC",[...I.encode(t.info.config.description)]),Bs=t=>C("stts",0,0,[l(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[l(e.sampleCount),l(e.sampleDelta)])]),Fs=t=>{if(t.samples.every(s=>s.type==="key"))return null;const e=[...t.samples.entries()].filter(([,s])=>s.type==="key");return C("stss",0,0,[l(e.length),e.map(([s])=>l(s+1))])},Is=t=>C("stsc",0,0,[l(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[l(e.firstChunk),l(e.samplesPerChunk),l(1)])]),Rs=t=>{if(t.type==="audio"&&t.info.requiresPcmTransformation){const{sampleSize:e}=D(t.track.source._codec);return C("stsz",0,0,[l(e*t.info.numberOfChannels),l(t.samples.reduce((s,i)=>s+_(i.duration,t.timescale),0))])}return C("stsz",0,0,[l(0),l(t.samples.length),t.samples.map(e=>l(e.size))])},Us=t=>t.finalizedChunks.length>0&&Q(t.finalizedChunks).offset>=2**32?C("co64",0,0,[l(t.finalizedChunks.length),t.finalizedChunks.map(e=>j(e.offset))]):C("stco",0,0,[l(t.finalizedChunks.length),t.finalizedChunks.map(e=>l(e.offset))]),Ws=t=>C("ctts",1,0,[l(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[l(e.sampleCount),N(e.sampleCompositionTimeOffset)])]),Vs=t=>{let e=1/0,s=-1/0,i=1/0,r=-1/0;f(t.compositionTimeOffsetTable.length>0),f(t.samples.length>0);for(let o=0;o<t.compositionTimeOffsetTable.length;o++){const a=t.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),s=Math.max(s,a.sampleCompositionTimeOffset)}for(let o=0;o<t.samples.length;o++){const a=t.samples[o];i=Math.min(i,_(a.timestamp,t.timescale)),r=Math.max(r,_(a.timestamp+a.duration,t.timescale))}const n=Math.max(-e,0);return r>=2**31?null:C("cslg",0,0,[N(n),N(e),N(s),N(i),N(r)])},Ns=t=>T("mvex",void 0,t.map($s)),$s=t=>C("trex",0,0,[l(t.track.id),l(1),l(0),l(0),l(0)]),Re=(t,e)=>T("moof",void 0,[Ls(t),...e.map(Hs)]),Ls=t=>C("mfhd",0,0,[l(t)]),et=t=>{let e=0,s=0;const i=0,r=0,n=t.type==="delta";return s|=+n,n?e|=1:e|=2,e<<24|s<<16|i<<8|r},Hs=t=>T("traf",void 0,[Qs(t),qs(t),js(t)]),Qs=t=>{f(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const s=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:s.timescaleUnitsToNextSample,size:s.size,flags:et(s)};return C("tfhd",0,e,[l(t.track.id),l(i.duration),l(i.size),l(i.flags)])},qs=t=>(f(t.currentChunk),C("tfdt",1,0,[j(_(t.currentChunk.startTimestamp,t.timescale))])),js=t=>{f(t.currentChunk);const e=t.currentChunk.samples.map(y=>y.timescaleUnitsToNextSample),s=t.currentChunk.samples.map(y=>y.size),i=t.currentChunk.samples.map(et),r=t.currentChunk.samples.map(y=>_(y.timestamp-y.decodeTimestamp,t.timescale)),n=new Set(e),o=new Set(s),a=new Set(i),u=new Set(r),c=a.size===2&&i[0]!==i[1],d=n.size>1,p=o.size>1,h=!c&&a.size>1,m=u.size>1||[...u].some(y=>y!==0);let g=0;return g|=1,g|=4*+c,g|=256*+d,g|=512*+p,g|=1024*+h,g|=2048*+m,C("trun",1,g,[l(t.currentChunk.samples.length),l(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?l(i[0]):[],t.currentChunk.samples.map((y,E)=>[d?l(e[E]):[],p?l(s[E]):[],h?l(i[E]):[],m?N(r[E]):[]])])},Gs=t=>T("mfra",void 0,[...t.map(Ks),Xs()]),Ks=(t,e)=>C("tfra",1,0,[l(t.track.id),l(63),l(t.finalizedChunks.length),t.finalizedChunks.map(i=>[j(_(i.samples[0].timestamp,t.timescale)),j(i.moofOffset),l(e+1),l(1),l(1)])]),Xs=()=>C("mfro",0,0,[l(0)]),Ys=()=>T("vtte"),Zs=(t,e,s,i,r)=>T("vttc",void 0,[r!==null?T("vsid",[N(r)]):null,s!==null?T("iden",[...I.encode(s)]):null,e!==null?T("ctim",[...I.encode(ts(e))]):null,i!==null?T("sttg",[...I.encode(i)]):null,T("payl",[...I.encode(t)])]),Js=t=>T("vtta",[...I.encode(t)]),Ds=t=>{const e=[],s=t.format._options.metadataFormat??"auto",i=t.output._metadataTags;if(s==="mdir"||s==="auto"&&!t.isQuickTime){const r=ti(i);r&&e.push(r)}else if(s==="mdta"){const r=si(i);r&&e.push(r)}else(s==="udta"||s==="auto"&&t.isQuickTime)&&ei(e,t.output._metadataTags);return e.length===0?null:T("udta",void 0,e)},ei=(t,e)=>{for(const{key:s,value:i}of Ne(e))switch(s){case"title":t.push(F("©nam",i));break;case"description":t.push(F("©des",i));break;case"artist":t.push(F("©ART",i));break;case"album":t.push(F("©alb",i));break;case"albumArtist":t.push(F("albr",i));break;case"genre":t.push(F("©gen",i));break;case"date":t.push(F("©day",i.toISOString().slice(0,10)));break;case"comment":t.push(F("©cmt",i));break;case"lyrics":t.push(F("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:_e(s)}if(e.raw)for(const s in e.raw){const i=e.raw[s];i==null||s.length!==4||t.some(r=>r.type===s)||(typeof i=="string"?t.push(F(s,i)):i instanceof Uint8Array&&t.push(T(s,Array.from(i))))}},F=(t,e)=>{const s=I.encode(e);return T(t,[w(s.length),w(it("und")),Array.from(s)])},Ue={"image/jpeg":13,"image/png":14,"image/bmp":27},tt=(t,e)=>{const s=[];for(const{key:i,value:r}of Ne(t))switch(i){case"title":s.push({key:e?"title":"©nam",value:M(r)});break;case"description":s.push({key:e?"description":"©des",value:M(r)});break;case"artist":s.push({key:e?"artist":"©ART",value:M(r)});break;case"album":s.push({key:e?"album":"©alb",value:M(r)});break;case"albumArtist":s.push({key:e?"album_artist":"aART",value:M(r)});break;case"comment":s.push({key:e?"comment":"©cmt",value:M(r)});break;case"genre":s.push({key:e?"genre":"©gen",value:M(r)});break;case"lyrics":s.push({key:e?"lyrics":"©lyr",value:M(r)});break;case"date":s.push({key:e?"date":"©day",value:M(r.toISOString().slice(0,10))});break;case"images":for(const n of r)n.kind==="coverFront"&&s.push({key:"covr",value:T("data",[l(Ue[n.mimeType]??0),l(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=t.tracksTotal!==void 0?`${r}/${t.tracksTotal}`:r.toString();s.push({key:"track",value:M(n)})}else s.push({key:"trkn",value:T("data",[l(0),l(0),w(0),w(r),w(t.tracksTotal??0),w(0)])});break;case"discNumber":e||s.push({key:"disc",value:T("data",[l(0),l(0),w(0),w(r),w(t.discsTotal??0),w(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:_e(i)}if(t.raw)for(const i in t.raw){const r=t.raw[i];r==null||!e&&i.length!==4||s.some(n=>n.key===i)||(typeof r=="string"?s.push({key:i,value:M(r)}):r instanceof Uint8Array?s.push({key:i,value:T("data",[l(0),l(0),Array.from(r)])}):r instanceof yt&&s.push({key:i,value:T("data",[l(Ue[r.mimeType]??0),l(0),Array.from(r.data)])}))}return s},ti=t=>{const e=tt(t,!1);return e.length===0?null:C("meta",0,0,void 0,[ke(!1,"mdir","","appl"),T("ilst",void 0,e.map(s=>T(s.key,void 0,[s.value])))])},si=t=>{const e=tt(t,!0);return e.length===0?null:T("meta",void 0,[ke(!1,"mdta",""),C("keys",0,0,[l(e.length)],e.map(s=>T("mdta",[...I.encode(s.key)]))),T("ilst",void 0,e.map((s,i)=>{const r=String.fromCharCode(...l(i+1));return T(r,void 0,[s.value])}))])},M=t=>T("data",[l(1),l(0),...I.encode(t)]),ii=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},ri={avc:vs,hevc:Ss,vp8:Ie,vp9:Ie,av1:_s},st=(t,e)=>{switch(t){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"}if(e)switch(t){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(t){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"}},ni=(t,e)=>{switch(t){case"aac":return pe;case"mp3":return pe;case"opus":return Ps;case"vorbis":return pe;case"flac":return Ms}if(e)switch(t){case"pcm-s24":return V;case"pcm-s24be":return V;case"pcm-s32":return V;case"pcm-s32be":return V;case"pcm-f32":return V;case"pcm-f32be":return V;case"pcm-f64":return V;case"pcm-f64be":return V}else switch(t){case"pcm-s16":return B;case"pcm-s16be":return B;case"pcm-s24":return B;case"pcm-s24be":return B;case"pcm-s32":return B;case"pcm-s32be":return B;case"pcm-f32":return B;case"pcm-f32be":return B;case"pcm-f64":return B;case"pcm-f64be":return B}return null},oi={webvtt:"wvtt"},ai={webvtt:zs},it=t=>{f(t.length===3);let e=0;for(let s=0;s<3;s++)e<<=5,e+=t.charCodeAt(s)-96;return e};class ci{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let s=this.getPos();if(s<this.trackedStart){if(s+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-s),s=0}const i=s+e.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const n=new Uint8Array(r);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,s-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,s+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const s={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,s}}const ge=2**16,we=2**32;class rt extends ci{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(ge,{maxByteLength:we})}catch{this.buffer=new ArrayBuffer(ge),this.supportsResize=!1}else this.buffer=new ArrayBuffer(ge);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let s=this.buffer.byteLength;for(;s<e;)s*=2;if(s!==this.buffer.byteLength){if(s>we)throw new Error(`ArrayBuffer exceeded maximum size of ${we} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(s);else{const i=new ArrayBuffer(s),r=new Uint8Array(i);r.set(this.bytes,0),this.buffer=i,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,s){return this.bytes.slice(e,s)}}class nt{constructor(){this._output=null,this.onwrite=null}}class ot extends nt{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new rt(this)}}const Ee=1e3,ui=2082844800,di=t=>{const e={},s=t.track;return s.metadata.name!==void 0&&(e.name=s.metadata.name),e},_=(t,e,s=!0)=>{const i=t*e;return s?Math.round(i):i};class li extends es{constructor(e,s){super(e),this.auxTarget=new ot,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Fe(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_t(),this.creationTime=Math.floor(Date.now()/1e3)+ui,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=s,this.writer=e._writer,this.boxWriter=new Fe(this.writer),this.isQuickTime=s instanceof dt;const i=this.writer instanceof rt?"in-memory":!1;this.fastStart=s._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=s._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),s=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(ss({isQuickTime:this.isQuickTime,holdsAvc:s,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:r}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,r)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ae(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(s=>s.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(s=>s.type==="video"||s.type==="audio"?s.info.decoderConfig.codec:{webvtt:"wvtt"}[s.track.source._codec]);return xt({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(s=>s.type==="video"),hasAudio:this.trackDatas.some(s=>s.type==="audio"),codecStrings:e})}getVideoTrackData(e,s,i){const r=this.trackDatas.find(c=>c.track===e);if(r)return r;kt(i),f(i),f(i.decoderConfig);const n={...i.decoderConfig};f(n.codedWidth!==void 0),f(n.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!n.description){const c=At(s.data);if(!c)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=Pt(c),o=!0}else if(e.source._codec==="hevc"&&!n.description){const c=Mt(s.data);if(!c)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Ot(c),o=!0}const a=zt(1/(e.metadata.frameRate??57600),1e6).denominator,u={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:o},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,s){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Bt(s),f(s),f(s.decoderConfig);const r={muxer:this,track:e,type:"audio",info:{numberOfChannels:s.decoderConfig.numberOfChannels,sampleRate:s.decoderConfig.sampleRate,decoderConfig:s.decoderConfig,requiresPcmTransformation:!this.isFragmented&&ee.includes(e.source._codec)},timescale:s.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}getSubtitleTrackData(e,s){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Ft(s),f(s),f(s.config);const r={muxer:this,track:e,type:"subtitle",info:{config:s.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,s,i){const r=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,s,i);let o=s.data;if(n.info.requiresAnnexBTransformation){const c=It(o);if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Rt(c,4)}const a=this.validateAndNormalizeTimestamp(n.track,s.timestamp,s.type==="key"),u=this.createSampleForTrack(n,o,a,s.duration,s.type);await this.registerSample(n,u)}finally{r()}}async addEncodedAudioPacket(e,s,i){const r=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i),o=this.validateAndNormalizeTimestamp(n.track,s.timestamp,s.type==="key"),a=this.createSampleForTrack(n,s.data,o,s.duration,s.type);n.info.requiresPcmTransformation&&await this.maybePadWithSilence(n,o),await this.registerSample(n,a)}finally{r()}}async maybePadWithSilence(e,s){const i=Q(e.samples),r=i?i.timestamp+i.duration:0,n=s-r,o=_(n,e.timescale);if(o>0){const{sampleSize:a,silentValue:u}=D(e.info.decoderConfig.codec),c=o*e.info.numberOfChannels,d=new Uint8Array(a*c).fill(u),p=this.createSampleForTrack(e,new Uint8Array(d.buffer),r,n,"key");await this.registerSample(e,p)}}async addSubtitleCue(e,s,i){const r=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,s.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(s),await this.processWebVTTCues(n,s.timestamp))}finally{r()}}async processWebVTTCues(e,s){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)f(c.timestamp<=s),f(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const r=[...i].sort((c,d)=>c-d),n=r[0],o=r[1]??n;if(s<o)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const c=Ys();this.auxBoxWriter.writeBox(c);const d=this.auxWriter.getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,p),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const d=e.cueQueue[c];if(d.timestamp>=o)break;Be.lastIndex=0;const p=Be.test(d.text),h=d.timestamp+d.duration;let m=e.cueToSourceId.get(d);if(m===void 0&&o<h&&(m=e.nextSourceId++,e.cueToSourceId.set(d,m)),d.notes){const y=Js(d.notes);this.auxBoxWriter.writeBox(y)}const g=Zs(d.text,p?n:null,d.identifier??null,d.settings??null,m??null);this.auxBoxWriter.writeBox(g),h===o&&e.cueQueue.splice(c--,1)}const a=this.auxWriter.getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,a,n,o-n,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=o}}createSampleForTrack(e,s,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:s,size:s.byteLength,type:n,timescaleUnitsToNextSample:_(r,e.timescale)}}processTimestamps(e,s){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let r=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const o=e.timestampProcessingQueue[n],a=_(o.duration,e.timescale);r+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:r,sampleDelta:1});else{const n=Q(e.timeToSampleTable);n.sampleCount+=r}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(r=>r.timestamp).sort((r,n)=>r-n);for(let r=0;r<e.timestampProcessingQueue.length;r++){const n=e.timestampProcessingQueue[r];n.decodeTimestamp=i[r],!this.isFragmented&&e.lastTimescaleUnits===null&&(n.decodeTimestamp=0);const o=_(n.timestamp-n.decodeTimestamp,e.timescale),a=_(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){f(e.lastSample);const u=_(n.decodeTimestamp,e.timescale,!1),c=Math.round(u-e.lastTimescaleUnits);if(f(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let d=Q(e.timeToSampleTable);if(f(d),d.sampleCount===1){d.sampleDelta=c;const h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===c&&(h.sampleCount++,e.timeToSampleTable.pop(),d=h)}else d.sampleDelta!==c&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:c}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const p=Q(e.compositionTimeOffsetTable);f(p),p.sampleCompositionTimeOffset===o?p.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=_(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,f(e.lastSample),f(e.lastTimescaleUnits!==null),s!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){f(s.type==="key");const r=_(s.timestamp,e.timescale,!1),n=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,s){s.type==="key"&&this.processTimestamps(e,s),e.timestampProcessingQueue.push(s),this.isFragmented?(e.sampleQueue.push(s),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,s):await this.addSampleToTrack(e,s)}async addSampleToTrack(e,s){if(!this.isFragmented&&(e.samples.push(s),this.fastStart==="reserve")){const r=e.track.metadata.maximumPacketCount;if(f(r!==void 0),e.samples.length>r)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${r}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,s.timestamp);const r=s.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(o=>{if(e===o)return s.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.track.source._closed});r>=this.minimumFragmentDuration&&n&&s.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:s.timestamp,samples:[],offset:null,moofOffset:null}),f(e.currentChunk),e.currentChunk.samples.push(s),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,s.timestamp))}async finalizeCurrentChunk(e){if(f(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let s=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(s=e.currentChunk.samples.reduce((i,r)=>i+_(r.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Q(e.compactlyCodedChunkTable).samplesPerChunk!==s)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:s}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)f(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(f(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let s=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.track.source._closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(s=n,i=n.sampleQueue[0].timestamp)}if(!s)break;const r=s.sampleQueue.shift();await this.addSampleToTrack(s,r)}}async finalizeFragment(e=!0){f(this.isFragmented);const s=this.nextFragmentNumber++;if(s===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const m=ie(this);if(this.boxWriter.writeBox(m),this.format._options.onMoov){const{data:g,start:y}=this.writer.stopTrackingWrites();this.format._options.onMoov(g,y)}}const i=this.trackDatas.filter(m=>m.currentChunk),r=Re(s,i),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let a=o+le,u=1/0;for(const m of i){m.currentChunk.offset=a,m.currentChunk.moofOffset=n;for(const g of m.currentChunk.samples)a+=g.size;u=Math.min(u,m.currentChunk.startTimestamp)}const c=a-o,d=c>=2**32;if(d)for(const m of i)m.currentChunk.offset+=ze-le;this.format._options.onMoof&&this.writer.startTrackingWrites();const p=Re(s,i);if(this.boxWriter.writeBox(p),this.format._options.onMoof){const{data:m,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(m,g,u)}f(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=ae(d);h.size=c,this.boxWriter.writeBox(h),this.writer.seek(o+(d?ze:le));for(const m of i)for(const g of m.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){const{data:m,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(m,g)}for(const m of i)m.finalizedChunks.push(m.currentChunk),this.finalizedChunks.push(m.currentChunk),m.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,s){if(this.allTracksAreKnown()){if(!this.mdat){const i=ie(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;f(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=ae(!0),this.boxWriter.writeBox(this.mdat);for(const o of this.trackDatas){for(const a of o.sampleQueue)await this.addSampleToTrack(o,a);o.sampleQueue.length=0}}await this.addSampleToTrack(e,s)}else e.sampleQueue.push(s)}computeSampleTableSizeUpperBound(){f(this.fastStart==="reserve");let e=0;for(const s of this.trackDatas){const i=s.track.metadata.maximumPacketCount;f(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const s=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(r=>r.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),s()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const s of this.trackDatas)s.type==="subtitle"&&s.track.source._codec==="webvtt"&&await this.processWebVTTCues(s,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const s of this.trackDatas)this.processTimestamps(s);await this.finalizeFragment(!1)}else for(const s of this.trackDatas)this.processTimestamps(s),await this.finalizeCurrentChunk(s);if(this.fastStart==="in-memory"){this.mdat=ae(!1);let s;for(let r=0;r<2;r++){const n=ie(this),o=this.boxWriter.measureBox(n);s=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+s;for(const u of this.finalizedChunks){u.offset=a;for(const{data:c}of u.samples)f(c),a+=c.byteLength,s+=c.byteLength}if(a<2**32)break;s>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=ie(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(r,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=s,this.boxWriter.writeBox(this.mdat);for(const r of this.finalizedChunks)for(const n of r.samples)f(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(r,n)}}else if(this.isFragmented){const s=this.writer.getPos(),i=Gs(this.trackDatas);this.boxWriter.writeBox(i);const r=this.writer.getPos()-s;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{f(this.mdat);const s=this.boxWriter.offsets.get(this.mdat);f(s!==void 0);const i=this.writer.getPos()-s;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,o)}const r=ie(this);if(this.fastStart==="reserve"){f(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(is(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,o)}}e()}}class at{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>$.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>q.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ce.includes(e))}_codecUnsupportedHint(e){return""}}class ct extends at{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new 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 new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new li(e,this)}}class ut extends ct{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...$,...Ut,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ce]}_codecUnsupportedHint(e){return new dt().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class dt extends ct{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...$,...q]}_codecUnsupportedHint(e){return new ut().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const hi=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!$.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${$.join(", ")}.`);if(!(t.bitrate instanceof K)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(t.keyFrameInterval!==void 0&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(t.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");lt(t.codec,t)},lt=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Qe(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},ve=t=>{const e=t.bitrate instanceof K?t.bitrate._toVideoBitrate(t.codec,t.width,t.height):t.bitrate;return{codec:t.fullCodecString??Vt(t.codec,t.width,t.height,e),width:t.width,height:t.height,bitrate:e,bitrateMode:t.bitrateMode,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...Wt(t.codec)}},fi=t=>{if(!t||typeof t!="object")throw new TypeError("Encoding config must be an object.");if(!q.includes(t.codec))throw new TypeError(`Invalid audio codec '${t.codec}'. Must be one of: ${q.join(", ")}.`);if(t.bitrate===void 0&&(!ee.includes(t.codec)||t.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(t.bitrate!==void 0&&!(t.bitrate instanceof K)&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(t.onEncodedPacket!==void 0&&typeof t.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(t.onEncoderConfig!==void 0&&typeof t.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ht(t.codec,t)},ht=(t,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Qe(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`)},Se=t=>{const e=t.bitrate instanceof K?t.bitrate._toAudioBitrate(t.codec):t.bitrate;return{codec:t.fullCodecString??$t(t.codec,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:e,bitrateMode:t.bitrateMode,...Nt(t.codec)}};class K{constructor(e){this._factor=e}_toVideoBitrate(e,s,i){const r=s*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},o=1920*1080,a=3e6,u=Math.pow(r/o,.95),p=a*u*n[e]*this._factor;return Math.ceil(p/1e3)*1e3}_toAudioBitrate(e){if(ee.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let r=i*this._factor;return e==="aac"?r=[96e3,128e3,16e4,192e3].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o):e==="opus"||e==="vorbis"?r=Math.max(6e3,r):e==="mp3"&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o)),Math.round(r/1e3)*1e3}}const ft=new K(2),mi=async(t,e={})=>{const{width:s=1280,height:i=720,bitrate:r=1e6,...n}=e;if(!$.includes(t))return!1;if(!Number.isInteger(s)||s<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer or a quality.");lt(t,n);let o=null;return be.length>0&&(o??=ve({codec:t,width:s,height:i,bitrate:r,framerate:void 0,...n}),be.some(c=>c.supports(t,o)))?!0:typeof VideoEncoder>"u"||(s%2===1||i%2===1)&&(t==="avc"||t==="hevc")||(o??=ve({codec:t,width:s,height:i,bitrate:r,framerate:void 0,...n,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:ye()?new Promise(async c=>{try{const d=new VideoEncoder({output:()=>{},error:()=>c(!1)});d.configure(o);const p=new Uint8Array(s*i*4),h=new VideoFrame(p,{format:"RGBA",codedWidth:s,codedHeight:i,timestamp:0});d.encode(h),h.close(),await d.flush(),c(!0)}catch{c(!1)}}):!0},pi=async(t,e={})=>{const{numberOfChannels:s=2,sampleRate:i=48e3,bitrate:r=128e3,...n}=e;if(!q.includes(t))return!1;if(!Number.isInteger(s)||s<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(r instanceof K)&&(!Number.isInteger(r)||r<=0))throw new TypeError("bitrate must be a positive integer.");ht(t,n);let o=null;return Ce.length>0&&(o??=Se({codec:t,numberOfChannels:s,sampleRate:i,bitrate:r,...n}),Ce.some(u=>u.supports(t,o)))||ee.includes(t)?!0:typeof AudioEncoder>"u"?!1:(o??=Se({codec:t,numberOfChannels:s,sampleRate:i,bitrate:r,...n}),(await AudioEncoder.isConfigSupported(o)).supported===!0)},gi=async(t,e)=>{for(const s of t)if(await mi(s,e))return s;return null},wi=async(t,e)=>{for(const s of t)if(await pi(s,e))return s;return null};class Ae{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new 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?this._closingPromise:this._flushAndClose(e)}}class mt extends Ae{constructor(e){if(super(),this._connectedTrack=null,!$.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${$.join(", ")}.`);this._codec=e}}class Ti{constructor(e,s){this.source=e,this.encodingConfig=s,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Ge,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,s,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const a=this.encodingConfig.sizeChangeBehavior??"deny";if(a!=="passThrough"){if(a==="deny")throw new 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 'strict' in the encoding options.`);{let u=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),u=!0);const c=this.resizeCanvas.getContext("2d",{alpha:ye()});f(c),u||(ye()?(c.fillStyle="black",c.fillRect(0,0,this.codedWidth,this.codedHeight)):c.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(c,{fit:a}),s&&e.close(),e=new qe(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),s=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),f(this.encoderInitialized);const r=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/r),o={...i,keyFrame:i?.keyFrame||r===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;const a=e.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(a,o)).then(()=>this.customEncoderQueueSize--).catch(c=>this.error??=c).finally(()=>{a.close()});this.customEncoderQueueSize>=4&&await u}else{f(this.encoder);const a=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(a,o),a.close();else if(!!a.format&&!a.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close();else{const c=a.displayWidth,d=a.displayHeight;if(!this.splitter)try{this.splitter=new bi(c,d)}catch(p){console.error("Due to an error, only color data will be encoded.",p),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close()}if(this.splitter){const p=this.splitter.extractColor(a),h=this.splitter.extractAlpha(a);this.alphaFrameQueue.push(h),this.encoder.encode(p,o),p.close(),a.close()}}s&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(u=>this.encoder.addEventListener("dequeue",u,{once:!0}))}await this.muxer.mutex.currentPromise}finally{s&&e.close()}}ensureEncoder(e){const s=new Error;this.ensureEncoderPromise=(async()=>{const i=ve({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const r=be.find(n=>n.supports(this.encodingConfig.codec,i));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(n,o)=>{if(!(n instanceof re))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,o),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,o).catch(a=>{this.error??=a,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.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(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const a=[],u=[];let c=0,d=0;const p=(h,m,g)=>{const y={};if(m){const x=new Uint8Array(m.byteLength);m.copyTo(x),y.alpha=x}const E=re.fromEncodedChunk(h,y);this.encodingConfig.onEncodedPacket?.(E,g),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,E,g).catch(x=>{this.error??=x,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(h,m)=>{if(!this.alphaEncoder){p(h,null,m);return}const g=this.alphaFrameQueue.shift();f(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:h.type==="key"}),d++,g.close(),a.push({chunk:h,meta:m})):d===0?p(h,null,m):(u.push(c+d),a.push({chunk:h,meta:m}))},error:h=>{h.stack=s.stack,this.error??=h}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(h,m)=>{d--;const g=a.shift();for(f(g!==void 0),p(g.chunk,h,g.meta),c++;u.length>0&&u[0]===c;){u.shift();const y=a.shift();f(y!==void 0),p(y.chunk,null,y.meta)}},error:h=>{h.stack=s.stack,this.error??=h}}),this.alphaEncoder.configure(i))}f(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),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(s=>s?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class bi{constructor(e,s){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,s):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=s);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2
2
  in vec2 a_position;
3
3
  in vec2 a_texCoord;
4
4
  out vec2 v_texCoord;