Files
mediabunny/dist/metamuxer.min.js
T
2024-11-10 17:08:04 +01:00

3 lines
38 KiB
JavaScript

"use strict";var Metamuxer=(()=>{var de=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var Be=(i,s)=>{for(var e in s)de(i,e,{get:s[e],enumerable:!0})},Ie=(i,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of Fe(s))!_e.call(i,r)&&r!==e&&de(i,r,{get:()=>s[r],enumerable:!(t=De(s,r))||t.enumerable});return i};var Ne=i=>Ie(de({},"__esModule",{value:!0}),i);var _t={};Be(_t,{ArrayBufferTarget:()=>ue,AudioBufferSource:()=>Y,AudioDataSource:()=>X,CanvasSource:()=>K,FileSystemWritableFileStreamTarget:()=>le,MediaStreamAudioTrackSource:()=>L,MediaStreamVideoTrackSource:()=>q,MkvOutputFormat:()=>H,Mp4OutputFormat:()=>se,Output:()=>Z,StreamTarget:()=>_,Target:()=>M,VideoFrameSource:()=>j,WebMOutputFormat:()=>U});var ge=(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"),a=r.toString(16).padStart(2,"0"),u=n.toString(16).padStart(2,"0");return`avc1.${o}${a}${u}`}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+/,""),a="L",u=120;return s<=1280&&e<=720?u=93:s<=1920&&e<=1080?u=120:s<=3840&&e<=2160?u=150:(a="H",u=180),`hev1.${t===0?"":String.fromCharCode(65+t-1)}${r}.${o}.${a}${u}.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}'.`)},Te=(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 P=i=>i&&i[i.length-1],O=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],a=7-(r&7),u=(o&1<<a)>>a;t<<=1,t|=u}return t},ke=(i,s,e,t)=>{for(let r=s;r<e;r++){let n=Math.floor(r/8),o=i[n],a=7-(r&7);o&=~(1<<a),o|=(t&1<<e-r-1)>>e-r-1<<a,i[n]=o}},E=i=>i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength);var V=class{constructor(s,e){this.connectedTrack=null;this.codec=s,this.metadata=e}ensureNotFinalizing(){if(this.connectedTrack?.output.finalizing)throw new Error("Cannot call digest after output has started finalizing.")}start(){}async flush(){}},B=class{constructor(s,e){this.connectedTrack=null;this.codec=s,this.metadata=e}ensureNotFinalizing(){if(this.connectedTrack?.output.finalizing)throw new Error("Cannot call digest after output has started finalizing.")}start(){}async flush(){}};var We=5,I=class{constructor(s,e){this.source=s;this.codecConfig=e;this.encoder=null;this.lastMultipleOfKeyFrameInterval=-1}digest(s){this.source.ensureNotFinalizing(),this.ensureEncoder(s),d(this.encoder);let e=Math.floor(s.timestamp/1e6/We);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:ge(this.codecConfig.codec,s.codedWidth,s.codedHeight),width:s.codedWidth,height:s.codedHeight,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},j=class extends V{constructor(s,e={}){super(s.codec,e),this.encoder=new I(this,s)}digest(s){this.encoder.digest(s)}flush(){return this.encoder.flush()}},K=class extends V{constructor(e,t,r={}){super(t.codec,r);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()}},q=class extends V{constructor(e,t,r={}){super(t.codec,r);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()}};var N=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:Te(this.codecConfig.codec,s.numberOfChannels,s.sampleRate),numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},X=class extends B{constructor(s,e={}){super(s.codec,e),this.encoder=new N(this,s)}digest(s){this.encoder.digest(s)}flush(){return this.encoder.flush()}},Y=class extends B{constructor(e,t={}){super(e.codec,t);this.accumulatedFrameCount=0;this.encoder=new N(this,e)}digest(e){let t=e.numberOfChannels,r=e.sampleRate,n=e.length,o=new Float32Array(t*n);for(let u=0;u<t;u++){let c=e.getChannelData(u);o.set(c,u*n)}let a=new AudioData({format:"f32-planar",sampleRate:r,numberOfFrames:n,numberOfChannels:t,timestamp:Math.round(1e6*this.accumulatedFrameCount/r),data:o});this.encoder.digest(a),a.close(),this.accumulatedFrameCount+=n}flush(){return this.encoder.flush()}},L=class extends B{constructor(e,t,r={}){super(t.codec,r);this.track=e;this.abortController=null;this.encoder=new N(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 Z=class{constructor(s){this.tracks=[];this.started=!1;this.finalizing=!1;this.writer=s.target.createWriter(),this.muxer=s.format.createMuxer(this)}addTrack(s){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 e={id:this.tracks.length+1,output:this,type:s instanceof V?"video":"audio",source:s};this.muxer.beforeTrackAdd(e),this.tracks.push(e),s.connectedTrack=e}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 f=new Uint8Array(8),y=new DataView(f.buffer),b=i=>[(i%256+256)%256],h=i=>(y.setUint16(0,i,!1),[f[0],f[1]]),Re=i=>(y.setInt16(0,i,!1),[f[0],f[1]]),ye=i=>(y.setUint32(0,i,!1),[f[1],f[2],f[3]]),l=i=>(y.setUint32(0,i,!1),[f[0],f[1],f[2],f[3]]),He=i=>(y.setInt32(0,i,!1),[f[0],f[1],f[2],f[3]]),z=i=>(y.setUint32(0,Math.floor(i/2**32),!1),y.setUint32(4,i,!1),[f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7]]),fe=i=>(y.setInt16(0,2**8*i,!1),[f[0],f[1]]),x=i=>(y.setInt32(0,2**16*i,!1),[f[0],f[1],f[2],f[3]]),ce=i=>(y.setInt32(0,2**30*i,!1),[f[0],f[1],f[2],f[3]]),T=(i,s=!1)=>{let e=Array(i.length).fill(null).map((t,r)=>i.charCodeAt(r));return s&&e.push(0),e},he=i=>{let s=null;for(let e of i)(!s||e.presentationTimestamp>s.presentationTimestamp)&&(s=e);return s},we=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]},Se=we(0),Ae=i=>[x(i[0]),x(i[1]),ce(i[2]),x(i[3]),x(i[4]),ce(i[5]),x(i[6]),x(i[7]),ce(i[8])],p=(i,s,e)=>({type:i,contents:s&&new Uint8Array(s.flat(10)),children:e}),m=(i,s,e,t,r)=>p(i,[b(s),ye(e),t??[]],r),Oe=i=>{let s=512;return i.fragmented?p("ftyp",[T("iso5"),l(s),T("iso5"),T("iso6"),T("mp41")]):p("ftyp",[T("isom"),l(s),T("isom"),i.holdsAvc?T("avc1"):[],T("mp41")])},ee=i=>({type:"mdat",largeSize:i}),ve=i=>({type:"free",size:i}),W=(i,s,e=!1)=>p("moov",void 0,[$e(s,i),...i.map(t=>Qe(t,s)),e?bt(i):null]),$e=(i,s)=>{let e=k(Math.max(0,...s.filter(o=>o.samples.length>0).map(o=>{let a=he(o.samples);return a.presentationTimestamp+a.duration})),J),t=Math.max(...s.map(o=>o.track.id))+1,r=!O(i)||!O(e),n=r?z:l;return m("mvhd",+r,0,[n(i),n(i),l(J),n(e),x(1),fe(1),Array(10).fill(0),Ae(Se),Array(24).fill(0),l(t)])},Qe=(i,s)=>p("trak",void 0,[Ge(i,s),je(i,s)]),Ge=(i,s)=>{let e=he(i.samples),t=k(e?e.presentationTimestamp+e.duration:0,J),r=!O(s)||!O(t),n=r?z:l,o;if(i.type==="video"){let a=i.track.source.metadata.rotation;o=a===void 0||typeof a=="number"?we(a??0):a}else o=Se;return m("tkhd",+r,3,[n(s),n(s),l(i.track.id),l(0),n(t),Array(8).fill(0),h(0),h(0),fe(i.type==="audio"?1:0),h(0),Ae(o),x(i.type==="video"?i.info.width:0),x(i.type==="video"?i.info.height:0)])},je=(i,s)=>p("mdia",void 0,[Ke(i,s),qe(i.type==="video"?"vide":"soun"),Xe(i)]),Ke=(i,s)=>{let e=he(i.samples),t=k(e?e.presentationTimestamp+e.duration:0,i.timescale),r=!O(s)||!O(t),n=r?z:l;return m("mdhd",+r,0,[n(s),n(s),l(i.timescale),n(t),h(21956),h(0)])},qe=i=>m("hdlr",0,0,[T("mhlr"),T(i),l(0),l(0),l(0),T("mp4-muxer-hdlr",!0)]),Xe=i=>p("minf",void 0,[i.type==="video"?Ye():Le(),Ze(),tt(i)]),Ye=()=>m("vmhd",0,1,[h(0),h(0),h(0),h(0)]),Le=()=>m("smhd",0,0,[h(0),h(0)]),Ze=()=>p("dinf",void 0,[Je()]),Je=()=>m("dref",0,0,[l(1)],[et()]),et=()=>m("url ",0,1),tt=i=>{let s=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return p("stbl",void 0,[rt(i),dt(i),ct(i),ft(i),ht(i),mt(i),s?pt(i):null])},rt=i=>m("stsd",0,0,[l(1)],[i.type==="video"?it(At[i.track.source.codec],i):at(vt[i.track.source.codec],i)]),it=(i,s)=>p(i,[Array(6).fill(0),h(1),h(0),h(0),Array(12).fill(0),h(s.info.width),h(s.info.height),l(4718592),l(4718592),l(0),h(1),Array(32).fill(0),h(24),Re(65535)],[Ot[s.track.source.codec](s)]),st=i=>i.info.decoderConfig&&p("avcC",[...E(i.info.decoderConfig.description)]),nt=i=>i.info.decoderConfig&&p("hvcC",[...E(i.info.decoderConfig.description)]),xe=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]),a=(Number(e[3])<<4)+(0<<1)+Number(s.colorSpace.fullRange);return m("vpcC",1,0,[b(t),b(r),b(a),b(2),b(2),b(2),h(0)])},ot=()=>{let e=(1<<7)+1;return p("av1C",[e,0,0,0])},at=(i,s)=>p(i,[Array(6).fill(0),h(1),h(0),h(0),l(0),h(s.info.numberOfChannels),h(16),h(0),h(0),x(s.info.sampleRate)],[Vt[s.track.source.codec](s)]),ut=i=>{let s=E(i.info.decoderConfig.description??new ArrayBuffer(0));return m("esds",0,0,[l(58753152),b(32+s.byteLength),h(1),b(0),l(75530368),b(18+s.byteLength),b(64),b(21),ye(0),l(130071),l(130071),l(92307584),b(s.byteLength),...s,l(109084800),b(1),b(2)])},lt=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),h(s),l(i.info.sampleRate),fe(e),b(0)])},dt=i=>m("stts",0,0,[l(i.timeToSampleTable.length),i.timeToSampleTable.map(s=>[l(s.sampleCount),l(s.sampleDelta)])]),ct=i=>{if(i.samples.every(e=>e.type==="key"))return null;let s=[...i.samples.entries()].filter(([,e])=>e.type==="key");return m("stss",0,0,[l(s.length),s.map(([e])=>l(e+1))])},ft=i=>m("stsc",0,0,[l(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(s=>[l(s.firstChunk),l(s.samplesPerChunk),l(1)])]),ht=i=>m("stsz",0,0,[l(0),l(i.samples.length),i.samples.map(s=>l(s.size))]),mt=i=>i.finalizedChunks.length>0&&P(i.finalizedChunks).offset>=2**32?m("co64",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(s=>z(s.offset))]):m("stco",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(s=>l(s.offset))]),pt=i=>m("ctts",0,0,[l(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(s=>[l(s.sampleCount),l(s.sampleCompositionTimeOffset)])]),bt=i=>p("mvex",void 0,i.map(Ct)),Ct=i=>m("trex",0,0,[l(i.track.id),l(1),l(0),l(0),l(0)]),me=(i,s)=>p("moof",void 0,[gt(i),...s.map(Tt)]),gt=i=>m("mfhd",0,0,[l(i)]),Ve=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},Tt=i=>p("traf",void 0,[kt(i),xt(i),yt(i)]),kt=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:Ve(e)};return m("tfhd",0,s,[l(i.track.id),l(t.duration),l(t.size),l(t.flags)])},xt=i=>(d(i.currentChunk),m("tfdt",1,0,[z(k(i.currentChunk.startTimestamp,i.timescale))])),yt=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(Ve),r=i.currentChunk.samples.map(w=>k(w.presentationTimestamp-w.decodeTimestamp,i.timescale)),n=new Set(s),o=new Set(e),a=new Set(t),u=new Set(r),c=a.size===2&&t[0]!==t[1],C=n.size>1,g=o.size>1,S=!c&&a.size>1,Ce=u.size>1||[...u].some(w=>w!==0),A=0;return A|=1,A|=4*+c,A|=256*+C,A|=512*+g,A|=1024*+S,A|=2048*+Ce,m("trun",1,A,[l(i.currentChunk.samples.length),l(i.currentChunk.offset-i.currentChunk.moofOffset||0),c?l(t[0]):[],i.currentChunk.samples.map((w,G)=>[C?l(s[G]):[],g?l(e[G]):[],S?l(t[G]):[],Ce?He(r[G]):[]])])},ze=i=>p("mfra",void 0,[...i.map(wt),St()]),wt=(i,s)=>m("tfra",1,0,[l(i.track.id),l(63),l(i.finalizedChunks.length),i.finalizedChunks.map(t=>[z(k(t.startTimestamp,i.timescale)),z(t.moofOffset),l(s+1),l(1),l(1)])]),St=()=>m("mfro",0,0,[l(0)]),At={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},Ot={avc:st,hevc:nt,vp8:xe,vp9:xe,av1:ot},vt={aac:"mp4a",opus:"Opus"},Vt={aac:ut,opus:lt};var D=class{constructor(s){this.output=s}beforeTrackAdd(s){}};var J=1e3,zt=2082844800,k=(i,s,e=!0)=>{let t=i*s;return e?Math.round(t):t},te=class extends D{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)+zt;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(Oe({holdsAvc:e,fragmented:this.#r.options.fastStart==="fragmented"})),this.#o=this.#e.getPos(),this.#r.options.fastStart==="in-memory")this.#n=ee(!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=ee(!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(a=>a.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.source.metadata.frameRate??57600,samples:[],sampleQueue:[],firstDecodeTimestamp:null,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.#s.push(o),this.#s.sort((a,u)=>a.track.id-u.track.id),o}#h(e,t,r){let n=this.#s.find(a=>a.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:[],firstDecodeTimestamp:null,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.#s.push(o),this.#s.sort((a,u)=>a.track.id-u.track.id),o}addEncodedVideoChunk(e,t,r,n){let o=this.#u(e,t,r);if(typeof this.#r.options.fastStart=="object"&&o.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 a=this.#m(o,t,n);this.#r.options.fastStart==="fragmented"?(o.sampleQueue.push(a),this.#g()):this.#c(o,a)}addEncodedAudioChunk(e,t,r){let n=this.#h(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.#m(n,t);this.#r.options.fastStart==="fragmented"?(n.sampleQueue.push(o),this.#g()):this.#c(n,o)}#m(e,t,r){let n=t.timestamp/1e6,o=(t.timestamp-(r??0))/1e6,a=(t.duration??0)/1e6,u=this.#T(e,n,o);n=u.presentationTimestamp,o=u.decodeTimestamp;let c=new Uint8Array(t.byteLength);return t.copyTo(c),{presentationTimestamp:n,decodeTimestamp:o,duration:a,data:c,size:c.byteLength,type:t.type,timescaleUnitsToNextSample:k(a,e.timescale)}}#c(e,t){this.#r.options.fastStart!=="fragmented"&&e.samples.push(t);let r=k(t.presentationTimestamp-t.decodeTimestamp,e.timescale);if(e.lastTimescaleUnits!==null){d(e.lastSample);let o=k(t.decodeTimestamp,e.timescale,!1),a=Math.round(o-e.lastTimescaleUnits);if(e.lastTimescaleUnits+=a,e.lastSample.timescaleUnitsToNextSample=a,this.#r.options.fastStart!=="fragmented"){let u=P(e.timeToSampleTable);d(u),u.sampleCount===1?(u.sampleDelta=a,u.sampleCount++):u.sampleDelta===a?u.sampleCount++:(u.sampleCount--,e.timeToSampleTable.push({sampleCount:2,sampleDelta:a}));let c=P(e.compositionTimeOffsetTable);d(c),c.sampleCompositionTimeOffset===r?c.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:r})}}else e.lastTimescaleUnits=0,this.#r.options.fastStart!=="fragmented"&&(e.timeToSampleTable.push({sampleCount:1,sampleDelta:k(t.duration,e.timescale)}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:r}));e.lastSample=t;let n=!1;if(!e.currentChunk)n=!0;else{let o=t.presentationTimestamp-e.currentChunk.startTimestamp;if(this.#r.options.fastStart==="fragmented"){let a=this.#s.every(u=>{if(e===u)return t.type==="key";let c=u.sampleQueue[0];return c&&c.type==="key"});o>=1&&a&&(n=!0,this.#p())}else n=o>=.5}n&&(e.currentChunk&&this.#C(e),e.currentChunk={startTimestamp:t.presentationTimestamp,samples:[],offset:null,moofOffset:null}),d(e.currentChunk),e.currentChunk.samples.push(t)}#T(e,t,r){if(r<0)throw new Error(`Timestamps must be non-negative (got ${r}s).`);if(e.firstDecodeTimestamp===null&&(e.firstDecodeTimestamp=r),r-=e.firstDecodeTimestamp,t-=e.firstDecodeTimestamp,r<e.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (timestamp went from ${e.lastDecodeTimestamp}s to ${r}s).`);return e.lastDecodeTimestamp=r,{presentationTimestamp:t,decodeTimestamp:r}}#C(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||P(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()}}#g(){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].decodeTimestamp<t&&(e=n,t=n.sampleQueue[0].decodeTimestamp)}if(!e)break;let r=e.sampleQueue.shift();this.#c(e,r)}}#p(e=!0){d(this.#r.options.fastStart==="fragmented");let t=this.#f++;if(t===1){let u=W(this.#s,this.#a,!0);this.writeBox(u)}let r=this.#e.getPos(),n=me(t,this.#s);this.writeBox(n);{let u=ee(!1),c=0;for(let g of this.#s){d(g.currentChunk);for(let S of g.currentChunk.samples)c+=S.size}let C=this.measureBox(u)+c;C>=2**32&&(u.largeSize=!0,C=this.measureBox(u)+c),u.size=C,this.writeBox(u)}for(let u of this.#s){u.currentChunk.offset=this.#e.getPos(),u.currentChunk.moofOffset=r;for(let c of u.currentChunk.samples)this.#e.write(c.data),c.data=null}let o=this.#e.getPos();this.#e.seek(this.offsets.get(n));let a=me(t,this.#s);this.writeBox(a),this.#e.seek(o);for(let u of this.#s)u.finalizedChunks.push(u.currentChunk),this.#l.push(u.currentChunk),u.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.#c(e,t);this.#p(!1)}else for(let e of this.#s)this.#C(e);if(this.#r.options.fastStart==="in-memory"){d(this.#n);let e;for(let r=0;r<2;r++){let n=W(this.#s,this.#a),o=this.measureBox(n);e=this.measureBox(this.#n);let a=this.#e.getPos()+o+e;for(let u of this.#l){u.offset=a;for(let{data:c}of u.samples)d(c),a+=c.byteLength,e+=c.byteLength}if(a<2**32)break;e>=2**32&&(this.#n.largeSize=!0)}let t=W(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=ze(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=W(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(ve(n))}else this.writeBox(r)}}};var R=class{constructor(s){this.value=s}},F=class{constructor(s){this.value=s}};var pe=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Ue=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 Ut=1,Mt=2,be=2**15,Me="https://github.com/Vanilagy/webm-muxer",Pe=6,Ee=5,Pt={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"},re=class extends D{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.#h=null;this.#m=new Set;this.#c=0;this.#e=e.writer,this.#r=t}#e;#r;#i;#t;#o;#n;#s;#a;#l;#f;#d;#u;#h;#m;#c;#T(e){this.#t.setUint8(0,e),this.#e.write(this.#i.subarray(0,1))}#C(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)}#p(e,t=pe(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))}writeEBMLVarInt(e,t=Ue(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))}#S(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.#p(e.id),Array.isArray(e.data)){let t=this.#e.getPos(),r=e.size===-1?1:e.size??4;e.size===-1?this.#T(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,a=this.#e.getPos();this.#e.seek(t),this.writeEBMLVarInt(o,r),this.#e.seek(a)}}else if(typeof e.data=="number"){let t=e.size??pe(e.data);this.writeEBMLVarInt(t),this.#p(e.data,t)}else typeof e.data=="string"?(this.writeEBMLVarInt(e.data.length),this.#S(e.data)):e.data instanceof Uint8Array?(this.writeEBMLVarInt(e.data.byteLength,e.size),this.#e.write(e.data)):e.data instanceof R?(this.writeEBMLVarInt(4),this.#C(e.data.value)):e.data instanceof F&&(this.writeEBMLVarInt(8),this.#g(e.data.value))}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.#A(),this.#r.options.streaming||this.#O(),this.#v(),this.#U(),this.#e.flush()}#A(){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)}#O(){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 F(0)};this.#f=e;let t={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Me},{id:22337,data:Me},this.#r.options.streaming?null:e]};this.#s=t}#V(){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"?Ut:Mt},{id:134,data:Pt[t.track.source.codec]},t.info.decoderConfig.description?{id:25506,data:E(t.info.decoderConfig.description)}:null,...t.type==="video"?[t.track.source.metadata.frameRate?{id:2352003,data:1e9/t.track.source.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}]}]:[]]})}#z(){let e={id:408125543,size:this.#r.options.streaming?-1:Pe,data:[this.#r.options.streaming?null:this.#a,this.#s,this.#l]};this.#n=e,this.writeEBML(e)}#U(){this.#d={id:475249515,data:[]}}get#b(){return d(this.#n),this.dataOffsets.get(this.#n)}#M(e,t,r){let n=this.#o.find(a=>a.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,lastTimestamp:null,lastWrittenTimestamp:null};return this.#o.push(o),this.#o.sort((a,u)=>a.track.id-u.track.id),o}#P(e,t,r){let n=this.#o.find(a=>a.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,lastTimestamp:null,lastWrittenTimestamp:null};return this.#o.push(o),this.#o.sort((a,u)=>a.track.id-u.track.id),o}addEncodedVideoChunk(e,t,r,n){let o=this.#M(e,t,r),a=this.#x(o,t);e.source.codec==="vp9"&&this.#E(o,a),o.lastTimestamp=a.timestamp,o.chunkQueue.push(a),this.#k(),this.#e.flush()}addEncodedAudioChunk(e,t,r){let n=this.#P(e,t,r),o=this.#x(n,t);n.lastTimestamp=o.timestamp,n.chunkQueue.push(o),this.#k(),this.#e.flush()}#k(){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.#y(e,r)}}#E(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 a=v(t.data,r+0,r+1);if(r++,a!==0)return;r+=2;let u=v(t.data,r+0,r+24);if(r+=24,u!==4817730)return;n>=2&&r++;let c={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];ke(t.data,r+0,r+3,c)}#x(e,t){let r=this.#D(e,t.timestamp),n=new Uint8Array(t.byteLength);return t.copyTo(n),{data:n,type:t.type,timestamp:r,duration:t.duration,additions:null}}#D(e,t){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(e.firstTimestamp===null&&(e.firstTimestamp=t),t-=e.firstTimestamp,e.lastTimestamp!==null&&t<e.lastTimestamp)throw new Error(`Timestamps must be monotonically increasing (timestamp went from ${e.lastTimestamp}s to ${t}s).`);return t}#y(e,t){this.#n||(this.#V(),this.#z());let r=Math.floor(t.timestamp/1e3),n=this.#o.every(g=>{if(e===g)return t.type==="key";let S=g.chunkQueue[0];return S&&S.type==="key"});(!this.#u||n&&r-this.#h>=1e3)&&this.#F(r);let o=r-this.#h;if(o<0)return;if(o>=be)throw new Error(`Current Matroska cluster exceeded its maximum allowed length of ${be} milliseconds. In order to produce a correct WebM file, you must pass in a key frame at least every ${be} milliseconds.`);let u=new Uint8Array(4),c=new DataView(u.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,o,!1);let C=Math.floor((t.duration??0)/1e3);if(C===0&&!t.additions){c.setUint8(3,+(t.type==="key")<<7);let g={id:163,data:[u,t.data]};this.writeEBML(g)}else{let g={id:160,data:[{id:161,data:[u,t.data]},t.type==="delta"?{id:251,data: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.#m.add(e)}#F(e){this.#u&&!this.#r.options.streaming&&this.#w(),this.#u={id:524531317,size:this.#r.options.streaming?-1:Ee,data:[{id:231,data:e}]},this.writeEBML(this.#u),this.#h=e,this.#m.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,Ee),this.#e.seek(t);let r=this.offsets.get(this.#u)-this.#b;d(this.#d),this.#d.data.push({id:187,data:[{id:179,data:this.#h},...[...this.#m].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.#y(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.#b;this.#e.seek(this.offsets.get(this.#n)+4),this.writeEBMLVarInt(t,Pe),this.#f.data=new F(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.#b,this.#a.data[1].data[1].data=this.offsets.get(this.#s)-this.#b,this.#a.data[2].data[1].data=this.offsets.get(this.#l)-this.#b,this.#e.seek(this.offsets.get(this.#a)),this.writeEBML(this.#a),this.#e.seek(e)}}};var ie=class{},se=class extends ie{constructor(e){super();this.options=e}createMuxer(e){return new te(e,this)}},H=class extends ie{constructor(e={}){super();this.options=e}createMuxer(e){return new re(e,this)}},U=class extends H{};var $=class{},ne=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))}},oe=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(){}},Et=2**24,Dt=2,Q=class extends ${#e=0;#r;#i;#t=[];constructor(s){if(super(),this.#r=s,this.#i=s.options?.chunkSize??Et,!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(u=>u.start<=e&&e<u.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 a={start:n,end:n+o.byteLength};if(this.#n(r,a),r.written[0].start===0&&r.written[0].end===this.#i&&(r.shouldFlush=!0),this.#t.length>Dt){for(let u=0;u<this.#t.length-1;u++)this.#t[u].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)}},ae=class extends Q{constructor(s){super(new _({onData:(e,t)=>s.stream.write({type:"write",data:e,position:t}),chunkSize:s.options?.chunkSize}))}};var Ft=Symbol("isTarget");Ft;var M=class{},ue=class extends M{constructor(){super(...arguments);this.buffer=null}createWriter(){return new ne(this)}},_=class extends M{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 Q(this):new oe(this)}},le=class extends M{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 ae(this)}};return Ne(_t);})();
if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Metamuxer)