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