mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-10-02 21:33:52 +02:00
10 lines
47 KiB
JavaScript
10 lines
47 KiB
JavaScript
var he=class{constructor(r){this.tracks=[];this.started=!1;this.finalizing=!1;if(r.target.output)throw new Error("Target is already used for another output.");r.target.output=this,this.writer=r.target.createWriter(),this.muxer=r.format.createMuxer(this)}addVideoTrack(r,e={}){this.addTrack("video",r,e)}addAudioTrack(r,e={}){this.addTrack("audio",r,e)}addSubtitleTrack(r,e={}){this.addTrack("subtitle",r,e)}addTrack(r,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:r,source:e,metadata:t};this.muxer.beforeTrackAdd(s),this.tracks.push(s),e.connectedTrack=s}start(){if(this.started)throw new Error("Output already started.");this.started=!0,this.muxer.start();for(let r of this.tracks)r.source.start()}async finalize(){if(this.finalizing)throw new Error("Cannot call finalize twice.");this.finalizing=!0;let r=this.tracks.map(e=>e.source.flush());await Promise.all(r),this.muxer.finalize(),this.writer.flush(),this.writer.finalize()}};function c(i){if(!i)throw new Error("Assertion failed.")}var P=i=>i&&i[i.length-1],V=i=>i>=0&&i<2**32,M=(i,r,e)=>{let t=0;for(let s=r;s<e;s++){let o=Math.floor(s/8),n=i[o],a=7-(s&7),u=(n&1<<a)>>a;t<<=1,t|=u}return t},_e=(i,r,e,t)=>{for(let s=r;s<e;s++){let o=Math.floor(s/8),n=i[o],a=7-(s&7);n&=~(1<<a),n|=(t&1<<e-s-1)>>e-s-1<<a,i[o]=n}},E=i=>i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),y=new TextEncoder,J={bt709:1,bt470bg:5,smpte170m:6},ee={bt709:1,smpte170m:6,"iec61966-2-1":13},te={rgb:0,bt709:1,bt470bg:5,smpte170m:6},re=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0;var W=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,tt=/^WEBVTT(.|\n)*?\n{2}/,I=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ie=class{#e;#i=null;#t=!1;constructor(r){this.#e=r}parse(r){r=r.replaceAll(`\r
|
|
`,`
|
|
`).replaceAll("\r",`
|
|
`),W.lastIndex=0;let e;if(!this.#i){if(!tt.test(r)){let s=new Error("WebVTT preamble incorrect.");throw this.#e.error(s),s}e=W.exec(r);let t=r.slice(0,e?.index??r.length).trimEnd();if(!t){let s=new Error("No WebVTT preamble provided.");throw this.#e.error(s),s}this.#i=t,e&&(r=r.slice(e.index),W.lastIndex=0)}for(;e=W.exec(r);){let t=r.slice(0,e.index),s=e[1],o=e.index+e[0].length,n=r.indexOf(`
|
|
`,o)+1,a=r.slice(o,n).trim(),u=r.indexOf(`
|
|
|
|
`,o);u===-1&&(u=r.length);let m=se(e[2]),f=se(e[3])-m,C=r.slice(n,u).trim();r=r.slice(u).trimStart(),W.lastIndex=0;let v={timestamp:m/1e3,duration:f/1e3,text:C,identifier:s,settings:a,notes:t},k={};this.#t||(k.config={description:this.#i},this.#t=!0),this.#e.output(v,k)}}},rt=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,se=i=>{let r=rt.exec(i);if(!r)throw new Error("Expected match.");return 60*60*1e3*Number(r[1]||"0")+60*1e3*Number(r[2])+1e3*Number(r[3])+Number(r[4])},oe=i=>{let r=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),t=Math.floor(i%(60*1e3)/1e3),s=i%1e3;return r.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};var Q=class{constructor(r){this.writer=r;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(r){this.helperView.setUint32(0,r,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(r){this.helperView.setUint32(0,Math.floor(r/2**32),!1),this.helperView.setUint32(4,r,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(r){for(let e=0;e<r.length;e++)this.helperView.setUint8(e%8,r.charCodeAt(e)),e%8===7&&this.writer.write(this.helper);r.length%8!==0&&this.writer.write(this.helper.subarray(0,r.length%8))}writeBox(r){if(this.offsets.set(r,this.writer.getPos()),r.contents&&!r.children)this.writeBoxHeader(r,r.size??r.contents.byteLength+8),this.writer.write(r.contents);else{let e=this.writer.getPos();if(this.writeBoxHeader(r,0),r.contents&&this.writer.write(r.contents),r.children)for(let o of r.children)o&&this.writeBox(o);let t=this.writer.getPos(),s=r.size??t-e;this.writer.seek(e),this.writeBoxHeader(r,s),this.writer.seek(t)}}writeBoxHeader(r,e){this.writeU32(r.largeSize?1:e),this.writeAscii(r.type),r.largeSize&&this.writeU64(e)}measureBoxHeader(r){return 8+(r.largeSize?8:0)}patchBox(r){let e=this.offsets.get(r);c(e!==void 0);let t=this.writer.getPos();this.writer.seek(e),this.writeBox(r),this.writer.seek(t)}measureBox(r){if(r.contents&&!r.children)return this.measureBoxHeader(r)+r.contents.byteLength;{let e=this.measureBoxHeader(r);if(r.contents&&(e+=r.contents.byteLength),r.children)for(let t of r.children)t&&(e+=this.measureBox(t));return e}}},p=new Uint8Array(8),O=new DataView(p.buffer),g=i=>[(i%256+256)%256],h=i=>(O.setUint16(0,i,!1),[p[0],p[1]]),it=i=>(O.setInt16(0,i,!1),[p[0],p[1]]),Be=i=>(O.setUint32(0,i,!1),[p[1],p[2],p[3]]),l=i=>(O.setUint32(0,i,!1),[p[0],p[1],p[2],p[3]]),Fe=i=>(O.setInt32(0,i,!1),[p[0],p[1],p[2],p[3]]),z=i=>(O.setUint32(0,Math.floor(i/2**32),!1),O.setUint32(4,i,!1),[p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]]),Te=i=>(O.setInt16(0,2**8*i,!1),[p[0],p[1]]),A=i=>(O.setInt32(0,2**16*i,!1),[p[0],p[1],p[2],p[3]]),be=i=>(O.setInt32(0,2**30*i,!1),[p[0],p[1],p[2],p[3]]),x=(i,r=!1)=>{let e=Array(i.length).fill(null).map((t,s)=>i.charCodeAt(s));return r&&e.push(0),e},Ce=i=>{let r=null;for(let e of i)(!r||e.timestamp>r.timestamp)&&(r=e);return r},De=i=>{let r=i*(Math.PI/180),e=Math.cos(r),t=Math.sin(r);return[e,t,0,-t,e,0,0,0,1]},Ne=De(0),We=i=>[A(i[0]),A(i[1]),be(i[2]),A(i[3]),A(i[4]),be(i[5]),A(i[6]),A(i[7]),be(i[8])],b=(i,r,e)=>({type:i,contents:r&&new Uint8Array(r.flat(10)),children:e}),T=(i,r,e,t,s)=>b(i,[g(r),Be(e),t??[]],s),Qe=i=>{let r=512;return i.fragmented?b("ftyp",[x("iso5"),l(r),x("iso5"),x("iso6"),x("mp41")]):b("ftyp",[x("isom"),l(r),x("isom"),i.holdsAvc?x("avc1"):[],x("mp41")])},ae=i=>({type:"mdat",largeSize:i}),He=i=>({type:"free",size:i}),H=(i,r,e=!1)=>b("moov",void 0,[st(r,i),...i.map(t=>ot(t,r)),e?Ft(i):null]),st=(i,r)=>{let e=w(Math.max(0,...r.filter(n=>n.samples.length>0).map(n=>{let a=Ce(n.samples);return a.timestamp+a.duration})),ne),t=Math.max(...r.map(n=>n.track.id))+1,s=!V(i)||!V(e),o=s?z:l;return T("mvhd",+s,0,[o(i),o(i),l(ne),o(e),A(1),Te(1),Array(10).fill(0),We(Ne),Array(24).fill(0),l(t)])},ot=(i,r)=>b("trak",void 0,[nt(i,r),at(i,r)]),nt=(i,r)=>{let e=Ce(i.samples),t=w(e?e.timestamp+e.duration:0,ne),s=!V(r)||!V(t),o=s?z:l,n;if(i.type==="video"){let a=i.track.metadata.rotation;n=a===void 0||typeof a=="number"?De(a??0):a}else n=Ne;return T("tkhd",+s,3,[o(r),o(r),l(i.track.id),l(0),o(t),Array(8).fill(0),h(0),h(i.track.id),Te(i.type==="audio"?1:0),h(0),We(n),A(i.type==="video"?i.info.width:0),A(i.type==="video"?i.info.height:0)])},at=(i,r)=>b("mdia",void 0,[ut(i,r),dt(i),mt(i)]),ut=(i,r)=>{let e=Ce(i.samples),t=w(e?e.timestamp+e.duration:0,i.timescale),s=!V(r)||!V(t),o=s?z:l;return T("mdhd",+s,0,[o(r),o(r),l(i.timescale),o(t),h(21956),h(0)])},lt={video:"vide",audio:"soun",subtitle:"text"},ct={video:"VideoHandler",audio:"SoundHandler",subtitle:"TextHandler"},dt=i=>T("hdlr",0,0,[x("mhlr"),x(lt[i.type]),l(0),l(0),l(0),x(ct[i.type],!0)]),mt=i=>b("minf",void 0,[bt[i.type](),Tt(),kt(i)]),ft=()=>T("vmhd",0,1,[h(0),h(0),h(0),h(0)]),pt=()=>T("smhd",0,0,[h(0),h(0)]),ht=()=>T("nmhd",0,0),bt={video:ft,audio:pt,subtitle:ht},Tt=()=>b("dinf",void 0,[Ct()]),Ct=()=>T("dref",0,0,[l(1)],[gt()]),gt=()=>T("url ",0,1),kt=i=>{let r=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return b("stbl",void 0,[xt(i),Ut(i),Pt(i),It(i),_t(i),Rt(i),r?Bt(i):null])},xt=i=>{let r;return i.type==="video"?r=St(Xt[i.track.source.codec],i):i.type==="audio"?r=vt(Lt[i.track.source.codec],i):i.type==="subtitle"&&(r=Et(Yt[i.track.source.codec],i)),c(r),T("stsd",0,0,[l(1)],[r])},St=(i,r)=>b(i,[Array(6).fill(0),h(1),h(0),h(0),Array(12).fill(0),h(r.info.width),h(r.info.height),l(4718592),l(4718592),l(0),h(1),Array(32).fill(0),h(24),it(65535)],[jt[r.track.source.codec](r),re(r.info.decoderConfig.colorSpace)?yt(r):null]),yt=i=>b("colr",[x("nclx"),h(J[i.info.decoderConfig.colorSpace.primaries]),h(ee[i.info.decoderConfig.colorSpace.transfer]),h(te[i.info.decoderConfig.colorSpace.matrix]),g((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),wt=i=>i.info.decoderConfig&&b("avcC",[...E(i.info.decoderConfig.description)]),At=i=>i.info.decoderConfig&&b("hvcC",[...E(i.info.decoderConfig.description)]),Re=i=>{if(!i.info.decoderConfig)return null;let r=i.info.decoderConfig;if(!r.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP8/VP9.");let e=r.codec.split("."),t=Number(e[1]),s=Number(e[2]),a=(Number(e[3])<<4)+(0<<1)+Number(r.colorSpace.fullRange);return T("vpcC",1,0,[g(t),g(s),g(a),g(2),g(2),g(2),h(0)])},Ot=()=>{let e=(1<<7)+1;return b("av1C",[e,0,0,0])},vt=(i,r)=>b(i,[Array(6).fill(0),h(1),h(0),h(0),l(0),h(r.info.numberOfChannels),h(16),h(0),h(0),A(r.info.sampleRate)],[qt[r.track.source.codec](r)]),Vt=i=>{let r=E(i.info.decoderConfig.description??new ArrayBuffer(0));return T("esds",0,0,[l(58753152),g(32+r.byteLength),h(1),g(0),l(75530368),g(18+r.byteLength),g(64),g(21),Be(0),l(130071),l(130071),l(92307584),g(r.byteLength),...r,l(109084800),g(1),g(2)])},Mt=i=>{let r=3840,e=0,t=i.info.decoderConfig?.description;if(t){if(t.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");let s=ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t);r=s.getUint16(10,!0),e=s.getInt16(14,!0)}return b("dOps",[g(0),g(i.info.numberOfChannels),h(r),l(i.info.sampleRate),Te(e),g(0)])},Et=(i,r)=>b(i,[Array(6).fill(0),h(1)],[Zt[r.track.source.codec](r)]),zt=i=>b("vttC",[...y.encode(i.info.config.description)]);var Ut=i=>T("stts",0,0,[l(i.timeToSampleTable.length),i.timeToSampleTable.map(r=>[l(r.sampleCount),l(r.sampleDelta)])]),Pt=i=>{if(i.samples.every(e=>e.type==="key"))return null;let r=[...i.samples.entries()].filter(([,e])=>e.type==="key");return T("stss",0,0,[l(r.length),r.map(([e])=>l(e+1))])},It=i=>T("stsc",0,0,[l(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(r=>[l(r.firstChunk),l(r.samplesPerChunk),l(1)])]),_t=i=>T("stsz",0,0,[l(0),l(i.samples.length),i.samples.map(r=>l(r.size))]),Rt=i=>i.finalizedChunks.length>0&&P(i.finalizedChunks).offset>=2**32?T("co64",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(r=>z(r.offset))]):T("stco",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(r=>l(r.offset))]),Bt=i=>T("ctts",0,0,[l(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(r=>[l(r.sampleCount),l(r.sampleCompositionTimeOffset)])]),Ft=i=>b("mvex",void 0,i.map(Dt)),Dt=i=>T("trex",0,0,[l(i.track.id),l(1),l(0),l(0),l(0)]),ge=(i,r)=>b("moof",void 0,[Nt(i),...r.map(Wt)]),Nt=i=>T("mfhd",0,0,[l(i)]),$e=i=>{let r=0,e=0,t=0,s=0,o=i.type==="delta";return e|=+o,o?r|=1:r|=2,r<<24|e<<16|t<<8|s},Wt=i=>b("traf",void 0,[Qt(i),Ht(i),$t(i)]),Qt=i=>{c(i.currentChunk);let r=0;r|=8,r|=16,r|=32,r|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],t={duration:e.timescaleUnitsToNextSample,size:e.size,flags:$e(e)};return T("tfhd",0,r,[l(i.track.id),l(t.duration),l(t.size),l(t.flags)])},Ht=i=>(c(i.currentChunk),T("tfdt",1,0,[z(w(i.currentChunk.startTimestamp,i.timescale))])),$t=i=>{c(i.currentChunk);let r=i.currentChunk.samples.map(S=>S.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(S=>S.size),t=i.currentChunk.samples.map($e),s=i.currentChunk.samples.map(S=>w(S.timestamp-S.decodeTimestamp,i.timescale)),o=new Set(r),n=new Set(e),a=new Set(t),u=new Set(s),m=a.size===2&&t[0]!==t[1],d=o.size>1,f=n.size>1,C=!m&&a.size>1,v=u.size>1||[...u].some(S=>S!==0),k=0;return k|=1,k|=4*+m,k|=256*+d,k|=512*+f,k|=1024*+C,k|=2048*+v,T("trun",1,k,[l(i.currentChunk.samples.length),l(i.currentChunk.offset-i.currentChunk.moofOffset||0),m?l(t[0]):[],i.currentChunk.samples.map((S,U)=>[d?l(r[U]):[],f?l(e[U]):[],C?l(t[U]):[],v?Fe(s[U]):[]])])},Ke=i=>b("mfra",void 0,[...i.map(Kt),Gt()]),Kt=(i,r)=>T("tfra",1,0,[l(i.track.id),l(63),l(i.finalizedChunks.length),i.finalizedChunks.map(t=>[z(w(t.startTimestamp,i.timescale)),z(t.moofOffset),l(r+1),l(1),l(1)])]),Gt=()=>T("mfro",0,0,[l(0)]),Ge=()=>b("vtte"),Xe=(i,r,e,t,s)=>b("vttc",void 0,[s!==null?b("vsid",[Fe(s)]):null,e!==null?b("iden",[...y.encode(e)]):null,r!==null?b("ctim",[...y.encode(oe(r))]):null,t!==null?b("sttg",[...y.encode(t)]):null,b("payl",[...y.encode(i)])]),je=i=>b("vtta",[...y.encode(i)]),Xt={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},jt={avc:wt,hevc:At,vp8:Re,vp9:Re,av1:Ot},Lt={aac:"mp4a",opus:"Opus"},qt={aac:Vt,opus:Mt},Yt={webvtt:"wvtt"},Zt={webvtt:zt};var _=class{constructor(r){this.trackTimestampInfo=new WeakMap;this.output=r}beforeTrackAdd(r){}onTrackClose(r){}validateAndNormalizeTimestamp(r,e,t){let s=e/1e6,o=this.trackTimestampInfo.get(r);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:r.source.offsetTimestamps?0:s,lastKeyFrameTimestamp:r.source.offsetTimestamps?0:s},this.trackTimestampInfo.set(r,o)}if(r.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 $=class{},ue=class extends ${#e=0;#i;#t=new ArrayBuffer(2**16);#r=new Uint8Array(this.#t);#o=0;constructor(r){super(),this.#i=r}#a(r){let e=this.#t.byteLength;for(;e<r;)e*=2;if(e===this.#t.byteLength)return;let t=new ArrayBuffer(e),s=new Uint8Array(t);s.set(this.#r,0),this.#t=t,this.#r=s}write(r){this.#a(this.#e+r.byteLength),this.#r.set(r,this.#e),this.#e+=r.byteLength,this.#o=Math.max(this.#o,this.#e)}seek(r){this.#e=r}getPos(){return this.#e}flush(){}finalize(){this.#a(this.#e),this.#i.buffer=this.#t.slice(0,Math.max(this.#o,this.#e))}getSlice(r,e){return this.#r.slice(r,e)}},le=class extends ${#e=0;#i;#t=[];constructor(r){super(),this.#i=r}write(r){this.#t.push({data:r.slice(),start:this.#e}),this.#e+=r.byteLength}seek(r){this.#e=r}getPos(){return this.#e}flush(){if(this.#t.length===0)return;let r=[],e=[...this.#t].sort((t,s)=>t.start-s.start);r.push({start:e[0].start,size:e[0].data.byteLength});for(let t=1;t<e.length;t++){let s=r[r.length-1],o=e[t];o.start<=s.start+s.size?s.size=Math.max(s.size,o.start+o.data.byteLength-s.start):r.push({start:o.start,size:o.data.byteLength})}for(let t of r){t.data=new Uint8Array(t.size);for(let s of this.#t)t.start<=s.start&&s.start<t.start+t.size&&t.data.set(s.data,s.start-t.start);this.#i.options.onData?.(t.data,t.start)}this.#t.length=0}finalize(){}},Jt=2**24,er=2,K=class extends ${#e=0;#i;#t;#r=[];constructor(r){if(super(),this.#i=r,this.#t=r.options?.chunkSize??Jt,!Number.isInteger(this.#t)||this.#t<2**10)throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.")}write(r){this.#o(r,this.#e),this.#n(),this.#e+=r.byteLength}seek(r){this.#e=r}getPos(){return this.#e}#o(r,e){let t=this.#r.findIndex(u=>u.start<=e&&e<u.start+this.#t);t===-1&&(t=this.#c(e));let s=this.#r[t],o=e-s.start,n=r.subarray(0,Math.min(this.#t-o,r.byteLength));s.data.set(n,o);let a={start:o,end:o+n.byteLength};if(this.#a(s,a),s.written[0].start===0&&s.written[0].end===this.#t&&(s.shouldFlush=!0),this.#r.length>er){for(let u=0;u<this.#r.length-1;u++)this.#r[u].shouldFlush=!0;this.#n()}n.byteLength<r.byteLength&&this.#o(r.subarray(n.byteLength),e+n.byteLength)}#a(r,e){let t=0,s=r.written.length-1,o=-1;for(;t<=s;){let n=Math.floor(t+(s-t+1)/2);r.written[n].start<=e.start?(t=n+1,o=n):s=n-1}for(r.written.splice(o+1,0,e),(o===-1||r.written[o].end<e.start)&&o++;o<r.written.length-1&&r.written[o].end>=r.written[o+1].start;)r.written[o].end=Math.max(r.written[o].end,r.written[o+1].end),r.written.splice(o+1,1)}#c(r){let t={start:Math.floor(r/this.#t)*this.#t,data:new Uint8Array(this.#t),written:[],shouldFlush:!1};return this.#r.push(t),this.#r.sort((s,o)=>s.start-o.start),this.#r.indexOf(t)}#n(r=!1){for(let e=0;e<this.#r.length;e++){let t=this.#r[e];if(!(!t.shouldFlush&&!r)){for(let s of t.written)this.#i.options.onData?.(t.data.subarray(s.start,s.end),t.start+s.start);this.#r.splice(e--,1)}}}flush(){}finalize(){this.#n(!0)}},ce=class extends K{constructor(r){super(new G({onData:(e,t)=>r.stream.write({type:"write",data:e,position:t}),chunkSize:r.options?.chunkSize}))}};var R=class{constructor(){this.output=null}},X=class extends R{constructor(){super(...arguments);this.buffer=null}createWriter(){return new ue(this)}},G=class extends R{constructor(e){super();this.options=e;if(typeof e!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(e.onData){if(typeof e.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(e.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}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.")}createWriter(){return this.options.chunked?new K(this):new le(this)}},ke=class extends R{constructor(e,t){super();this.stream=e;this.options=t;if(!(e instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(t!==void 0&&typeof t!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(t&&t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}createWriter(){return new ce(this)}};var ne=1e3,tr=2082844800,w=(i,r,e=!0)=>{let t=i*r;return e?Math.round(t):t},de=class extends _{constructor(e,t){super(e);this.timestampsMustStartAtZero=!0;this.#r=new X;this.#o=this.#r.createWriter();this.#a=new Q(this.#o);this.#c=null;this.#n=null;this.#s=[];this.#d=Math.floor(Date.now()/1e3)+tr;this.#u=[];this.#l=1;this.#e=e.writer,this.#i=new Q(this.#e),this.#t=t}#e;#i;#t;#r;#o;#a;#c;#n;#s;#d;#u;#l;start(){let e=this.output.tracks.some(t=>t.type==="video"&&t.source.codec==="avc");if(this.#i.writeBox(Qe({holdsAvc:e,fragmented:this.#t.options.fastStart==="fragmented"})),this.#c=this.#e.getPos(),this.#t.options.fastStart==="in-memory")this.#n=ae(!1);else if(this.#t.options.fastStart!=="fragmented"){if(typeof this.#t.options.fastStart=="object"){let t=this.#h();this.#e.seek(this.#e.getPos()+t)}this.#n=ae(!0),this.#i.writeBox(this.#n)}this.#e.flush()}#h(){c(typeof this.#t.options.fastStart=="object");let e=0,t=[this.#t.options.fastStart.expectedVideoChunks,this.#t.options.fastStart.expectedAudioChunks];for(let s of t)s&&(e+=8*Math.ceil(2/3*s),e+=4*s,e+=12*Math.ceil(2/3*s),e+=4*s,e+=8*s);return e+=4096,e}#T(e,t){let s=this.#s.find(n=>n.track===e);if(s)return s;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.#s.push(o),this.#s.sort((n,a)=>n.track.id-a.track.id),o}#C(e,t){let s=this.#s.find(n=>n.track===e);if(s)return s;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.#s.push(o),this.#s.sort((n,a)=>n.track.id-a.track.id),o}#w(e,t){let s=this.#s.find(n=>n.track===e);if(s)return s;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.#s.push(o),this.#s.sort((n,a)=>n.track.id-a.track.id),this.validateAndNormalizeTimestamp(e,0,!0),o}addEncodedVideoChunk(e,t,s){let o=this.#T(e,s);if(typeof this.#t.options.fastStart=="object"&&o.samples.length===this.#t.options.fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${this.#t.options.fastStart.expectedVideoChunks}).`);let n=new Uint8Array(t.byteLength);t.copyTo(n);let a=this.validateAndNormalizeTimestamp(o.track,t.timestamp,t.type==="key"),u=this.#b(o,n,a,(t.duration??0)/1e6,t.type);this.#t.options.fastStart==="fragmented"?(o.sampleQueue.push(u),this.#p()):this.#m(o,u)}addEncodedAudioChunk(e,t,s){let o=this.#C(e,s);if(typeof this.#t.options.fastStart=="object"&&o.samples.length===this.#t.options.fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${this.#t.options.fastStart.expectedAudioChunks}).`);let n=new Uint8Array(t.byteLength);t.copyTo(n);let a=this.validateAndNormalizeTimestamp(o.track,t.timestamp,t.type==="key"),u=this.#b(o,n,a,(t.duration??0)/1e6,t.type);this.#t.options.fastStart==="fragmented"?(o.sampleQueue.push(u),this.#p()):this.#m(o,u)}addSubtitleCue(e,t,s){let o=this.#w(e,s);this.validateAndNormalizeTimestamp(o.track,1e6*t.timestamp,!0),e.source.codec==="webvtt"&&(o.cueQueue.push(t),this.#g(o,t.timestamp))}#g(e,t){for(;e.cueQueue.length>0;){let s=new Set([]);for(let d of e.cueQueue)c(d.timestamp<=t),c(e.lastCueEndTimestamp<=d.timestamp+d.duration),s.add(Math.max(d.timestamp,e.lastCueEndTimestamp)),s.add(d.timestamp+d.duration);let o=[...s].sort((d,f)=>d-f),n=o[0],a=o[1]??n;if(t<a)break;if(e.lastCueEndTimestamp<n){this.#o.seek(0);let d=Ge();this.#a.writeBox(d);let f=this.#o.getSlice(0,this.#o.getPos()),C=this.#b(e,f,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");this.#t.options.fastStart==="fragmented"?(e.sampleQueue.push(C),this.#p()):this.#m(e,C),e.lastCueEndTimestamp=n}this.#o.seek(0);for(let d=0;d<e.cueQueue.length;d++){let f=e.cueQueue[d];if(f.timestamp>=a)break;I.lastIndex=0;let C=I.test(f.text),v=f.timestamp+f.duration,k=e.cueToSourceId.get(f);if(k===void 0&&a<v&&(k=e.nextSourceId++,e.cueToSourceId.set(f,k)),f.notes){let U=je(f.notes);this.#a.writeBox(U)}let S=Xe(f.text,C?n:null,f.identifier??null,f.settings??null,k??null);this.#a.writeBox(S),v===a&&e.cueQueue.splice(d--,1)}let u=this.#o.getSlice(0,this.#o.getPos()),m=this.#b(e,u,n,a-n,"key");this.#t.options.fastStart==="fragmented"?(e.sampleQueue.push(m),this.#p()):this.#m(e,m),e.lastCueEndTimestamp=a}}#b(e,t,s,o,n){return{timestamp:s,decodeTimestamp:s,duration:o,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:w(o,e.timescale)}}#f(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 n=w(o.timestamp-o.decodeTimestamp,e.timescale),a=w(o.duration,e.timescale);if(e.lastTimescaleUnits!==null){c(e.lastSample);let u=w(o.decodeTimestamp,e.timescale,!1),m=Math.round(u-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=m,e.lastSample.timescaleUnitsToNextSample=m,this.#t.options.fastStart!=="fragmented"){let d=P(e.timeToSampleTable);if(c(d),d.sampleCount===1){d.sampleDelta=m;let C=e.timeToSampleTable[e.timeToSampleTable.length-2];C&&C.sampleDelta===m&&(C.sampleCount++,e.timeToSampleTable.pop(),d=C)}else d.sampleDelta!==m&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:m}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let f=P(e.compositionTimeOffsetTable);c(f),f.sampleCompositionTimeOffset===n?f.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=0,this.#t.options.fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=o}e.timestampProcessingQueue.length=0}#m(e,t){t.type==="key"&&this.#f(e),this.#t.options.fastStart!=="fragmented"&&e.samples.push(t);let s=!1;if(!e.currentChunk)s=!0;else{let o=t.timestamp-e.currentChunk.startTimestamp;if(this.#t.options.fastStart==="fragmented"){let n=this.#s.every(a=>{if(e===a)return t.type==="key";let u=a.sampleQueue[0];return u&&u.type==="key"});o>=1&&n&&(s=!0,this.#S())}else s=o>=.5}s&&(e.currentChunk&&this.#x(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),c(e.currentChunk),e.currentChunk.samples.push(t),e.timestampProcessingQueue.push(t)}#x(e){if(c(this.#t.options.fastStart!=="fragmented"),!!e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),this.#u.push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||P(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),this.#t.options.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.#e.getPos();for(let t of e.currentChunk.samples)c(t.data),this.#e.write(t.data),t.data=null;this.#e.flush()}}#p(){c(this.#t.options.fastStart==="fragmented");for(let e of this.output.tracks)if(!e.source.closed&&!this.#s.some(t=>t.track===e))return;e:for(;;){let e=null,t=1/0;for(let o of this.#s){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();this.#m(e,s)}}#S(e=!0){c(this.#t.options.fastStart==="fragmented");let t=this.#l++;if(t===1){let u=H(this.#s,this.#d,!0);this.#i.writeBox(u)}let s=this.#e.getPos(),o=ge(t,this.#s);this.#i.writeBox(o);{let u=ae(!1),m=0;for(let f of this.#s){c(f.currentChunk);for(let C of f.currentChunk.samples)m+=C.size}let d=this.#i.measureBox(u)+m;d>=2**32&&(u.largeSize=!0,d=this.#i.measureBox(u)+m),u.size=d,this.#i.writeBox(u)}for(let u of this.#s){u.currentChunk.offset=this.#e.getPos(),u.currentChunk.moofOffset=s;for(let m of u.currentChunk.samples)this.#e.write(m.data),m.data=null}let n=this.#e.getPos();this.#e.seek(this.#i.offsets.get(o));let a=ge(t,this.#s);this.#i.writeBox(a),this.#e.seek(n);for(let u of this.#s)u.finalizedChunks.push(u.currentChunk),this.#u.push(u.currentChunk),u.currentChunk=null;e&&this.#e.flush()}onTrackClose(e){if(e.type==="subtitle"&&e.source.codec==="webvtt"){let t=this.#s.find(s=>s.track===e);t&&this.#g(t,1/0)}this.#t.options.fastStart==="fragmented"&&this.#p()}finalize(){for(let e of this.#s)e.type==="subtitle"&&e.track.source.codec==="webvtt"&&this.#g(e,1/0);if(this.#t.options.fastStart==="fragmented"){for(let e of this.#s){for(let t of e.sampleQueue)this.#m(e,t);this.#f(e)}this.#S(!1)}else for(let e of this.#s)this.#f(e),this.#x(e);if(this.#t.options.fastStart==="in-memory"){c(this.#n);let e;for(let s=0;s<2;s++){let o=H(this.#s,this.#d),n=this.#i.measureBox(o);e=this.#i.measureBox(this.#n);let a=this.#e.getPos()+n+e;for(let u of this.#u){u.offset=a;for(let{data:m}of u.samples)c(m),a+=m.byteLength,e+=m.byteLength}if(a<2**32)break;e>=2**32&&(this.#n.largeSize=!0)}let t=H(this.#s,this.#d);this.#i.writeBox(t),this.#n.size=e,this.#i.writeBox(this.#n);for(let s of this.#u)for(let o of s.samples)c(o.data),this.#e.write(o.data),o.data=null}else if(this.#t.options.fastStart==="fragmented"){let e=this.#e.getPos(),t=Ke(this.#s);this.#i.writeBox(t);let s=this.#e.getPos()-e;this.#e.seek(this.#e.getPos()-4),this.#i.writeU32(s)}else{c(this.#n),c(this.#c!==null);let e=this.#i.offsets.get(this.#n);c(e!==void 0);let t=this.#e.getPos()-e;this.#n.size=t,this.#n.largeSize=t>=2**32,this.#i.patchBox(this.#n);let s=H(this.#s,this.#d);if(typeof this.#t.options.fastStart=="object"){this.#e.seek(this.#c),this.#i.writeBox(s);let o=e-this.#e.getPos();this.#i.writeBox(He(o))}else this.#i.writeBox(s)}}};var j=class{constructor(r){this.value=r}},B=class{constructor(r){this.value=r}},L=class{constructor(r){this.value=r}};var xe=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Se=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,Le=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML VINT size not supported "+i)};var ye=2**15,qe="https://github.com/Vanilagy/webm-muxer",Ye=6,Ze=5,rr={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"},ir={video:1,audio:2,subtitle:17},me=class extends _{constructor(e,t){super(e);this.timestampsMustStartAtZero=!0;this.#t=new Uint8Array(8);this.#r=new DataView(this.#t.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap;this.#o=[];this.#a=null;this.#c=null;this.#n=null;this.#s=null;this.#d=null;this.#u=null;this.#l=null;this.#h=null;this.#T=new Set;this.#C=0;this.#e=e.writer,this.#i=t}#e;#i;#t;#r;#o;#a;#c;#n;#s;#d;#u;#l;#h;#T;#C;#w(e){this.#r.setUint8(0,e),this.#e.write(this.#t.subarray(0,1))}#g(e){this.#r.setFloat32(0,e,!1),this.#e.write(this.#t.subarray(0,4))}#b(e){this.#r.setFloat64(0,e,!1),this.#e.write(this.#t)}#f(e,t=xe(e)){let s=0;switch(t){case 6:this.#r.setUint8(s++,e/2**40|0);case 5:this.#r.setUint8(s++,e/2**32|0);case 4:this.#r.setUint8(s++,e>>24);case 3:this.#r.setUint8(s++,e>>16);case 2:this.#r.setUint8(s++,e>>8);case 1:this.#r.setUint8(s++,e);break;default:throw new Error("Bad UINT size "+t)}this.#e.write(this.#t.subarray(0,s))}#m(e,t=Se(e)){e<0&&(e+=2**(t*8)),this.#f(e,t)}writeEBMLVarInt(e,t=Le(e)){let s=0;switch(t){case 1:this.#r.setUint8(s++,128|e);break;case 2:this.#r.setUint8(s++,64|e>>8),this.#r.setUint8(s++,e);break;case 3:this.#r.setUint8(s++,32|e>>16),this.#r.setUint8(s++,e>>8),this.#r.setUint8(s++,e);break;case 4:this.#r.setUint8(s++,16|e>>24),this.#r.setUint8(s++,e>>16),this.#r.setUint8(s++,e>>8),this.#r.setUint8(s++,e);break;case 5:this.#r.setUint8(s++,8|e/2**32&7),this.#r.setUint8(s++,e>>24),this.#r.setUint8(s++,e>>16),this.#r.setUint8(s++,e>>8),this.#r.setUint8(s++,e);break;case 6:this.#r.setUint8(s++,4|e/2**40&3),this.#r.setUint8(s++,e/2**32|0),this.#r.setUint8(s++,e>>24),this.#r.setUint8(s++,e>>16),this.#r.setUint8(s++,e>>8),this.#r.setUint8(s++,e);break;default:throw new Error("Bad EBML VINT size "+t)}this.#e.write(this.#t.subarray(0,s))}#x(e){this.#e.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.#e.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.#e.getPos()),this.#f(e.id),Array.isArray(e.data)){let t=this.#e.getPos(),s=e.size===-1?1:e.size??4;e.size===-1?this.#w(255):this.#e.seek(this.#e.getPos()+s);let o=this.#e.getPos();if(this.dataOffsets.set(e,o),this.writeEBML(e.data),e.size!==-1){let n=this.#e.getPos()-o,a=this.#e.getPos();this.#e.seek(t),this.writeEBMLVarInt(n,s),this.#e.seek(a)}}else if(typeof e.data=="number"){let t=e.size??xe(e.data);this.writeEBMLVarInt(t),this.#f(e.data,t)}else if(typeof e.data=="string")this.writeEBMLVarInt(e.data.length),this.#x(e.data);else if(e.data instanceof Uint8Array)this.writeEBMLVarInt(e.data.byteLength,e.size),this.#e.write(e.data);else if(e.data instanceof j)this.writeEBMLVarInt(4),this.#g(e.data.value);else if(e.data instanceof B)this.writeEBMLVarInt(8),this.#b(e.data.value);else if(e.data instanceof L){let t=e.size??Se(e.data.value);this.writeEBMLVarInt(t),this.#m(e.data.value,t)}}}beforeTrackAdd(e){if(this.#i instanceof F)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.")}start(){this.#p(),this.#i.options.streaming||this.#S(),this.#V(),this.#z(),this.#e.flush()}#p(){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.#i instanceof F?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};this.writeEBML(e)}#S(){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.#n=o}#V(){let e={id:17545,data:new B(0)};this.#d=e;let t={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:qe},{id:22337,data:qe},this.#i.options.streaming?null:e]};this.#c=t}#M(){let e={id:374648427,data:[]};this.#s=e;for(let t of this.#o)e.data.push({id:174,data:[{id:215,data:t.track.id},{id:29637,data:t.track.id},{id:131,data:ir[t.type]},{id:134,data:rr[t.track.source.codec]},...t.type==="video"?[t.info.decoderConfig.description?{id:25506,data:E(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 re(s)?{id:21936,data:[{id:21937,data:te[s.matrix]},{id:21946,data:ee[s.transfer]},{id:21947,data:J[s.primaries]},{id:21945,data:[1,2][Number(s.fullRange)]}]}:null}return null})()]}]:[],...t.type==="audio"?[t.info.decoderConfig.description?{id:25506,data:E(t.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new j(t.info.sampleRate)},{id:159,data:t.info.numberOfChannels}]}]:[],...t.type==="subtitle"?[{id:25506,data:y.encode(t.info.config.description)}]:[]]})}#E(){let e={id:408125543,size:this.#i.options.streaming?-1:Ye,data:[this.#i.options.streaming?null:this.#n,this.#c,this.#s]};this.#a=e,this.writeEBML(e)}#z(){this.#u={id:475249515,data:[]}}get#k(){return c(this.#a),this.dataOffsets.get(this.#a)}#U(e,t){let s=this.#o.find(n=>n.track===e);if(s)return s;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.#o.push(o),this.#o.sort((n,a)=>n.track.id-a.track.id),o}#P(e,t){let s=this.#o.find(n=>n.track===e);if(s)return s;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.#o.push(o),this.#o.sort((n,a)=>n.track.id-a.track.id),o}#I(e,t){let s=this.#o.find(n=>n.track===e);if(s)return s;c(t),c(t.config);let o={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.#o.push(o),this.#o.sort((n,a)=>n.track.id-a.track.id),o}addEncodedVideoChunk(e,t,s){let o=this.#U(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let a=this.validateAndNormalizeTimestamp(o.track,t.timestamp,t.type==="key"),u=this.#A(n,a,(t.duration??0)/1e6,t.type);e.source.codec==="vp9"&&this.#_(o,u),o.chunkQueue.push(u),this.#y()}addEncodedAudioChunk(e,t,s){let o=this.#P(e,s),n=new Uint8Array(t.byteLength);t.copyTo(n);let a=this.validateAndNormalizeTimestamp(o.track,t.timestamp,t.type==="key"),u=this.#A(n,a,(t.duration??0)/1e6,t.type);o.chunkQueue.push(u),this.#y()}addSubtitleCue(e,t,s){let o=this.#I(e,s),n=this.validateAndNormalizeTimestamp(o.track,1e6*t.timestamp,!0),a=t.text,u=Math.floor(n*1e3);I.lastIndex=0,a=a.replace(I,C=>{let k=se(C.slice(1,-1))-u;return`<${oe(k)}>`});let m=y.encode(a),d=`${t.settings??""}
|
|
${t.identifier??""}
|
|
${t.notes??""}`,f=this.#A(m,n,t.duration,"key",d.trim()?y.encode(d):null);o.chunkQueue.push(f),this.#y()}#y(){for(let e of this.output.tracks)if(!e.source.closed&&!this.#o.some(t=>t.track===e))return;e:for(;;){let e=null,t=1/0;for(let o of this.#o){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.#O(e,s)}this.#e.flush()}#_(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 n=M(t.data,s+0,s+1);if(s++,n)return;let a=M(t.data,s+0,s+1);if(s++,a!==0)return;s+=2;let u=M(t.data,s+0,s+24);if(s+=24,u!==4817730)return;o>=2&&s++;let m={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];_e(t.data,s+0,s+3,m)}#A(e,t,s,o,n=null){return{data:e,type:o,timestamp:t,duration:s,additions:n}}#O(e,t){this.#a||(this.#M(),this.#E());let s=Math.floor(1e3*t.timestamp),o=this.#o.every(f=>{if(f.track.source.closed)return!0;if(e===f)return t.type==="key";let C=f.chunkQueue[0];return C&&C.type==="key"});(!this.#l||o&&s-this.#h>=1e3)&&this.#R(s);let n=s-this.#h;if(n<0)return;if(n>=ye)throw new Error(`Current Matroska cluster exceeded its maximum allowed length of ${ye} milliseconds. In order to produce a correct WebM file, you must pass in a key frame at least every ${ye} milliseconds.`);let u=new Uint8Array(4),m=new DataView(u.buffer);m.setUint8(0,128|e.track.id),m.setInt16(1,n,!1);let d=Math.floor(1e3*t.duration);if(d===0&&!t.additions){m.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 L(e.lastWrittenMsTimestamp-s)}:null,t.additions?{id:30113,data:[{id:166,data:[{id:165,data:t.additions},{id:238,data:1}]}]}:null,d>0?{id:155,data:d}:null]};this.writeEBML(f)}this.#C=Math.max(this.#C,s+d),e.lastWrittenMsTimestamp=s,this.#T.add(e)}#R(e){this.#l&&!this.#i.options.streaming&&this.#v(),this.#l={id:524531317,size:this.#i.options.streaming?-1:Ze,data:[{id:231,data:e}]},this.writeEBML(this.#l),this.#h=e,this.#T.clear()}#v(){c(this.#l);let e=this.#e.getPos()-this.dataOffsets.get(this.#l),t=this.#e.getPos();this.#e.seek(this.offsets.get(this.#l)+4),this.writeEBMLVarInt(e,Ze),this.#e.seek(t);let s=this.offsets.get(this.#l)-this.#k;c(this.#u),this.#u.data.push({id:187,data:[{id:179,data:this.#h},...[...this.#T].map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:s}]}))]})}onTrackClose(){this.#y()}finalize(){for(let e of this.#o)for(;e.chunkQueue.length>0;)this.#O(e,e.chunkQueue.shift());if(this.#i.options.streaming||this.#v(),c(this.#u),this.writeEBML(this.#u),!this.#i.options.streaming){let e=this.#e.getPos(),t=this.#e.getPos()-this.#k;this.#e.seek(this.offsets.get(this.#a)+4),this.writeEBMLVarInt(t,Ye),this.#d.data=new B(this.#C),this.#e.seek(this.offsets.get(this.#d)),this.writeEBML(this.#d),this.#n.data[0].data[1].data=this.offsets.get(this.#u)-this.#k,this.#n.data[1].data[1].data=this.offsets.get(this.#c)-this.#k,this.#n.data[2].data[1].data=this.offsets.get(this.#s)-this.#k,this.#e.seek(this.offsets.get(this.#n)),this.writeEBML(this.#n),this.#e.seek(e)}}};var fe=class{},we=class extends fe{constructor(e){super();this.options=e}createMuxer(e){return new de(e,this)}},pe=class extends fe{constructor(e={}){super();this.options=e}createMuxer(e){return new me(e,this)}},F=class extends pe{};var Je=(i,r,e)=>{if(i==="avc"){let t=100;r<=768&&e<=432?t=66:r<=1920&&e<=1080&&(t=77);let s=0,o=r>1920||e>1080?50:41,n=t.toString(16).padStart(2,"0"),a=s.toString(16).padStart(2,"0"),u=o.toString(16).padStart(2,"0");return`avc1.${n}${a}${u}`}else if(i==="hevc"){let t=0,s=1,o=Array(32).fill(0);o[s]=1;let n=parseInt(o.reverse().join(""),2).toString(16).replace(/^0+/,""),a="L",u=120;return r<=1280&&e<=720?u=93:r<=1920&&e<=1080?u=120:r<=3840&&e<=2160?u=150:(a="H",u=180),`hev1.${t===0?"":String.fromCharCode(65+t-1)}${s}.${n}.${a}${u}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let t="00",s;return r<=854&&e<=480?s="21":r<=1280&&e<=720?s="31":r<=1920&&e<=1080?s="41":r<=3840&&e<=2160?s="51":s="61",`vp09.${t}.${s}.08`}else if(i==="av1"){let s;return r<=854&&e<=480?s="01":r<=1280&&e<=720?s="03":r<=1920&&e<=1080?s="04":r<=3840&&e<=2160?s="07":s="09",`av01.0.${s}M.08`}}throw new Error(`Unhandled codec '${i}'.`)},et=(i,r,e)=>{if(i==="aac")return r>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";throw new Error(`Unhandled codec '${i}'.`)};var q=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)}},D=class extends q{constructor(e){super();this.connectedTrack=null;this.codec=e}},Ae=class extends D{constructor(r){super(r)}digest(r,e){this.ensureValidDigest(),this.connectedTrack?.output.muxer.addEncodedVideoChunk(this.connectedTrack,r,e)}},sr=5,Y=class{constructor(r,e){this.source=r;this.codecConfig=e;this.encoder=null;this.lastMultipleOfKeyFrameInterval=-1}digest(r){this.source.ensureValidDigest(),this.ensureEncoder(r),c(this.encoder);let e=Math.floor(r.timestamp/1e6/sr);this.encoder.encode(r,{keyFrame:e!==this.lastMultipleOfKeyFrameInterval}),this.lastMultipleOfKeyFrameInterval=e}ensureEncoder(r){this.encoder||(this.encoder=new VideoEncoder({output:(e,t)=>this.source.connectedTrack?.output.muxer.addEncodedVideoChunk(this.source.connectedTrack,e,t),error:e=>console.error(e)}),this.encoder.configure({codec:Je(this.codecConfig.codec,r.codedWidth,r.codedHeight),width:r.codedWidth,height:r.codedHeight,bitrate:this.codecConfig.bitrate,framerate:this.source.connectedTrack?.metadata.frameRate,latencyMode:this.codecConfig.latencyMode}))}async flush(){return this.encoder?.flush()}},Oe=class extends D{constructor(r){super(r.codec),this.encoder=new Y(this,r)}digest(r){this.encoder.digest(r)}flush(){return this.encoder.flush()}},ve=class extends D{constructor(e,t){super(t.codec);this.canvas=e;this.encoder=new Y(this,t)}digest(e,t=0){let s=new VideoFrame(this.canvas,{timestamp:Math.round(1e6*e),duration:Math.round(1e6*t),alpha:"discard"});this.encoder.digest(s),s.close()}flush(){return this.encoder.flush()}},Ve=class extends D{constructor(e,t){super(t.codec);this.track=e;this.abortController=null;this.offsetTimestamps=!0;this.encoder=new Y(this,t)}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()}},N=class extends q{constructor(e){super();this.connectedTrack=null;this.codec=e}},Me=class extends N{constructor(r){super(r)}digest(r,e){this.ensureValidDigest(),this.connectedTrack?.output.muxer.addEncodedAudioChunk(this.connectedTrack,r,e)}},Z=class{constructor(r,e){this.source=r;this.codecConfig=e;this.encoder=null}digest(r){this.source.ensureValidDigest(),this.ensureEncoder(r),c(this.encoder),this.encoder.encode(r)}ensureEncoder(r){this.encoder||(this.encoder=new AudioEncoder({output:(e,t)=>this.source.connectedTrack?.output.muxer.addEncodedAudioChunk(this.source.connectedTrack,e,t),error:e=>console.error(e)}),this.encoder.configure({codec:et(this.codecConfig.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},Ee=class extends N{constructor(r){super(r.codec),this.encoder=new Z(this,r)}digest(r){this.encoder.digest(r)}flush(){return this.encoder.flush()}},ze=class extends N{constructor(e){super(e.codec);this.accumulatedFrameCount=0;this.encoder=new Z(this,e)}digest(e){let t=e.numberOfChannels,s=e.sampleRate,o=e.length,n=new Float32Array(t*o);for(let u=0;u<t;u++){let m=e.getChannelData(u);n.set(m,u*o)}let a=new AudioData({format:"f32-planar",sampleRate:s,numberOfFrames:o,numberOfChannels:t,timestamp:Math.round(1e6*this.accumulatedFrameCount/s),data:n});this.encoder.digest(a),a.close(),this.accumulatedFrameCount+=o}flush(){return this.encoder.flush()}},Ue=class extends N{constructor(e,t){super(t.codec);this.track=e;this.abortController=null;this.offsetTimestamps=!0;this.encoder=new Z(this,t)}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()}},Pe=class extends q{constructor(e){super();this.connectedTrack=null;this.codec=e}},Ie=class extends Pe{constructor(r){super(r),this.parser=new ie({codec:r,output:(e,t)=>this.connectedTrack?.output.muxer.addSubtitleCue(this.connectedTrack,e,t),error:e=>console.error(e)})}digest(r){this.ensureValidDigest(),this.parser.parse(r)}};export{X as ArrayBufferTarget,ze as AudioBufferSource,Ee as AudioDataSource,ve as CanvasSource,Me as EncodedAudioChunkSource,Ae as EncodedVideoChunkSource,ke as FileSystemWritableFileStreamTarget,Ue as MediaStreamAudioTrackSource,Ve as MediaStreamVideoTrackSource,pe as MkvOutputFormat,we as Mp4OutputFormat,he as Output,G as StreamTarget,R as Target,Ie as TextSubtitleSource,Oe as VideoFrameSource,F as WebMOutputFormat};
|