mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-09-27 19:03:46 +02:00
10 lines
61 KiB
JavaScript
10 lines
61 KiB
JavaScript
function c(r){if(!r)throw new Error("Assertion failed.")}var R=r=>r&&r[r.length-1],V=r=>r>=0&&r<2**32,M=(r,i,e)=>{let t=0;for(let s=i;s<e;s++){let o=Math.floor(s/8),a=r[o],n=7-(s&7),u=(a&1<<n)>>n;t<<=1,t|=u}return t},He=(r,i,e,t)=>{for(let s=i;s<e;s++){let o=Math.floor(s/8),a=r[o],n=7-(s&7);a&=~(1<<n),a|=(t&1<<e-s-1)>>e-s-1<<n,r[o]=a}},I=r=>r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength),x=new TextEncoder,F={bt709:1,bt470bg:5,smpte170m:6},B={bt709:1,smpte170m:6,"iec61966-2-1":13},N={rgb:0,bt709:1,bt470bg:5,smpte170m:6},ae=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,ge=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView),W=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let i,e=new Promise(s=>{i=s}),t=this.currentPromise;return this.currentPromise=e,await t,i}};var X=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,ut=/^WEBVTT(.|\n)*?\n{2}/,H=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ne=class{constructor(i){this.preambleText=null;this.preambleEmitted=!1;this.options=i}parse(i){i=i.replaceAll(`\r
|
|
`,`
|
|
`).replaceAll("\r",`
|
|
`),X.lastIndex=0;let e;if(!this.preambleText){if(!ut.test(i)){let s=new Error("WebVTT preamble incorrect.");throw this.options.error(s),s}e=X.exec(i);let t=i.slice(0,e?.index??i.length).trimEnd();if(!t){let s=new Error("No WebVTT preamble provided.");throw this.options.error(s),s}this.preambleText=t,e&&(i=i.slice(e.index),X.lastIndex=0)}for(;e=X.exec(i);){let t=i.slice(0,e.index),s=e[1],o=e.index+e[0].length,a=i.indexOf(`
|
|
`,o)+1,n=i.slice(o,a).trim(),u=i.indexOf(`
|
|
|
|
`,o);u===-1&&(u=i.length);let d=ue(e[2]),f=ue(e[3])-d,w=i.slice(a,u).trim();i=i.slice(u).trimStart(),X.lastIndex=0;let _={timestamp:d/1e3,duration:f/1e3,text:w,identifier:s,settings:n,notes:t},g={};this.preambleEmitted||(g.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(_,g)}}},lt=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ue=r=>{let i=lt.exec(r);if(!i)throw new Error("Expected match.");return 60*60*1e3*Number(i[1]||"0")+60*1e3*Number(i[2])+1e3*Number(i[3])+Number(i[4])},le=r=>{let i=Math.floor(r/36e5),e=Math.floor(r%(60*60*1e3)/(60*1e3)),t=Math.floor(r%(60*1e3)/1e3),s=r%1e3;return i.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};var G=class{constructor(i){this.writer=i;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(i){this.helperView.setUint32(0,i,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(i){this.helperView.setUint32(0,Math.floor(i/2**32),!1),this.helperView.setUint32(4,i,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(i){for(let e=0;e<i.length;e++)this.helperView.setUint8(e%8,i.charCodeAt(e)),e%8===7&&this.writer.write(this.helper);i.length%8!==0&&this.writer.write(this.helper.subarray(0,i.length%8))}writeBox(i){if(this.offsets.set(i,this.writer.getPos()),i.contents&&!i.children)this.writeBoxHeader(i,i.size??i.contents.byteLength+8),this.writer.write(i.contents);else{let e=this.writer.getPos();if(this.writeBoxHeader(i,0),i.contents&&this.writer.write(i.contents),i.children)for(let o of i.children)o&&this.writeBox(o);let t=this.writer.getPos(),s=i.size??t-e;this.writer.seek(e),this.writeBoxHeader(i,s),this.writer.seek(t)}}writeBoxHeader(i,e){this.writeU32(i.largeSize?1:e),this.writeAscii(i.type),i.largeSize&&this.writeU64(e)}measureBoxHeader(i){return 8+(i.largeSize?8:0)}patchBox(i){let e=this.offsets.get(i);c(e!==void 0);let t=this.writer.getPos();this.writer.seek(e),this.writeBox(i),this.writer.seek(t)}measureBox(i){if(i.contents&&!i.children)return this.measureBoxHeader(i)+i.contents.byteLength;{let e=this.measureBoxHeader(i);if(i.contents&&(e+=i.contents.byteLength),i.children)for(let t of i.children)t&&(e+=this.measureBox(t));return e}}},p=new Uint8Array(8),A=new DataView(p.buffer),C=r=>[(r%256+256)%256],h=r=>(A.setUint16(0,r,!1),[p[0],p[1]]),ct=r=>(A.setInt16(0,r,!1),[p[0],p[1]]),$e=r=>(A.setUint32(0,r,!1),[p[1],p[2],p[3]]),l=r=>(A.setUint32(0,r,!1),[p[0],p[1],p[2],p[3]]),je=r=>(A.setInt32(0,r,!1),[p[0],p[1],p[2],p[3]]),z=r=>(A.setUint32(0,Math.floor(r/2**32),!1),A.setUint32(4,r,!1),[p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]]),xe=r=>(A.setInt16(0,2**8*r,!1),[p[0],p[1]]),v=r=>(A.setInt32(0,2**16*r,!1),[p[0],p[1],p[2],p[3]]),ke=r=>(A.setInt32(0,2**30*r,!1),[p[0],p[1],p[2],p[3]]),ye=(r,i)=>{let e=[],t=r;do{let s=t&127;t>>=7,e.length>0&&(s|=128),e.push(s),i!==void 0&&i--}while(t>0||i);return e.reverse()},y=(r,i=!1)=>{let e=Array(r.length).fill(null).map((t,s)=>r.charCodeAt(s));return i&&e.push(0),e},Se=r=>{let i=null;for(let e of r)(!i||e.timestamp>i.timestamp)&&(i=e);return i},qe=r=>{let i=r*(Math.PI/180),e=Math.cos(i),t=Math.sin(i);return[e,t,0,-t,e,0,0,0,1]},Ke=qe(0),Le=r=>[v(r[0]),v(r[1]),ke(r[2]),v(r[3]),v(r[4]),ke(r[5]),v(r[6]),v(r[7]),ke(r[8])],b=(r,i,e)=>({type:r,contents:i&&new Uint8Array(i.flat(10)),children:e}),T=(r,i,e,t,s)=>b(r,[C(i),$e(e),t??[]],s),Xe=r=>{let i=512;return r.fragmented?b("ftyp",[y("iso5"),l(i),y("iso5"),y("iso6"),y("mp41")]):b("ftyp",[y("isom"),l(i),y("isom"),r.holdsAvc?y("avc1"):[],y("mp41")])},de=r=>({type:"mdat",largeSize:r}),Ge=r=>({type:"free",size:r}),Y=(r,i,e=!1)=>b("moov",void 0,[dt(i,r),...r.map(t=>mt(t,i)),e?jt(r):null]),dt=(r,i)=>{let e=S(Math.max(0,...i.filter(a=>a.samples.length>0).map(a=>{let n=Se(a.samples);return n.timestamp+n.duration})),ce),t=Math.max(0,...i.map(a=>a.track.id))+1,s=!V(r)||!V(e),o=s?z:l;return T("mvhd",+s,0,[o(r),o(r),l(ce),o(e),v(1),xe(1),Array(10).fill(0),Le(Ke),Array(24).fill(0),l(t)])},mt=(r,i)=>b("trak",void 0,[ft(r,i),pt(r,i)]),ft=(r,i)=>{let e=Se(r.samples),t=S(e?e.timestamp+e.duration:0,ce),s=!V(i)||!V(t),o=s?z:l,a;if(r.type==="video"){let n=r.track.metadata.rotation;a=n===void 0||typeof n=="number"?qe(n??0):n}else a=Ke;return T("tkhd",+s,3,[o(i),o(i),l(r.track.id),l(0),o(t),Array(8).fill(0),h(0),h(r.track.id),xe(r.type==="audio"?1:0),h(0),Le(a),v(r.type==="video"?r.info.width:0),v(r.type==="video"?r.info.height:0)])},pt=(r,i)=>b("mdia",void 0,[ht(r,i),wt(r),Ct(r)]),ht=(r,i)=>{let e=Se(r.samples),t=S(e?e.timestamp+e.duration:0,r.timescale),s=!V(i)||!V(t),o=s?z:l;return T("mdhd",+s,0,[o(i),o(i),l(r.timescale),o(t),h(21956),h(0)])},bt={video:"vide",audio:"soun",subtitle:"text"},Tt={video:"VideoHandler",audio:"SoundHandler",subtitle:"TextHandler"},wt=r=>T("hdlr",0,0,[y("mhlr"),y(bt[r.type]),l(0),l(0),l(0),y(Tt[r.type],!0)]),Ct=r=>b("minf",void 0,[xt[r.type](),St(),_t(r)]),gt=()=>T("vmhd",0,1,[h(0),h(0),h(0),h(0)]),kt=()=>T("smhd",0,0,[h(0),h(0)]),yt=()=>T("nmhd",0,0),xt={video:gt,audio:kt,subtitle:yt},St=()=>b("dinf",void 0,[vt()]),vt=()=>T("dref",0,0,[l(1)],[At()]),At=()=>T("url ",0,1),_t=r=>{let i=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return b("stbl",void 0,[Ot(r),Ft(r),Bt(r),Nt(r),Ht(r),Qt(r),i?$t(r):null])},Ot=r=>{let i;return r.type==="video"?i=Et(er[r.track.source._codec],r):r.type==="audio"?i=Pt(rr[r.track.source._codec],r):r.type==="subtitle"&&(i=Wt(sr[r.track.source._codec],r)),c(i),T("stsd",0,0,[l(1)],[i])},Et=(r,i)=>b(r,[Array(6).fill(0),h(1),h(0),h(0),Array(12).fill(0),h(i.info.width),h(i.info.height),l(4718592),l(4718592),l(0),h(1),Array(32).fill(0),h(24),ct(65535)],[tr[i.track.source._codec](i),ae(i.info.decoderConfig.colorSpace)?Vt(i):null]),Vt=r=>b("colr",[y("nclx"),h(F[r.info.decoderConfig.colorSpace.primaries]),h(B[r.info.decoderConfig.colorSpace.transfer]),h(N[r.info.decoderConfig.colorSpace.matrix]),C((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Mt=r=>r.info.decoderConfig&&b("avcC",[...I(r.info.decoderConfig.description)]),It=r=>r.info.decoderConfig&&b("hvcC",[...I(r.info.decoderConfig.description)]),Qe=r=>{if(!r.info.decoderConfig)return null;let i=r.info.decoderConfig;c(i.colorSpace);let e=i.codec.split("."),t=Number(e[1]),s=Number(e[2]),n=(Number(e[3])<<4)+(0<<1)+Number(i.colorSpace.fullRange);return T("vpcC",1,0,[C(t),C(s),C(n),C(2),C(2),C(2),h(0)])},zt=()=>{let e=(1<<7)+1;return b("av1C",[e,0,0,0])},Pt=(r,i)=>b(r,[Array(6).fill(0),h(1),h(0),h(0),l(0),h(i.info.numberOfChannels),h(16),h(0),h(0),v(i.info.sampleRate)],[ir[i.track.source._codec](i)]),Ut=r=>{let e=[...I(r.info.decoderConfig.description??new ArrayBuffer(0))];return e=[...C(64),...C(21),...$e(0),...l(0),...l(0),...C(5),...ye(e.length),...e],e=[...h(1),...C(0),...C(4),...ye(e.length),...e,...C(6),...C(1),...C(2)],e=[...C(3),...ye(e.length),...e],T("esds",0,0,e)},Dt=r=>{let i=3840,e=0,t=r.info.decoderConfig?.description;if(t){c(t.byteLength<18);let s=ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t);i=s.getUint16(10,!0),e=s.getInt16(14,!0)}return b("dOps",[C(0),C(r.info.numberOfChannels),h(i),l(r.info.sampleRate),xe(e),C(0)])},Wt=(r,i)=>b(r,[Array(6).fill(0),h(1)],[or[i.track.source._codec](i)]),Rt=r=>b("vttC",[...x.encode(r.info.config.description)]);var Ft=r=>T("stts",0,0,[l(r.timeToSampleTable.length),r.timeToSampleTable.map(i=>[l(i.sampleCount),l(i.sampleDelta)])]),Bt=r=>{if(r.samples.every(e=>e.type==="key"))return null;let i=[...r.samples.entries()].filter(([,e])=>e.type==="key");return T("stss",0,0,[l(i.length),i.map(([e])=>l(e+1))])},Nt=r=>T("stsc",0,0,[l(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(i=>[l(i.firstChunk),l(i.samplesPerChunk),l(1)])]),Ht=r=>T("stsz",0,0,[l(0),l(r.samples.length),r.samples.map(i=>l(i.size))]),Qt=r=>r.finalizedChunks.length>0&&R(r.finalizedChunks).offset>=2**32?T("co64",0,0,[l(r.finalizedChunks.length),r.finalizedChunks.map(i=>z(i.offset))]):T("stco",0,0,[l(r.finalizedChunks.length),r.finalizedChunks.map(i=>l(i.offset))]),$t=r=>T("ctts",0,0,[l(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(i=>[l(i.sampleCount),l(i.sampleCompositionTimeOffset)])]),jt=r=>b("mvex",void 0,r.map(qt)),qt=r=>T("trex",0,0,[l(r.track.id),l(1),l(0),l(0),l(0)]),ve=(r,i)=>b("moof",void 0,[Kt(r),...i.map(Lt)]),Kt=r=>T("mfhd",0,0,[l(r)]),Ye=r=>{let i=0,e=0,t=0,s=0,o=r.type==="delta";return e|=+o,o?i|=1:i|=2,i<<24|e<<16|t<<8|s},Lt=r=>b("traf",void 0,[Xt(r),Gt(r),Yt(r)]),Xt=r=>{c(r.currentChunk);let i=0;i|=8,i|=16,i|=32,i|=131072;let e=r.currentChunk.samples[1]??r.currentChunk.samples[0],t={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Ye(e)};return T("tfhd",0,i,[l(r.track.id),l(t.duration),l(t.size),l(t.flags)])},Gt=r=>(c(r.currentChunk),T("tfdt",1,0,[z(S(r.currentChunk.startTimestamp,r.timescale))])),Yt=r=>{c(r.currentChunk);let i=r.currentChunk.samples.map(k=>k.timescaleUnitsToNextSample),e=r.currentChunk.samples.map(k=>k.size),t=r.currentChunk.samples.map(Ye),s=r.currentChunk.samples.map(k=>S(k.timestamp-k.decodeTimestamp,r.timescale)),o=new Set(i),a=new Set(e),n=new Set(t),u=new Set(s),d=n.size===2&&t[0]!==t[1],m=o.size>1,f=a.size>1,w=!d&&n.size>1,_=u.size>1||[...u].some(k=>k!==0),g=0;return g|=1,g|=4*+d,g|=256*+m,g|=512*+f,g|=1024*+w,g|=2048*+_,T("trun",1,g,[l(r.currentChunk.samples.length),l(r.currentChunk.offset-r.currentChunk.moofOffset||0),d?l(t[0]):[],r.currentChunk.samples.map((k,D)=>[m?l(i[D]):[],f?l(e[D]):[],w?l(t[D]):[],_?je(s[D]):[]])])},Ze=r=>b("mfra",void 0,[...r.map(Zt),Jt()]),Zt=(r,i)=>T("tfra",1,0,[l(r.track.id),l(63),l(r.finalizedChunks.length),r.finalizedChunks.map(t=>[z(S(t.startTimestamp,r.timescale)),z(t.moofOffset),l(i+1),l(1),l(1)])]),Jt=()=>T("mfro",0,0,[l(0)]),Je=()=>b("vtte"),et=(r,i,e,t,s)=>b("vttc",void 0,[s!==null?b("vsid",[je(s)]):null,e!==null?b("iden",[...x.encode(e)]):null,i!==null?b("ctim",[...x.encode(le(i))]):null,t!==null?b("sttg",[...x.encode(t)]):null,b("payl",[...x.encode(r)])]),tt=r=>b("vtta",[...x.encode(r)]),er={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},tr={avc:Mt,hevc:It,vp8:Qe,vp9:Qe,av1:zt},rr={aac:"mp4a",opus:"Opus"},ir={aac:Ut,opus:Dt},sr={webvtt:"wvtt"},or={webvtt:Rt};var Q=class{constructor(i){this.mutex=new W;this.trackTimestampInfo=new WeakMap;this.output=i}beforeTrackAdd(i){}onTrackClose(i){}validateAndNormalizeTimestamp(i,e,t){let s=e/1e6,o=this.trackTimestampInfo.get(i);if(!o){if(!t)throw new Error("First frame must be a key frame.");if(this.timestampsMustStartAtZero&&s>0)throw new Error(`Timestamps must start at zero (got ${s}s).`);o={timestampOffset:s,maxTimestamp:i.source._offsetTimestamps?0:s,lastKeyFrameTimestamp:i.source._offsetTimestamps?0:s},this.trackTimestampInfo.set(i,o)}if(i.source._offsetTimestamps&&(s-=o.timestampOffset),s<0)throw new Error(`Timestamps must be non-negative (got ${s}s).`);if(s<o.lastKeyFrameTimestamp)throw new Error(`Timestamp cannot be smaller than last key frame's timestamp (got ${s}s, last key frame at ${o.lastKeyFrameTimestamp}s).`);if(t){if(s<o.maxTimestamp)throw new Error(`Key frame timestamps cannot be smaller than any timestamp that came before (got ${s}s, max timestamp was ${o.maxTimestamp}s).`);o.lastKeyFrameTimestamp=s}return o.maxTimestamp=Math.max(o.maxTimestamp,s),s}};var Z=class{constructor(){this.ensureMonotonicity=!1}start(){}},$=class extends Z{constructor(e){super();this.pos=0;this.buffer=new ArrayBuffer(2**16);this.bytes=new Uint8Array(this.buffer);this.maxPos=0;this.target=e}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t===this.buffer.byteLength)return;let s=new ArrayBuffer(t),o=new Uint8Array(s);o.set(this.bytes,0),this.buffer=s,this.bytes=o}write(e){this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),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))}getSlice(e,t){return this.bytes.slice(e,t)}},me=class extends Z{constructor(e){super();this.pos=0;this.sections=[];this.lastFlushEnd=0;this.writer=null;this.target=e}start(){this.writer=this.target._writable.getWriter()}write(e){this.sections.push({data:e.slice(),start:this.pos}),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(c(this.writer),this.sections.length===0)return;let e=[],t=[...this.sections].sort((s,o)=>s.start-o.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let s=1;s<t.length;s++){let o=e[e.length-1],a=t[s];a.start<=o.start+o.size?o.size=Math.max(o.size,a.start+a.data.byteLength-o.start):e.push({start:a.start,size:a.data.byteLength})}for(let s of e){s.data=new Uint8Array(s.size);for(let o of this.sections)s.start<=o.start&&o.start<s.start+s.size&&s.data.set(o.data,o.start-s.start);if(this.ensureMonotonicity&&s.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.writer.write({type:"write",data:s.data,position:s.start}),this.lastFlushEnd=s.start+s.data.byteLength}this.sections.length=0}finalize(){return c(this.writer),this.writer.close()}},ar=2**24,nr=2,fe=class extends Z{constructor(e){super();this.pos=0;this.chunks=[];this.lastFlushEnd=0;this.writer=null;this.flushedChunkQueue=[];if(this.target=e,this.chunkSize=e._options?.chunkSize??ar,!Number.isInteger(this.chunkSize)||this.chunkSize<2**10)throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.")}start(){this.writer=this.target._writable.getWriter()}write(e){this.writeDataIntoChunks(e,this.pos),this.queueChunksForFlush(),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}writeDataIntoChunks(e,t){let s=this.chunks.findIndex(d=>d.start<=t&&t<d.start+this.chunkSize);s===-1&&(s=this.createChunk(t));let o=this.chunks[s],a=t-o.start,n=e.subarray(0,Math.min(this.chunkSize-a,e.byteLength));o.data.set(n,a);let u={start:a,end:a+n.byteLength};if(this.insertSectionIntoChunk(o,u),o.written[0].start===0&&o.written[0].end===this.chunkSize&&(o.shouldFlush=!0),this.chunks.length>nr){for(let d=0;d<this.chunks.length-1;d++)this.chunks[d].shouldFlush=!0;this.queueChunksForFlush()}n.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(n.byteLength),t+n.byteLength)}insertSectionIntoChunk(e,t){let s=0,o=e.written.length-1,a=-1;for(;s<=o;){let n=Math.floor(s+(o-s+1)/2);e.written[n].start<=t.start?(s=n+1,a=n):o=n-1}for(e.written.splice(a+1,0,t),(a===-1||e.written[a].end<t.start)&&a++;a<e.written.length-1&&e.written[a].end>=e.written[a+1].start;)e.written[a].end=Math.max(e.written[a].end,e.written[a+1].end),e.written.splice(a+1,1)}createChunk(e){let s={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(s),this.chunks.sort((o,a)=>o.start-a.start),this.chunks.indexOf(s)}queueChunksForFlush(e=!1){c(this.writer);for(let t=0;t<this.chunks.length;t++){let s=this.chunks[t];if(!(!s.shouldFlush&&!e)){for(let o of s.written){if(this.ensureMonotonicity&&s.start+o.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.flushedChunkQueue.push({type:"write",data:s.data.subarray(o.start,o.end),position:s.start+o.start}),this.lastFlushEnd=s.start+o.end}this.chunks.splice(t--,1)}}}async flush(){if(c(this.writer),this.flushedChunkQueue.length!==0){for(let e of this.flushedChunkQueue)this.writer.desiredSize!==null&&this.writer.desiredSize<=0&&await this.writer.ready,this.writer.write(e);this.flushedChunkQueue.length=0}}async finalize(){return c(this.writer),this.queueChunksForFlush(!0),await this.flush(),this.writer.close()}};var P=class{constructor(){this._output=null}},J=class extends P{constructor(){super(...arguments);this.buffer=null}_createWriter(){return new $(this)}},Ae=class extends P{constructor(i,e={}){if(super(),!(i instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(e!=null&&typeof e!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(e.chunked!==void 0&&typeof e.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer.");this._writable=i,this._options=e}_createWriter(){return this._options.chunked?new fe(this):new me(this)}};var rt=(r,i,e)=>{if(r==="avc"){let t=100;i<=768&&e<=432?t=66:i<=1920&&e<=1080&&(t=77);let s=0,o=i>1920||e>1080?50:41,a=t.toString(16).padStart(2,"0"),n=s.toString(16).padStart(2,"0"),u=o.toString(16).padStart(2,"0");return`avc1.${a}${n}${u}`}else if(r==="hevc"){let t=0,s=1,o=Array(32).fill(0);o[s]=1;let a=parseInt(o.reverse().join(""),2).toString(16).replace(/^0+/,""),n="L",u=120;return i<=1280&&e<=720?u=93:i<=1920&&e<=1080?u=120:i<=3840&&e<=2160?u=150:(n="H",u=180),`hev1.${t===0?"":String.fromCharCode(65+t-1)}${s}.${a}.${n}${u}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){let t="00",s;return i<=854&&e<=480?s="21":i<=1280&&e<=720?s="31":i<=1920&&e<=1080?s="41":i<=3840&&e<=2160?s="51":s="61",`vp09.${t}.${s}.08`}else if(r==="av1"){let s;return i<=854&&e<=480?s="01":i<=1280&&e<=720?s="03":i<=1920&&e<=1080?s="04":i<=3840&&e<=2160?s="07":s="09",`av01.0.${s}M.08`}}throw new TypeError(`Unhandled codec '${r}'.`)},it=(r,i,e)=>{if(r==="aac")return i>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";throw new TypeError(`Unhandled codec '${r}'.`)},pe=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.description!==void 0&&!ge(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){let{colorSpace:i}=r.decoderConfig;if(typeof i!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let e=Object.keys(F);if(i.primaries!=null&&!e.includes(i.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${e.join(", ")}.`);let t=Object.keys(B);if(i.transfer!=null&&!t.includes(i.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${t.join(", ")}.`);let s=Object.keys(N);if(i.matrix!=null&&!s.includes(i.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(i.fullRange!=null&&typeof i.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if((r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3"))&&!r.decoderConfig.description)throw new TypeError("Video chunk metadata decoder configuration for AVC must include a description, which is expected to be an AVCDecoderConfigurationRecord as specified in ISO 14496-15.");if((r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1"))&&!r.decoderConfig.description)throw new TypeError("Video chunk metadata decoder configuration for HEVC must include a description, which is expected to be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15.");if((r.decoderConfig.codec==="vp8"||r.decoderConfig.codec.startsWith("vp09"))&&r.decoderConfig.colorSpace===void 0)throw new TypeError("Video chunk metadata decoder configuration for VP8/VP9 must include a colorSpace.")},he=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!ge(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec==="opus"&&r.decoderConfig.description&&r.decoderConfig.description.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.")},be=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var ce=1e3,ur=2082844800,S=(r,i,e=!0)=>{let t=r*i;return e?Math.round(t):t},Te=class extends Q{constructor(e,t){super(e);this.timestampsMustStartAtZero=!0;this.auxTarget=new J;this.auxWriter=this.auxTarget._createWriter();this.auxBoxWriter=new G(this.auxWriter);this.ftypSize=null;this.mdat=null;this.trackDatas=[];this.creationTime=Math.floor(Date.now()/1e3)+ur;this.finalizedChunks=[];this.nextFragmentNumber=1;this.writer=e._writer,this.boxWriter=new G(this.writer),this.fastStart=t._options.fastStart??(this.writer instanceof $?"in-memory":!1),(this.fastStart==="in-memory"||this.fastStart==="fragmented")&&(this.writer.ensureMonotonicity=!0)}async start(){let e=await this.mutex.acquire(),t=this.output._tracks.some(s=>s.type==="video"&&s.source._codec==="avc");this.boxWriter.writeBox(Xe({holdsAvc:t,fragmented:this.fastStart==="fragmented"})),this.ftypSize=this.writer.getPos(),this.fastStart==="in-memory"?this.mdat=de(!1):this.fastStart==="fragmented"||(this.mdat=de(!0),this.boxWriter.writeBox(this.mdat)),await this.writer.flush(),e()}getVideoTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;pe(t),c(t),c(t.decoderConfig),c(t.decoderConfig.codedWidth!==void 0),c(t.decoderConfig.codedHeight!==void 0);let o={track:e,type:"video",info:{width:t.decoderConfig.codedWidth,height:t.decoderConfig.codedHeight,decoderConfig:t.decoderConfig},timescale:e.metadata.frameRate??57600,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),o}getAudioTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;he(t),c(t),c(t.decoderConfig);let o={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),o}getSubtitleTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;be(t),c(t),c(t.config);let o={track:e,type:"subtitle",info:{config:t.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(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),this.validateAndNormalizeTimestamp(e,0,!0),o}async addEncodedVideoChunk(e,t,s){let o=await this.mutex.acquire();try{let a=this.getVideoTrackData(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let u=this.validateAndNormalizeTimestamp(a.track,t.timestamp,t.type==="key"),d=this.createSampleForTrack(a,n,u,(t.duration??0)/1e6,t.type);await this.registerSample(a,d)}finally{o()}}async addEncodedAudioChunk(e,t,s){let o=await this.mutex.acquire();try{let a=this.getAudioTrackData(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let u=this.validateAndNormalizeTimestamp(a.track,t.timestamp,t.type==="key"),d=this.createSampleForTrack(a,n,u,(t.duration??0)/1e6,t.type);await this.registerSample(a,d)}finally{o()}}async addSubtitleCue(e,t,s){let o=await this.mutex.acquire();try{let a=this.getSubtitleTrackData(e,s);this.validateAndNormalizeTimestamp(a.track,1e6*t.timestamp,!0),e.source._codec==="webvtt"&&(a.cueQueue.push(t),await this.processWebVTTCues(a,t.timestamp))}finally{o()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let s=new Set([]);for(let m of e.cueQueue)c(m.timestamp<=t),c(e.lastCueEndTimestamp<=m.timestamp+m.duration),s.add(Math.max(m.timestamp,e.lastCueEndTimestamp)),s.add(m.timestamp+m.duration);let o=[...s].sort((m,f)=>m-f),a=o[0],n=o[1]??a;if(t<n)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);let m=Je();this.auxBoxWriter.writeBox(m);let f=this.auxWriter.getSlice(0,this.auxWriter.getPos()),w=this.createSampleForTrack(e,f,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,"key");await this.registerSample(e,w),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let m=0;m<e.cueQueue.length;m++){let f=e.cueQueue[m];if(f.timestamp>=n)break;H.lastIndex=0;let w=H.test(f.text),_=f.timestamp+f.duration,g=e.cueToSourceId.get(f);if(g===void 0&&n<_&&(g=e.nextSourceId++,e.cueToSourceId.set(f,g)),f.notes){let D=tt(f.notes);this.auxBoxWriter.writeBox(D)}let k=et(f.text,w?a:null,f.identifier??null,f.settings??null,g??null);this.auxBoxWriter.writeBox(k),_===n&&e.cueQueue.splice(m--,1)}let u=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,u,a,n-a,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,s,o,a){return{timestamp:s,decodeTimestamp:s,duration:o,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:S(o,e.timescale)}}processTimestamps(e){if(e.timestampProcessingQueue.length===0)return;let t=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,o)=>s-o);for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s];o.decodeTimestamp=t[s];let a=S(o.timestamp-o.decodeTimestamp,e.timescale),n=S(o.duration,e.timescale);if(e.lastTimescaleUnits!==null){c(e.lastSample);let u=S(o.decodeTimestamp,e.timescale,!1),d=Math.round(u-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=d,e.lastSample.timescaleUnitsToNextSample=d,this.fastStart!=="fragmented"){let m=R(e.timeToSampleTable);if(c(m),m.sampleCount===1){m.sampleDelta=d;let w=e.timeToSampleTable[e.timeToSampleTable.length-2];w&&w.sampleDelta===d&&(w.sampleCount++,e.timeToSampleTable.pop(),m=w)}else m.sampleDelta!==d&&(m.sampleCount--,e.timeToSampleTable.push(m={sampleCount:1,sampleDelta:d}));m.sampleDelta===n?m.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:n});let f=R(e.compositionTimeOffsetTable);c(f),f.sampleCompositionTimeOffset===a?f.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=0,this.fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=o}e.timestampProcessingQueue.length=0}async registerSample(e,t){this.fastStart==="fragmented"?(e.sampleQueue.push(t),await this.interleaveSamples()):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){t.type==="key"&&this.processTimestamps(e),this.fastStart!=="fragmented"&&e.samples.push(t);let s=!1;if(!e.currentChunk)s=!0;else{let o=t.timestamp-e.currentChunk.startTimestamp;if(this.fastStart==="fragmented"){let a=this.trackDatas.every(n=>{if(e===n)return t.type==="key";let u=n.sampleQueue[0];return u&&u.type==="key"});o>=1&&a&&(s=!0,await this.finalizeFragment())}else s=o>=.5}s&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),c(e.currentChunk),e.currentChunk.samples.push(t),e.timestampProcessingQueue.push(t)}async finalizeCurrentChunk(e){if(c(this.fastStart!=="fragmented"),!!e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||R(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)c(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}}async interleaveSamples(){c(this.fastStart==="fragmented");for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return;e:for(;;){let e=null,t=1/0;for(let o of this.trackDatas){if(o.sampleQueue.length===0&&!o.track.source._closed)break e;o.sampleQueue.length>0&&o.sampleQueue[0].timestamp<t&&(e=o,t=o.sampleQueue[0].timestamp)}if(!e)break;let s=e.sampleQueue.shift();await this.addSampleToTrack(e,s)}}async finalizeFragment(e=!0){c(this.fastStart==="fragmented");let t=this.nextFragmentNumber++;if(t===1){let u=Y(this.trackDatas,this.creationTime,!0);this.boxWriter.writeBox(u)}let s=this.writer.getPos(),o=ve(t,this.trackDatas);this.boxWriter.writeBox(o);{let u=de(!1),d=0;for(let f of this.trackDatas){c(f.currentChunk);for(let w of f.currentChunk.samples)d+=w.size}let m=this.boxWriter.measureBox(u)+d;m>=2**32&&(u.largeSize=!0,m=this.boxWriter.measureBox(u)+d),u.size=m,this.boxWriter.writeBox(u)}for(let u of this.trackDatas){u.currentChunk.offset=this.writer.getPos(),u.currentChunk.moofOffset=s;for(let d of u.currentChunk.samples)this.writer.write(d.data),d.data=null}let a=this.writer.getPos();this.writer.seek(this.boxWriter.offsets.get(o));let n=ve(t,this.trackDatas);this.boxWriter.writeBox(n),this.writer.seek(a);for(let u of this.trackDatas)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;e&&await this.writer.flush()}async onTrackClose(e){let t=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){let s=this.trackDatas.find(o=>o.track===e);s&&await this.processWebVTTCues(s,1/0)}this.fastStart==="fragmented"&&await this.interleaveSamples(),t()}async finalize(){let e=await this.mutex.acquire();for(let t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0);if(this.fastStart==="fragmented"){for(let t of this.trackDatas){for(let s of t.sampleQueue)await this.addSampleToTrack(t,s);this.processTimestamps(t)}await this.finalizeFragment(!1)}else for(let t of this.trackDatas)this.processTimestamps(t),await this.finalizeCurrentChunk(t);if(this.fastStart==="in-memory"){c(this.mdat);let t;for(let o=0;o<2;o++){let a=Y(this.trackDatas,this.creationTime),n=this.boxWriter.measureBox(a);t=this.boxWriter.measureBox(this.mdat);let u=this.writer.getPos()+n+t;for(let d of this.finalizedChunks){d.offset=u;for(let{data:m}of d.samples)c(m),u+=m.byteLength,t+=m.byteLength}if(u<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}let s=Y(this.trackDatas,this.creationTime);this.boxWriter.writeBox(s),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(let o of this.finalizedChunks)for(let a of o.samples)c(a.data),this.writer.write(a.data),a.data=null}else if(this.fastStart==="fragmented"){let t=this.writer.getPos(),s=Ze(this.trackDatas);this.boxWriter.writeBox(s);let o=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(o)}else{c(this.mdat),c(this.ftypSize!==null);let t=this.boxWriter.offsets.get(this.mdat);c(t!==void 0);let s=this.writer.getPos()-t;this.mdat.size=s,this.mdat.largeSize=s>=2**32,this.boxWriter.patchBox(this.mdat);let o=Y(this.trackDatas,this.creationTime);if(typeof this.fastStart=="object"){this.writer.seek(this.ftypSize),this.boxWriter.writeBox(o);let a=t-this.writer.getPos();this.boxWriter.writeBox(Ge(a))}else this.boxWriter.writeBox(o)}e()}};var ee=class{constructor(i){this.value=i}},j=class{constructor(i){this.value=i}},te=class{constructor(i){this.value=i}};var _e=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,Oe=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-(1<<20)&&r<1<<20?3:r>=-(1<<27)&&r<1<<27?4:r>=-(2**34)&&r<2**34?5:6,st=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML VINT size not supported "+r)};var Ee=2**15,ot="https://github.com/Vanilagy/webm-muxer",at=6,nt=5,lr={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",opus:"A_OPUS",webvtt:"S_TEXT/WEBVTT"},cr={video:1,audio:2,subtitle:17},we=class extends Q{constructor(e,t){super(e);this.timestampsMustStartAtZero=!1;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap;this.trackDatas=[];this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterMsTimestamp=null;this.trackDatasInCurrentCluster=new Set;this.duration=0;this.writer=e._writer,this.format=t,this.format._options.streamable&&(this.writer.ensureMonotonicity=!0)}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=_e(e)){let s=0;switch(t){case 6:this.helperView.setUint8(s++,e/2**40|0);case 5:this.helperView.setUint8(s++,e/2**32|0);case 4:this.helperView.setUint8(s++,e>>24);case 3:this.helperView.setUint8(s++,e>>16);case 2:this.helperView.setUint8(s++,e>>8);case 1:this.helperView.setUint8(s++,e);break;default:throw new Error("Bad UINT size "+t)}this.writer.write(this.helper.subarray(0,s))}writeSignedInt(e,t=Oe(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeEBMLVarInt(e,t=st(e)){let s=0;switch(t){case 1:this.helperView.setUint8(s++,128|e);break;case 2:this.helperView.setUint8(s++,64|e>>8),this.helperView.setUint8(s++,e);break;case 3:this.helperView.setUint8(s++,32|e>>16),this.helperView.setUint8(s++,e>>8),this.helperView.setUint8(s++,e);break;case 4:this.helperView.setUint8(s++,16|e>>24),this.helperView.setUint8(s++,e>>16),this.helperView.setUint8(s++,e>>8),this.helperView.setUint8(s++,e);break;case 5:this.helperView.setUint8(s++,8|e/2**32&7),this.helperView.setUint8(s++,e>>24),this.helperView.setUint8(s++,e>>16),this.helperView.setUint8(s++,e>>8),this.helperView.setUint8(s++,e);break;case 6:this.helperView.setUint8(s++,4|e/2**40&3),this.helperView.setUint8(s++,e/2**32|0),this.helperView.setUint8(s++,e>>24),this.helperView.setUint8(s++,e>>16),this.helperView.setUint8(s++,e>>8),this.helperView.setUint8(s++,e);break;default:throw new Error("Bad EBML VINT size "+t)}this.writer.write(this.helper.subarray(0,s))}writeString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),s=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+s);let o=this.writer.getPos();if(this.dataOffsets.set(e,o),this.writeEBML(e.data),e.size!==-1){let a=this.writer.getPos()-o,n=this.writer.getPos();this.writer.seek(t),this.writeEBMLVarInt(a,s),this.writer.seek(n)}}else if(typeof e.data=="number"){let t=e.size??_e(e.data);this.writeEBMLVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="string")this.writeEBMLVarInt(e.data.length),this.writeString(e.data);else if(e.data instanceof Uint8Array)this.writeEBMLVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof ee)this.writeEBMLVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof j)this.writeEBMLVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof te){let t=e.size??Oe(e.data.value);this.writeEBMLVarInt(t),this.writeSignedInt(e.data.value,t)}}}beforeTrackAdd(e){if(this.format instanceof q)if(e.type==="video"){if(!["vp8","vp9","av1"].includes(e.source._codec))throw new Error("WebM only supports VP8, VP9 and AV1 as video codecs. Switching to MKV removes this restriction.")}else if(e.type==="audio"){if(!["opus","vorbis"].includes(e.source._codec))throw new Error("WebM only supports Opus and Vorbis as audio codecs. Switching to MKV removes this restriction.")}else if(e.type==="subtitle"){if(e.source._codec!=="webvtt")throw new Error("WebM only supports WebVTT as subtitle codec. Switching to MKV removes this restriction.")}else throw new Error("WebM only supports video, audio and subtitle tracks. Switching to MKV removes this restriction.")}async start(){let e=await this.mutex.acquire();this.writeEBMLHeader(),this.format._options.streamable||this.createSeekHead(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof q?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};this.writeEBML(e)}createSeekHead(){let e=new Uint8Array([28,83,187,107]),t=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),o={id:290298740,data:[{id:19899,data:[{id:21419,data:e},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:t},{id:21420,size:5,data:0}]},{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:0}]}]};this.seekHead=o}createSegmentInfo(){let e={id:17545,data:new j(0)};this.segmentDuration=e;let t={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:ot},{id:22337,data:ot},this.format._options.streamable?null:e]};this.segmentInfo=t}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let t of this.trackDatas)e.data.push({id:174,data:[{id:215,data:t.track.id},{id:29637,data:t.track.id},{id:131,data:cr[t.type]},{id:134,data:lr[t.track.source._codec]},...t.type==="video"?[t.info.decoderConfig.description?{id:25506,data:I(t.info.decoderConfig.description)}:null,t.track.metadata.frameRate?{id:2352003,data:1e9/t.track.metadata.frameRate}:null,{id:224,data:[{id:176,data:t.info.width},{id:186,data:t.info.height},(()=>{if(t.info.decoderConfig.colorSpace){let s=t.info.decoderConfig.colorSpace;return ae(s)?{id:21936,data:[{id:21937,data:N[s.matrix]},{id:21946,data:B[s.transfer]},{id:21947,data:F[s.primaries]},{id:21945,data:[1,2][Number(s.fullRange)]}]}:null}return null})()]}]:[],...t.type==="audio"?[t.info.decoderConfig.description?{id:25506,data:I(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new ee(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels}]}]:[],...t.type==="subtitle"?[{id:25506,data:x.encode(t.info.config.description)}]:[]]})}createSegment(){let e={id:408125543,size:this.format._options.streamable?-1:at,data:[this.format._options.streamable?null:this.seekHead,this.segmentInfo,this.tracksElement]};this.segment=e,this.writeEBML(e)}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return c(this.segment),this.dataOffsets.get(this.segment)}getVideoTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;pe(t),c(t),c(t.decoderConfig),c(t.decoderConfig.codedWidth!==void 0),c(t.decoderConfig.codedHeight!==void 0);let o={track:e,type:"video",info:{width:t.decoderConfig.codedWidth,height:t.decoderConfig.codedHeight,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),o}getAudioTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;he(t),c(t),c(t.decoderConfig);let o={track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),o}getSubtitleTrackData(e,t){let s=this.trackDatas.find(a=>a.track===e);if(s)return s;be(t),c(t),c(t.config);let o={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(o),this.trackDatas.sort((a,n)=>a.track.id-n.track.id),o}async addEncodedVideoChunk(e,t,s){let o=await this.mutex.acquire();try{let a=this.getVideoTrackData(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let u=this.validateAndNormalizeTimestamp(a.track,t.timestamp,t.type==="key"),d=this.createInternalChunk(n,u,(t.duration??0)/1e6,t.type);e.source._codec==="vp9"&&this.fixVP9ColorSpace(a,d),a.chunkQueue.push(d),await this.interleaveChunks()}finally{o()}}async addEncodedAudioChunk(e,t,s){let o=await this.mutex.acquire();try{let a=this.getAudioTrackData(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let u=this.validateAndNormalizeTimestamp(a.track,t.timestamp,t.type==="key"),d=this.createInternalChunk(n,u,(t.duration??0)/1e6,t.type);a.chunkQueue.push(d),await this.interleaveChunks()}finally{o()}}async addSubtitleCue(e,t,s){let o=await this.mutex.acquire();try{let a=this.getSubtitleTrackData(e,s),n=this.validateAndNormalizeTimestamp(a.track,1e6*t.timestamp,!0),u=t.text,d=Math.floor(n*1e3);H.lastIndex=0,u=u.replace(H,_=>{let k=ue(_.slice(1,-1))-d;return`<${le(k)}>`});let m=x.encode(u),f=`${t.settings??""}
|
|
${t.identifier??""}
|
|
${t.notes??""}`,w=this.createInternalChunk(m,n,t.duration,"key",f.trim()?x.encode(f):null);a.chunkQueue.push(w),await this.interleaveChunks()}finally{o()}}async interleaveChunks(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return;e:for(;;){let e=null,t=1/0;for(let o of this.trackDatas){if(o.chunkQueue.length===0&&!o.track.source._closed)break e;o.chunkQueue.length>0&&o.chunkQueue[0].timestamp<t&&(e=o,t=o.chunkQueue[0].timestamp)}if(!e)break;let s=e.chunkQueue.shift();this.writeBlock(e,s)}await this.writer.flush()}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let s=0;if(M(t.data,0,2)!==2)return;s+=2;let o=(M(t.data,s+1,s+2)<<1)+M(t.data,s+0,s+1);s+=2,o===3&&s++;let a=M(t.data,s+0,s+1);if(s++,a)return;let n=M(t.data,s+0,s+1);if(s++,n!==0)return;s+=2;let u=M(t.data,s+0,s+24);if(s+=24,u!==4817730)return;o>=2&&s++;let d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];He(t.data,s+0,s+3,d)}createInternalChunk(e,t,s,o,a=null){return{data:e,type:o,timestamp:t,duration:s,additions:a}}writeBlock(e,t){this.segment||(this.createTracks(),this.createSegment());let s=Math.floor(1e3*t.timestamp),o=this.trackDatas.every(f=>{if(f.track.source._closed)return!0;if(e===f)return t.type==="key";let w=f.chunkQueue[0];return w&&w.type==="key"});(!this.currentCluster||o&&s-this.currentClusterMsTimestamp>=1e3)&&this.createNewCluster(s);let a=s-this.currentClusterMsTimestamp;if(a<0)return;if(a>=Ee)throw new Error(`Current Matroska cluster exceeded its maximum allowed length of ${Ee} milliseconds. In order to produce a correct WebM file, you must pass in a key frame at least every ${Ee} milliseconds.`);let u=new Uint8Array(4),d=new DataView(u.buffer);d.setUint8(0,128|e.track.id),d.setInt16(1,a,!1);let m=Math.floor(1e3*t.duration);if(m===0&&!t.additions){d.setUint8(3,+(t.type==="key")<<7);let f={id:163,data:[u,t.data]};this.writeEBML(f)}else{let f={id:160,data:[{id:161,data:[u,t.data]},t.type==="delta"?{id:251,data:new te(e.lastWrittenMsTimestamp-s)}:null,t.additions?{id:30113,data:[{id:166,data:[{id:165,data:t.additions},{id:238,data:1}]}]}:null,m>0?{id:155,data:m}:null]};this.writeEBML(f)}this.duration=Math.max(this.duration,s+m),e.lastWrittenMsTimestamp=s,this.trackDatasInCurrentCluster.add(e)}createNewCluster(e){this.currentCluster&&!this.format._options.streamable&&this.finalizeCurrentCluster(),this.currentCluster={id:524531317,size:this.format._options.streamable?-1:nt,data:[{id:231,data:e}]},this.writeEBML(this.currentCluster),this.currentClusterMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){c(this.currentCluster);let e=this.writer.getPos()-this.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.offsets.get(this.currentCluster)+4),this.writeEBMLVarInt(e,nt),this.writer.seek(t);let s=this.offsets.get(this.currentCluster)-this.segmentDataOffset;c(this.cues),this.cues.data.push({id:187,data:[{id:179,data:this.currentClusterMsTimestamp},...[...this.trackDatasInCurrentCluster].map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:s}]}))]})}async onTrackClose(){let e=await this.mutex.acquire();await this.interleaveChunks(),e()}async finalize(){let e=await this.mutex.acquire();this.segment||(this.createTracks(),this.createSegment());for(let t of this.trackDatas)for(;t.chunkQueue.length>0;)this.writeBlock(t,t.chunkQueue.shift());if(!this.format._options.streamable&&this.currentCluster&&this.finalizeCurrentCluster(),c(this.cues),this.writeEBML(this.cues),!this.format._options.streamable){let t=this.writer.getPos(),s=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.offsets.get(this.segment)+4),this.writeEBMLVarInt(s,at),this.segmentDuration.data=new j(this.duration),this.writer.seek(this.offsets.get(this.segmentDuration)),this.writeEBML(this.segmentDuration),this.seekHead.data[0].data[1].data=this.offsets.get(this.cues)-this.segmentDataOffset,this.seekHead.data[1].data[1].data=this.offsets.get(this.segmentInfo)-this.segmentDataOffset,this.seekHead.data[2].data[1].data=this.offsets.get(this.tracksElement)-this.segmentDataOffset,this.writer.seek(this.offsets.get(this.seekHead)),this.writeEBML(this.seekHead),this.writer.seek(t)}e()}};var U=class{},Ve=class extends U{constructor(i={}){if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.fastStart!==void 0&&![!1,"in-memory","fragmented"].includes(i.fastStart))throw new TypeError('options.fastStart, when provided, must be false, "in-memory", or "fragmented".');super(),this._options=i}_createMuxer(i){return new Te(i,this)}},Ce=class extends U{constructor(i={}){if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.streamable!==void 0&&typeof i.streamable!="boolean")throw new TypeError("options.streamable, when provided, must be a boolean.");super(),this._options=i}_createMuxer(i){return new we(i,this)}},q=class extends Ce{};var re=["avc","hevc","vp8","vp9","av1"],ie=["aac","opus"],Me=["webvtt"],K=class{constructor(){this._connectedTrack=null;this._closed=!1;this._offsetTimestamps=!1}_ensureValidDigest(){if(!this._connectedTrack)throw new Error("Cannot call digest without connecting the source to an output track.");if(!this._connectedTrack.output._started)throw new Error("Cannot call digest before output has been started.");if(this._connectedTrack.output._finalizing)throw new Error("Cannot call digest after output has started finalizing.");if(this._closed)throw new Error("Cannot call digest after source has been closed.")}_start(){}async _flush(){}close(){if(this._closed)throw new Error("Source already closed.");if(!this._connectedTrack)throw new Error("Cannot call close without connecting the source to an output track.");if(!this._connectedTrack.output._started)throw new Error("Cannot call close before output has been started.");this._closed=!0,!this._connectedTrack.output._finalizing&&this._connectedTrack.output._muxer.onTrackClose(this._connectedTrack)}},O=class extends K{constructor(e){super();this._connectedTrack=null;if(!re.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${re.join(", ")}.`);this._codec=e}},Ie=class extends O{constructor(i){super(i)}digest(i,e){if(!(i instanceof EncodedVideoChunk))throw new TypeError("chunk must be an EncodedVideoChunk.");return this._ensureValidDigest(),this._connectedTrack.output._muxer.addEncodedVideoChunk(this._connectedTrack,i,e)}},dr=5,mr=r=>{if(!r||typeof r!="object")throw new TypeError("Codec config must be an object.");if(!re.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${re.join(", ")}.`);if(!Number.isInteger(r.bitrate)||r.bitrate<=0)throw new TypeError("config.bitrate must be a positive integer.");if(r.latencyMode!==void 0&&["quality","realtime"].includes(r.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.")},se=class{constructor(i,e){this.source=i;this.codecConfig=e;this.encoder=null;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.lastWidth=null;this.lastHeight=null;mr(e)}async digest(i){if(this.source._ensureValidDigest(),this.lastWidth!==null&&this.lastHeight!==null){if(i.codedWidth!==this.lastWidth||i.codedHeight!==this.lastHeight)throw new Error(`Video frame size must remain constant. Expected ${this.lastWidth}x${this.lastHeight}, got ${i.codedWidth}x${i.codedHeight}.`)}else this.lastWidth=i.codedWidth,this.lastHeight=i.codedHeight;this.ensureEncoder(i),c(this.encoder);let e=Math.floor(i.timestamp/1e6/dr);this.encoder.encode(i,{keyFrame:e!==this.lastMultipleOfKeyFrameInterval}),this.lastMultipleOfKeyFrameInterval=e,this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0})),await this.muxer.mutex.currentPromise}ensureEncoder(i){this.encoder||(this.encoder=new VideoEncoder({output:(e,t)=>this.muxer.addEncodedVideoChunk(this.source._connectedTrack,e,t),error:e=>console.error("Video encode error:",e)}),this.encoder.configure({codec:rt(this.codecConfig.codec,i.codedWidth,i.codedHeight),width:i.codedWidth,height:i.codedHeight,bitrate:this.codecConfig.bitrate,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.codecConfig.latencyMode}),c(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer)}async flush(){this.encoder&&(await this.encoder.flush(),this.encoder.close())}},ze=class extends O{constructor(i){super(i.codec),this._encoder=new se(this,i)}digest(i){if(!(i instanceof VideoFrame))throw new TypeError("videoFrame must be a VideoFrame.");return this._encoder.digest(i)}_flush(){return this._encoder.flush()}},Pe=class extends O{constructor(i,e){if(!(i instanceof HTMLCanvasElement))throw new TypeError("canvas must be an HTMLCanvasElement.");super(e.codec),this._encoder=new se(this,e),this._canvas=i}digest(i,e=0){if(!Number.isFinite(i)||i<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");let t=new VideoFrame(this._canvas,{timestamp:Math.round(1e6*i),duration:Math.round(1e6*e),alpha:"discard"}),s=this._encoder.digest(t);return t.close(),s}_flush(){return this._encoder.flush()}},Ue=class extends O{constructor(e,t){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");t={...t,latencyMode:"realtime"};super(t.codec);this._abortController=null;this._offsetTimestamps=!0;this._encoder=new se(this,t),this._track=e}_start(){this._abortController=new AbortController;let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:s=>{this._encoder.digest(s),s.close()}});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(s=>{s instanceof DOMException&&s.name==="AbortError"||console.error("Pipe error:",s)})}async _flush(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flush()}},E=class extends K{constructor(e){super();this._connectedTrack=null;if(!ie.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${ie.join(", ")}.`);this._codec=e}},De=class extends E{constructor(i){super(i)}digest(i,e){if(!(i instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedAudioChunk.");return this._ensureValidDigest(),this._connectedTrack.output._muxer.addEncodedAudioChunk(this._connectedTrack,i,e)}},fr=r=>{if(!r||typeof r!="object")throw new TypeError("Codec config must be an object.");if(!ie.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${ie.join(", ")}.`);if(!Number.isInteger(r.bitrate)||r.bitrate<=0)throw new TypeError("config.bitrate must be a positive integer.")},oe=class{constructor(i,e){this.source=i;this.codecConfig=e;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;fr(e)}async digest(i){if(this.source._ensureValidDigest(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(i.numberOfChannels!==this.lastNumberOfChannels||i.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${i.numberOfChannels} channels at ${i.sampleRate} Hz.`)}else this.lastNumberOfChannels=i.numberOfChannels,this.lastSampleRate=i.sampleRate;this.ensureEncoder(i),c(this.encoder),this.encoder.encode(i),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0})),await this.muxer.mutex.currentPromise}ensureEncoder(i){this.encoder||(this.encoder=new AudioEncoder({output:(e,t)=>this.muxer.addEncodedAudioChunk(this.source._connectedTrack,e,t),error:e=>console.error("Audio encode error:",e)}),this.encoder.configure({codec:it(this.codecConfig.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:this.codecConfig.bitrate}),c(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer)}async flush(){this.encoder&&(await this.encoder.flush(),this.encoder.close())}},We=class extends E{constructor(i){super(i.codec),this._encoder=new oe(this,i)}digest(i){if(!(i instanceof AudioData))throw new TypeError("audioData must be an AudioData.");return this._encoder.digest(i)}_flush(){return this._encoder.flush()}},Re=class extends E{constructor(e){super(e.codec);this._accumulatedFrameCount=0;this._encoder=new oe(this,e)}digest(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let t=e.numberOfChannels,s=e.sampleRate,o=e.length,a=new Float32Array(t*o);for(let d=0;d<t;d++){let m=e.getChannelData(d);a.set(m,d*o)}let n=new AudioData({format:"f32-planar",sampleRate:s,numberOfFrames:o,numberOfChannels:t,timestamp:Math.round(1e6*this._accumulatedFrameCount/s),data:a}),u=this._encoder.digest(n);return n.close(),this._accumulatedFrameCount+=o,u}_flush(){return this._encoder.flush()}},Fe=class extends E{constructor(e,t){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");super(t.codec);this._abortController=null;this._offsetTimestamps=!0;this._encoder=new oe(this,t),this._track=e}_start(){this._abortController=new AbortController;let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:s=>{this._encoder.digest(s),s.close()}});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(s=>{s instanceof DOMException&&s.name==="AbortError"||console.error("Pipe error:",s)})}async _flush(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flush()}},L=class extends K{constructor(e){super();this._connectedTrack=null;if(!Me.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Me.join(", ")}.`);this._codec=e}},Be=class extends L{constructor(i){super(i),this._parser=new ne({codec:i,output:(e,t)=>this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,e,t),error:e=>console.error("Subtitle parse error:",e)})}digest(i){if(typeof i!="string")throw new TypeError("text must be a string.");return this._ensureValidDigest(),this._parser.parse(i),this._connectedTrack.output._muxer.mutex.currentPromise}};var Ne=class{constructor(i){this._tracks=[];this._started=!1;this._finalizing=!1;this._mutex=new W;if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(!(i.format instanceof U))throw new TypeError("options.format must be an OutputFormat.");if(!(i.target instanceof P))throw new TypeError("options.target must be a Target.");if(i.target._output)throw new Error("Target is already used for another output.");i.target._output=this,this._writer=i.target._createWriter(),this._muxer=i.format._createMuxer(this)}addVideoTrack(i,e={}){if(!(i instanceof O))throw new TypeError("source must be a VideoSource.");if(!e||typeof e!="object")throw new TypeError("metadata must be an object.");if(typeof e.rotation=="number"&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(e.rotation)&&(e.rotation.length!==9||e.rotation.some(t=>!Number.isFinite(t))))throw new TypeError(`Invalid video transformation matrix: ${e.rotation.join()}`);if(e.frameRate!==void 0&&(!Number.isInteger(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive integer.`);this._addTrack("video",i,e)}addAudioTrack(i,e={}){if(!(i instanceof E))throw new TypeError("source must be an AudioSource.");if(!e||typeof e!="object")throw new TypeError("metadata must be an object.");this._addTrack("audio",i,e)}addSubtitleTrack(i,e={}){if(!(i instanceof L))throw new TypeError("source must be a SubtitleSource.");if(!e||typeof e!="object")throw new TypeError("metadata must be an object.");this._addTrack("subtitle",i,e)}_addTrack(i,e,t){if(this._started)throw new Error("Cannot add track after output has started.");if(e._connectedTrack)throw new Error("Source is already used for a track.");let s={id:this._tracks.length+1,output:this,type:i,source:e,metadata:t};this._muxer.beforeTrackAdd(s),this._tracks.push(s),e._connectedTrack=s}async start(){if(this._started)throw new Error("Output already started.");this._started=!0,this._writer.start();let i=await this._mutex.acquire();await this._muxer.start();for(let e of this._tracks)e.source._start();i()}async finalize(){if(!this._started)throw new Error("Cannot finalize before starting.");if(this._finalizing)throw new Error("Cannot call finalize twice.");this._finalizing=!0;let i=await this._mutex.acquire(),e=this._tracks.map(t=>t.source._flush());await Promise.all(e),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),i()}};export{ie as AUDIO_CODECS,J as ArrayBufferTarget,Re as AudioBufferSource,We as AudioDataSource,E as AudioSource,Pe as CanvasSource,De as EncodedAudioChunkSource,Ie as EncodedVideoChunkSource,K as MediaSource,Fe as MediaStreamAudioTrackSource,Ue as MediaStreamVideoTrackSource,Ce as MkvOutputFormat,Ve as Mp4OutputFormat,Ne as Output,U as OutputFormat,Me as SUBTITLE_CODECS,Ae as StreamTarget,L as SubtitleSource,P as Target,Be as TextSubtitleSource,re as VIDEO_CODECS,ze as VideoFrameSource,O as VideoSource,q as WebMOutputFormat};
|