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