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