function d(i){if(!i)throw new Error("Assertion failed.")}var B=i=>i&&i[i.length-1],V=i=>i>=0&&i<2**32,I=(i,t,e)=>{let r=0;for(let o=t;o>a;r<<=1,r|=u}return r},$e=(i,t,e,r)=>{for(let o=t;o>e-o-1<i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),x=new TextEncoder,N={bt709:1,bt470bg:5,smpte170m:6},D={bt709:1,smpte170m:6,"iec61966-2-1":13},F={rgb:0,bt709:1,bt470bg:5,smpte170m:6},ae=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,we=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i)&&!(i instanceof DataView);var X=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,lt=/^WEBVTT(.|\n)*?\n{2}/,W=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ue=class{#e;#r=null;#i=!1;constructor(t){this.#e=t}parse(t){t=t.replaceAll(`\r `,` `).replaceAll("\r",` `),X.lastIndex=0;let e;if(!this.#r){if(!lt.test(t)){let o=new Error("WebVTT preamble incorrect.");throw this.#e.error(o),o}e=X.exec(t);let r=t.slice(0,e?.index??t.length).trimEnd();if(!r){let o=new Error("No WebVTT preamble provided.");throw this.#e.error(o),o}this.#r=r,e&&(t=t.slice(e.index),X.lastIndex=0)}for(;e=X.exec(t);){let r=t.slice(0,e.index),o=e[1],s=e.index+e[0].length,n=t.indexOf(` `,s)+1,a=t.slice(s,n).trim(),u=t.indexOf(` `,s);u===-1&&(u=t.length);let f=le(e[2]),m=le(e[3])-f,g=t.slice(n,u).trim();t=t.slice(u).trimStart(),X.lastIndex=0;let v={timestamp:f/1e3,duration:m/1e3,text:g,identifier:o,settings:a,notes:r},y={};this.#i||(y.config={description:this.#r},this.#i=!0),this.#e.output(v,y)}}},dt=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,le=i=>{let t=dt.exec(i);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},de=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),o=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+o.toString().padStart(3,"0")};var G=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e[(i%256+256)%256],p=i=>(_.setUint16(0,i,!1),[h[0],h[1]]),ct=i=>(_.setInt16(0,i,!1),[h[0],h[1]]),Qe=i=>(_.setUint32(0,i,!1),[h[1],h[2],h[3]]),l=i=>(_.setUint32(0,i,!1),[h[0],h[1],h[2],h[3]]),Ke=i=>(_.setInt32(0,i,!1),[h[0],h[1],h[2],h[3]]),z=i=>(_.setUint32(0,Math.floor(i/2**32),!1),_.setUint32(4,i,!1),[h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7]]),Se=i=>(_.setInt16(0,2**8*i,!1),[h[0],h[1]]),A=i=>(_.setInt32(0,2**16*i,!1),[h[0],h[1],h[2],h[3]]),ke=i=>(_.setInt32(0,2**30*i,!1),[h[0],h[1],h[2],h[3]]),xe=(i,t)=>{let e=[],r=i;do{let o=r&127;r>>=7,e.length>0&&(o|=128),e.push(o),t!==void 0&&t--}while(r>0||t);return e.reverse()},w=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,o)=>i.charCodeAt(o));return t&&e.push(0),e},Ae=i=>{let t=null;for(let e of i)(!t||e.timestamp>t.timestamp)&&(t=e);return t},Le=i=>{let t=i*(Math.PI/180),e=Math.cos(t),r=Math.sin(t);return[e,r,0,-r,e,0,0,0,1]},Xe=Le(0),Ge=i=>[A(i[0]),A(i[1]),ke(i[2]),A(i[3]),A(i[4]),ke(i[5]),A(i[6]),A(i[7]),ke(i[8])],b=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),T=(i,t,e,r,o)=>b(i,[C(t),Qe(e),r??[]],o),qe=i=>{let t=512;return i.fragmented?b("ftyp",[w("iso5"),l(t),w("iso5"),w("iso6"),w("mp41")]):b("ftyp",[w("isom"),l(t),w("isom"),i.holdsAvc?w("avc1"):[],w("mp41")])},fe=i=>({type:"mdat",largeSize:i}),Ye=i=>({type:"free",size:i}),q=(i,t,e=!1)=>b("moov",void 0,[ft(t,i),...i.map(r=>mt(r,t)),e?Kt(i):null]),ft=(i,t)=>{let e=S(Math.max(0,...t.filter(n=>n.samples.length>0).map(n=>{let a=Ae(n.samples);return a.timestamp+a.duration})),ce),r=Math.max(0,...t.map(n=>n.track.id))+1,o=!V(i)||!V(e),s=o?z:l;return T("mvhd",+o,0,[s(i),s(i),l(ce),s(e),A(1),Se(1),Array(10).fill(0),Ge(Xe),Array(24).fill(0),l(r)])},mt=(i,t)=>b("trak",void 0,[ht(i,t),pt(i,t)]),ht=(i,t)=>{let e=Ae(i.samples),r=S(e?e.timestamp+e.duration:0,ce),o=!V(t)||!V(r),s=o?z:l,n;if(i.type==="video"){let a=i.track.metadata.rotation;n=a===void 0||typeof a=="number"?Le(a??0):a}else n=Xe;return T("tkhd",+o,3,[s(t),s(t),l(i.track.id),l(0),s(r),Array(8).fill(0),p(0),p(i.track.id),Se(i.type==="audio"?1:0),p(0),Ge(n),A(i.type==="video"?i.info.width:0),A(i.type==="video"?i.info.height:0)])},pt=(i,t)=>b("mdia",void 0,[bt(i,t),Ct(i),yt(i)]),bt=(i,t)=>{let e=Ae(i.samples),r=S(e?e.timestamp+e.duration:0,i.timescale),o=!V(t)||!V(r),s=o?z:l;return T("mdhd",+o,0,[s(t),s(t),l(i.timescale),s(r),p(21956),p(0)])},Tt={video:"vide",audio:"soun",subtitle:"text"},gt={video:"VideoHandler",audio:"SoundHandler",subtitle:"TextHandler"},Ct=i=>T("hdlr",0,0,[w("mhlr"),w(Tt[i.type]),l(0),l(0),l(0),w(gt[i.type],!0)]),yt=i=>b("minf",void 0,[St[i.type](),At(),Ot(i)]),wt=()=>T("vmhd",0,1,[p(0),p(0),p(0),p(0)]),kt=()=>T("smhd",0,0,[p(0),p(0)]),xt=()=>T("nmhd",0,0),St={video:wt,audio:kt,subtitle:xt},At=()=>b("dinf",void 0,[_t()]),_t=()=>T("dref",0,0,[l(1)],[Et()]),Et=()=>T("url ",0,1),Ot=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return b("stbl",void 0,[vt(i),Ft(i),Wt(i),Ht(i),$t(i),jt(i),t?Qt(i):null])},vt=i=>{let t;return i.type==="video"?t=Mt(tr[i.track.source._codec],i):i.type==="audio"?t=Pt(ir[i.track.source._codec],i):i.type==="subtitle"&&(t=Nt(sr[i.track.source._codec],i)),d(t),T("stsd",0,0,[l(1)],[t])},Mt=(i,t)=>b(i,[Array(6).fill(0),p(1),p(0),p(0),Array(12).fill(0),p(t.info.width),p(t.info.height),l(4718592),l(4718592),l(0),p(1),Array(32).fill(0),p(24),ct(65535)],[rr[t.track.source._codec](t),ae(t.info.decoderConfig.colorSpace)?Vt(t):null]),Vt=i=>b("colr",[w("nclx"),p(N[i.info.decoderConfig.colorSpace.primaries]),p(D[i.info.decoderConfig.colorSpace.transfer]),p(F[i.info.decoderConfig.colorSpace.matrix]),C((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),It=i=>i.info.decoderConfig&&b("avcC",[...U(i.info.decoderConfig.description)]),Ut=i=>i.info.decoderConfig&&b("hvcC",[...U(i.info.decoderConfig.description)]),je=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig;d(t.colorSpace);let e=t.codec.split("."),r=Number(e[1]),o=Number(e[2]),a=(Number(e[3])<<4)+(0<<1)+Number(t.colorSpace.fullRange);return T("vpcC",1,0,[C(r),C(o),C(a),C(2),C(2),C(2),p(0)])},zt=()=>{let e=(1<<7)+1;return b("av1C",[e,0,0,0])},Pt=(i,t)=>b(i,[Array(6).fill(0),p(1),p(0),p(0),l(0),p(t.info.numberOfChannels),p(16),p(0),p(0),A(t.info.sampleRate)],[or[t.track.source._codec](t)]),Rt=i=>{let e=[...U(i.info.decoderConfig.description??new ArrayBuffer(0))];return e=[...C(64),...C(21),...Qe(0),...l(0),...l(0),...C(5),...xe(e.length),...e],e=[...p(1),...C(0),...C(4),...xe(e.length),...e,...C(6),...C(1),...C(2)],e=[...C(3),...xe(e.length),...e],T("esds",0,0,e)},Bt=i=>{let t=3840,e=0,r=i.info.decoderConfig?.description;if(r){d(r.byteLength<18);let o=ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r);t=o.getUint16(10,!0),e=o.getInt16(14,!0)}return b("dOps",[C(0),C(i.info.numberOfChannels),p(t),l(i.info.sampleRate),Se(e),C(0)])},Nt=(i,t)=>b(i,[Array(6).fill(0),p(1)],[nr[t.track.source._codec](t)]),Dt=i=>b("vttC",[...x.encode(i.info.config.description)]);var Ft=i=>T("stts",0,0,[l(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[l(t.sampleCount),l(t.sampleDelta)])]),Wt=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return T("stss",0,0,[l(t.length),t.map(([e])=>l(e+1))])},Ht=i=>T("stsc",0,0,[l(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[l(t.firstChunk),l(t.samplesPerChunk),l(1)])]),$t=i=>T("stsz",0,0,[l(0),l(i.samples.length),i.samples.map(t=>l(t.size))]),jt=i=>i.finalizedChunks.length>0&&B(i.finalizedChunks).offset>=2**32?T("co64",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(t=>z(t.offset))]):T("stco",0,0,[l(i.finalizedChunks.length),i.finalizedChunks.map(t=>l(t.offset))]),Qt=i=>T("ctts",0,0,[l(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[l(t.sampleCount),l(t.sampleCompositionTimeOffset)])]),Kt=i=>b("mvex",void 0,i.map(Lt)),Lt=i=>T("trex",0,0,[l(i.track.id),l(1),l(0),l(0),l(0)]),_e=(i,t)=>b("moof",void 0,[Xt(i),...t.map(Gt)]),Xt=i=>T("mfhd",0,0,[l(i)]),Ze=i=>{let t=0,e=0,r=0,o=0,s=i.type==="delta";return e|=+s,s?t|=1:t|=2,t<<24|e<<16|r<<8|o},Gt=i=>b("traf",void 0,[qt(i),Yt(i),Zt(i)]),qt=i=>{d(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Ze(e)};return T("tfhd",0,t,[l(i.track.id),l(r.duration),l(r.size),l(r.flags)])},Yt=i=>(d(i.currentChunk),T("tfdt",1,0,[z(S(i.currentChunk.startTimestamp,i.timescale))])),Zt=i=>{d(i.currentChunk);let t=i.currentChunk.samples.map(k=>k.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(k=>k.size),r=i.currentChunk.samples.map(Ze),o=i.currentChunk.samples.map(k=>S(k.timestamp-k.decodeTimestamp,i.timescale)),s=new Set(t),n=new Set(e),a=new Set(r),u=new Set(o),f=a.size===2&&r[0]!==r[1],c=s.size>1,m=n.size>1,g=!f&&a.size>1,v=u.size>1||[...u].some(k=>k!==0),y=0;return y|=1,y|=4*+f,y|=256*+c,y|=512*+m,y|=1024*+g,y|=2048*+v,T("trun",1,y,[l(i.currentChunk.samples.length),l(i.currentChunk.offset-i.currentChunk.moofOffset||0),f?l(r[0]):[],i.currentChunk.samples.map((k,R)=>[c?l(t[R]):[],m?l(e[R]):[],g?l(r[R]):[],v?Ke(o[R]):[]])])},Je=i=>b("mfra",void 0,[...i.map(Jt),er()]),Jt=(i,t)=>T("tfra",1,0,[l(i.track.id),l(63),l(i.finalizedChunks.length),i.finalizedChunks.map(r=>[z(S(r.startTimestamp,i.timescale)),z(r.moofOffset),l(t+1),l(1),l(1)])]),er=()=>T("mfro",0,0,[l(0)]),et=()=>b("vtte"),tt=(i,t,e,r,o)=>b("vttc",void 0,[o!==null?b("vsid",[Ke(o)]):null,e!==null?b("iden",[...x.encode(e)]):null,t!==null?b("ctim",[...x.encode(de(t))]):null,r!==null?b("sttg",[...x.encode(r)]):null,b("payl",[...x.encode(i)])]),rt=i=>b("vtta",[...x.encode(i)]),tr={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},rr={avc:It,hevc:Ut,vp8:je,vp9:je,av1:zt},ir={aac:"mp4a",opus:"Opus"},or={aac:Rt,opus:Bt},sr={webvtt:"wvtt"},nr={webvtt:Dt};var H=class{constructor(t){this.trackTimestampInfo=new WeakMap;this.output=t}beforeTrackAdd(t){}onTrackClose(t){}validateAndNormalizeTimestamp(t,e,r){let o=e/1e6,s=this.trackTimestampInfo.get(t);if(!s){if(!r)throw new Error("First frame must be a key frame.");if(this.timestampsMustStartAtZero&&o>0)throw new Error(`Timestamps must start at zero (got ${o}s).`);s={timestampOffset:o,maxTimestamp:t.source._offsetTimestamps?0:o,lastKeyFrameTimestamp:t.source._offsetTimestamps?0:o},this.trackTimestampInfo.set(t,s)}if(t.source._offsetTimestamps&&(o-=s.timestampOffset),o<0)throw new Error(`Timestamps must be non-negative (got ${o}s).`);if(or.start-o.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let r=1;ru.start<=e&&eur){for(let u=0;u=t.written[s+1].start;)t.written[s].end=Math.max(t.written[s].end,t.written[s+1].end),t.written.splice(s+1,1)}#l(t){let r={start:Math.floor(t/this.#i)*this.#i,data:new Uint8Array(this.#i),written:[],shouldFlush:!1};return this.#t.push(r),this.#t.sort((o,s)=>o.start-s.start),this.#t.indexOf(r)}#n(t=!1){for(let e=0;et.stream.write({type:"write",data:e,position:r}),chunkSize:t.options?.chunkSize}))}};var it=(i,t,e)=>{if(i==="avc"){let r=100;t<=768&&e<=432?r=66:t<=1920&&e<=1080&&(r=77);let o=0,s=t>1920||e>1080?50:41,n=r.toString(16).padStart(2,"0"),a=o.toString(16).padStart(2,"0"),u=s.toString(16).padStart(2,"0");return`avc1.${n}${a}${u}`}else if(i==="hevc"){let r=0,o=1,s=Array(32).fill(0);s[o]=1;let n=parseInt(s.reverse().join(""),2).toString(16).replace(/^0+/,""),a="L",u=120;return t<=1280&&e<=720?u=93:t<=1920&&e<=1080?u=120:t<=3840&&e<=2160?u=150:(a="H",u=180),`hev1.${r===0?"":String.fromCharCode(65+r-1)}${o}.${n}.${a}${u}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let r="00",o;return t<=854&&e<=480?o="21":t<=1280&&e<=720?o="31":t<=1920&&e<=1080?o="41":t<=3840&&e<=2160?o="51":o="61",`vp09.${r}.${o}.08`}else if(i==="av1"){let o;return t<=854&&e<=480?o="01":t<=1280&&e<=720?o="03":t<=1920&&e<=1080?o="04":t<=3840&&e<=2160?o="07":o="09",`av01.0.${o}M.08`}}throw new TypeError(`Unhandled codec '${i}'.`)},ot=(i,t,e)=>{if(i==="aac")return t>=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 TypeError(`Unhandled codec '${i}'.`)},pe=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.description!==void 0&&!we(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=i.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let e=Object.keys(N);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${e.join(", ")}.`);let r=Object.keys(D);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);let o=Object.keys(F);if(t.matrix!=null&&!o.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${o.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if((i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3"))&&!i.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((i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1"))&&!i.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((i.decoderConfig.codec==="vp8"||i.decoderConfig.codec.startsWith("vp09"))&&i.decoderConfig.colorSpace===void 0)throw new TypeError("Video chunk metadata decoder configuration for VP8/VP9 must include a colorSpace.")},be=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!we(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec==="opus"&&i.decoderConfig.description&&i.decoderConfig.description.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.")},Te=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var ce=1e3,lr=2082844800,S=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},ge=class extends H{constructor(e,r){super(e);this.timestampsMustStartAtZero=!0;this.#s=new Y;this.#a=this.#s._createWriter();this.#c=new G(this.#a);this.#l=null;this.#n=null;this.#o=[];this.#d=Math.floor(Date.now()/1e3)+lr;this.#u=[];this.#m=1;this.#e=e._writer,this.#r=new G(this.#e),this.#i=r,this.#t=r.options.fastStart??(this.#e instanceof $?"in-memory":!1),(this.#t==="in-memory"||this.#t==="fragmented")&&(this.#e.ensureMonotonicity=!0)}#e;#r;#i;#t;#s;#a;#c;#l;#n;#o;#d;#u;#m;start(){let e=this.output._tracks.some(r=>r.type==="video"&&r.source._codec==="avc");this.#r.writeBox(qe({holdsAvc:e,fragmented:this.#t==="fragmented"})),this.#l=this.#e.getPos(),this.#t==="in-memory"?this.#n=fe(!1):this.#t==="fragmented"||(this.#n=fe(!0),this.#r.writeBox(this.#n)),this.#e.flush()}#b(e,r){let o=this.#o.find(n=>n.track===e);if(o)return o;pe(r),d(r),d(r.decoderConfig),d(r.decoderConfig.codedWidth!==void 0),d(r.decoderConfig.codedHeight!==void 0);let s={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.#o.push(s),this.#o.sort((n,a)=>n.track.id-a.track.id),s}#T(e,r){let o=this.#o.find(n=>n.track===e);if(o)return o;be(r),d(r),d(r.decoderConfig);let s={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.#o.push(s),this.#o.sort((n,a)=>n.track.id-a.track.id),s}#A(e,r){let o=this.#o.find(n=>n.track===e);if(o)return o;Te(r),d(r),d(r.config);let s={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.#o.push(s),this.#o.sort((n,a)=>n.track.id-a.track.id),this.validateAndNormalizeTimestamp(e,0,!0),s}addEncodedVideoChunk(e,r,o){let s=this.#b(e,o),n=new Uint8Array(r.byteLength);r.copyTo(n);let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.#h(s,n,a,(r.duration??0)/1e6,r.type);this.#p(s,u)}addEncodedAudioChunk(e,r,o){let s=this.#T(e,o),n=new Uint8Array(r.byteLength);r.copyTo(n);let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.#h(s,n,a,(r.duration??0)/1e6,r.type);this.#p(s,u)}addSubtitleCue(e,r,o){let s=this.#A(e,o);this.validateAndNormalizeTimestamp(s.track,1e6*r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),this.#g(s,r.timestamp))}#g(e,r){for(;e.cueQueue.length>0;){let o=new Set([]);for(let c of e.cueQueue)d(c.timestamp<=r),d(e.lastCueEndTimestamp<=c.timestamp+c.duration),o.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),o.add(c.timestamp+c.duration);let s=[...o].sort((c,m)=>c-m),n=s[0],a=s[1]??n;if(r=a)break;W.lastIndex=0;let g=W.test(m.text),v=m.timestamp+m.duration,y=e.cueToSourceId.get(m);if(y===void 0&&ao.timestamp).sort((o,s)=>o-s);for(let o=0;o{if(e===a)return r.type==="key";let u=a.sampleQueue[0];return u&&u.type==="key"});s>=1&&n&&(o=!0,this.#x())}else o=s>=.5}o&&(e.currentChunk&&this.#w(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),d(e.currentChunk),e.currentChunk.samples.push(r),e.timestampProcessingQueue.push(r)}#w(e){if(d(this.#t!=="fragmented"),!!e.currentChunk){if(e.finalizedChunks.push(e.currentChunk),this.#u.push(e.currentChunk),(e.compactlyCodedChunkTable.length===0||B(e.compactlyCodedChunkTable).samplesPerChunk!==e.currentChunk.samples.length)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:e.currentChunk.samples.length}),this.#t==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.#e.getPos();for(let r of e.currentChunk.samples)d(r.data),this.#e.write(r.data),r.data=null;this.#e.flush()}}#k(){d(this.#t==="fragmented");for(let e of this.output._tracks)if(!e.source._closed&&!this.#o.some(r=>r.track===e))return;e:for(;;){let e=null,r=1/0;for(let s of this.#o){if(s.sampleQueue.length===0&&!s.track.source._closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp=2**32&&(u.largeSize=!0,c=this.#r.measureBox(u)+f),u.size=c,this.#r.writeBox(u)}for(let u of this.#o){u.currentChunk.offset=this.#e.getPos(),u.currentChunk.moofOffset=o;for(let f of u.currentChunk.samples)this.#e.write(f.data),f.data=null}let n=this.#e.getPos();this.#e.seek(this.#r.offsets.get(s));let a=_e(r,this.#o);this.#r.writeBox(a),this.#e.seek(n);for(let u of this.#o)u.finalizedChunks.push(u.currentChunk),this.#u.push(u.currentChunk),u.currentChunk=null;e&&this.#e.flush()}onTrackClose(e){if(e.type==="subtitle"&&e.source._codec==="webvtt"){let r=this.#o.find(o=>o.track===e);r&&this.#g(r,1/0)}this.#t==="fragmented"&&this.#k()}finalize(){for(let e of this.#o)e.type==="subtitle"&&e.track.source._codec==="webvtt"&&this.#g(e,1/0);if(this.#t==="fragmented"){for(let e of this.#o){for(let r of e.sampleQueue)this.#C(e,r);this.#f(e)}this.#x(!1)}else for(let e of this.#o)this.#f(e),this.#w(e);if(this.#t==="in-memory"){d(this.#n);let e;for(let o=0;o<2;o++){let s=q(this.#o,this.#d),n=this.#r.measureBox(s);e=this.#r.measureBox(this.#n);let a=this.#e.getPos()+n+e;for(let u of this.#u){u.offset=a;for(let{data:f}of u.samples)d(f),a+=f.byteLength,e+=f.byteLength}if(a<2**32)break;e>=2**32&&(this.#n.largeSize=!0)}let r=q(this.#o,this.#d);this.#r.writeBox(r),this.#n.size=e,this.#r.writeBox(this.#n);for(let o of this.#u)for(let s of o.samples)d(s.data),this.#e.write(s.data),s.data=null}else if(this.#t==="fragmented"){let e=this.#e.getPos(),r=Je(this.#o);this.#r.writeBox(r);let o=this.#e.getPos()-e;this.#e.seek(this.#e.getPos()-4),this.#r.writeU32(o)}else{d(this.#n),d(this.#l!==null);let e=this.#r.offsets.get(this.#n);d(e!==void 0);let r=this.#e.getPos()-e;this.#n.size=r,this.#n.largeSize=r>=2**32,this.#r.patchBox(this.#n);let o=q(this.#o,this.#d);if(typeof this.#t=="object"){this.#e.seek(this.#l),this.#r.writeBox(o);let s=e-this.#e.getPos();this.#r.writeBox(Ye(s))}else this.#r.writeBox(o)}}};var te=class{constructor(t){this.value=t}},j=class{constructor(t){this.value=t}},re=class{constructor(t){this.value=t}};var Oe=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,ve=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,st=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 Me=2**15,nt="https://github.com/Vanilagy/webm-muxer",at=6,ut=5,dr={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},Ce=class extends H{constructor(e,r){super(e);this.timestampsMustStartAtZero=!1;this.#i=new Uint8Array(8);this.#t=new DataView(this.#i.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap;this.#s=[];this.#a=null;this.#c=null;this.#l=null;this.#n=null;this.#o=null;this.#d=null;this.#u=null;this.#m=null;this.#b=new Set;this.#T=0;this.#e=e._writer,this.#r=r,this.#r.options.streamable&&(this.#e.ensureMonotonicity=!0)}#e;#r;#i;#t;#s;#a;#c;#l;#n;#o;#d;#u;#m;#b;#T;#A(e){this.#t.setUint8(0,e),this.#e.write(this.#i.subarray(0,1))}#g(e){this.#t.setFloat32(0,e,!1),this.#e.write(this.#i.subarray(0,4))}#h(e){this.#t.setFloat64(0,e,!1),this.#e.write(this.#i)}#f(e,r=Oe(e)){let o=0;switch(r){case 6:this.#t.setUint8(o++,e/2**40|0);case 5:this.#t.setUint8(o++,e/2**32|0);case 4:this.#t.setUint8(o++,e>>24);case 3:this.#t.setUint8(o++,e>>16);case 2:this.#t.setUint8(o++,e>>8);case 1:this.#t.setUint8(o++,e);break;default:throw new Error("Bad UINT size "+r)}this.#e.write(this.#i.subarray(0,o))}#p(e,r=ve(e)){e<0&&(e+=2**(r*8)),this.#f(e,r)}writeEBMLVarInt(e,r=st(e)){let o=0;switch(r){case 1:this.#t.setUint8(o++,128|e);break;case 2:this.#t.setUint8(o++,64|e>>8),this.#t.setUint8(o++,e);break;case 3:this.#t.setUint8(o++,32|e>>16),this.#t.setUint8(o++,e>>8),this.#t.setUint8(o++,e);break;case 4:this.#t.setUint8(o++,16|e>>24),this.#t.setUint8(o++,e>>16),this.#t.setUint8(o++,e>>8),this.#t.setUint8(o++,e);break;case 5:this.#t.setUint8(o++,8|e/2**32&7),this.#t.setUint8(o++,e>>24),this.#t.setUint8(o++,e>>16),this.#t.setUint8(o++,e>>8),this.#t.setUint8(o++,e);break;case 6:this.#t.setUint8(o++,4|e/2**40&3),this.#t.setUint8(o++,e/2**32|0),this.#t.setUint8(o++,e>>24),this.#t.setUint8(o++,e>>16),this.#t.setUint8(o++,e>>8),this.#t.setUint8(o++,e);break;default:throw new Error("Bad EBML VINT size "+r)}this.#e.write(this.#i.subarray(0,o))}#C(e){this.#e.write(new Uint8Array(e.split("").map(r=>r.charCodeAt(0))))}writeEBML(e){if(e!==null){if(e instanceof Uint8Array)this.#e.write(e);else if(Array.isArray(e))for(let r of e)this.writeEBML(r);else if(this.offsets.set(e,this.#e.getPos()),this.#f(e.id),Array.isArray(e.data)){let r=this.#e.getPos(),o=e.size===-1?1:e.size??4;e.size===-1?this.#A(255):this.#e.seek(this.#e.getPos()+o);let s=this.#e.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){let n=this.#e.getPos()-s,a=this.#e.getPos();this.#e.seek(r),this.writeEBMLVarInt(n,o),this.#e.seek(a)}}else if(typeof e.data=="number"){let r=e.size??Oe(e.data);this.writeEBMLVarInt(r),this.#f(e.data,r)}else if(typeof e.data=="string")this.writeEBMLVarInt(e.data.length),this.#C(e.data);else if(e.data instanceof Uint8Array)this.writeEBMLVarInt(e.data.byteLength,e.size),this.#e.write(e.data);else if(e.data instanceof te)this.writeEBMLVarInt(4),this.#g(e.data.value);else if(e.data instanceof j)this.writeEBMLVarInt(8),this.#h(e.data.value);else if(e.data instanceof re){let r=e.size??ve(e.data.value);this.writeEBMLVarInt(r),this.#p(e.data.value,r)}}}beforeTrackAdd(e){if(this.#r instanceof Q)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.#w(),this.#r.options.streamable||this.#k(),this.#x(),this.#V(),this.#e.flush()}#w(){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 Q?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};this.writeEBML(e)}#k(){let e=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),o=new Uint8Array([22,84,174,107]),s={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:o},{id:21420,size:5,data:0}]}]};this.#l=s}#x(){let e={id:17545,data:new j(0)};this.#o=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:nt},{id:22337,data:nt},this.#r.options.streamable?null:e]};this.#c=r}#E(){let e={id:374648427,data:[]};this.#n=e;for(let r of this.#s)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:dr[r.track.source._codec]},...r.type==="video"?[r.info.decoderConfig.description?{id:25506,data:U(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 o=r.info.decoderConfig.colorSpace;return ae(o)?{id:21936,data:[{id:21937,data:F[o.matrix]},{id:21946,data:D[o.transfer]},{id:21947,data:N[o.primaries]},{id:21945,data:[1,2][Number(o.fullRange)]}]}:null}return null})()]}]:[],...r.type==="audio"?[r.info.decoderConfig.description?{id:25506,data:U(r.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new te(r.info.sampleRate)},{id:159,data:r.info.numberOfChannels}]}]:[],...r.type==="subtitle"?[{id:25506,data:x.encode(r.info.config.description)}]:[]]})}#O(){let e={id:408125543,size:this.#r.options.streamable?-1:at,data:[this.#r.options.streamable?null:this.#l,this.#c,this.#n]};this.#a=e,this.writeEBML(e)}#V(){this.#d={id:475249515,data:[]}}get#y(){return d(this.#a),this.dataOffsets.get(this.#a)}#I(e,r){let o=this.#s.find(n=>n.track===e);if(o)return o;pe(r),d(r),d(r.decoderConfig),d(r.decoderConfig.codedWidth!==void 0),d(r.decoderConfig.codedHeight!==void 0);let s={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.#s.push(s),this.#s.sort((n,a)=>n.track.id-a.track.id),s}#U(e,r){let o=this.#s.find(n=>n.track===e);if(o)return o;be(r),d(r),d(r.decoderConfig);let s={track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.#s.push(s),this.#s.sort((n,a)=>n.track.id-a.track.id),s}#z(e,r){let o=this.#s.find(n=>n.track===e);if(o)return o;Te(r),d(r),d(r.config);let s={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};return this.#s.push(s),this.#s.sort((n,a)=>n.track.id-a.track.id),s}addEncodedVideoChunk(e,r,o){let s=this.#I(e,o),n=new Uint8Array(r.byteLength);r.copyTo(n);let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.#_(n,a,(r.duration??0)/1e6,r.type);e.source._codec==="vp9"&&this.#P(s,u),s.chunkQueue.push(u),this.#S()}addEncodedAudioChunk(e,r,o){let s=this.#U(e,o),n=new Uint8Array(r.byteLength);r.copyTo(n);let a=this.validateAndNormalizeTimestamp(s.track,r.timestamp,r.type==="key"),u=this.#_(n,a,(r.duration??0)/1e6,r.type);s.chunkQueue.push(u),this.#S()}addSubtitleCue(e,r,o){let s=this.#z(e,o),n=this.validateAndNormalizeTimestamp(s.track,1e6*r.timestamp,!0),a=r.text,u=Math.floor(n*1e3);W.lastIndex=0,a=a.replace(W,g=>{let y=le(g.slice(1,-1))-u;return`<${de(y)}>`});let f=x.encode(a),c=`${r.settings??""} ${r.identifier??""} ${r.notes??""}`,m=this.#_(f,n,r.duration,"key",c.trim()?x.encode(c):null);s.chunkQueue.push(m),this.#S()}#S(){for(let e of this.output._tracks)if(!e.source._closed&&!this.#s.some(r=>r.track===e))return;e:for(;;){let e=null,r=1/0;for(let s of this.#s){if(s.chunkQueue.length===0&&!s.track.source._closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp=2&&o++;let f={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];$e(r.data,o+0,o+3,f)}#_(e,r,o,s,n=null){return{data:e,type:s,timestamp:r,duration:o,additions:n}}#v(e,r){this.#a||(this.#E(),this.#O());let o=Math.floor(1e3*r.timestamp),s=this.#s.every(m=>{if(m.track.source._closed)return!0;if(e===m)return r.type==="key";let g=m.chunkQueue[0];return g&&g.type==="key"});(!this.#u||s&&o-this.#m>=1e3)&&this.#R(o);let n=o-this.#m;if(n<0)return;if(n>=Me)throw new Error(`Current Matroska cluster exceeded its maximum allowed length of ${Me} milliseconds. In order to produce a correct WebM file, you must pass in a key frame at least every ${Me} milliseconds.`);let u=new Uint8Array(4),f=new DataView(u.buffer);f.setUint8(0,128|e.track.id),f.setInt16(1,n,!1);let c=Math.floor(1e3*r.duration);if(c===0&&!r.additions){f.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 re(e.lastWrittenMsTimestamp-o)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:165,data:r.additions},{id:238,data:1}]}]}:null,c>0?{id:155,data:c}:null]};this.writeEBML(m)}this.#T=Math.max(this.#T,o+c),e.lastWrittenMsTimestamp=o,this.#b.add(e)}#R(e){this.#u&&!this.#r.options.streamable&&this.#M(),this.#u={id:524531317,size:this.#r.options.streamable?-1:ut,data:[{id:231,data:e}]},this.writeEBML(this.#u),this.#m=e,this.#b.clear()}#M(){d(this.#u);let e=this.#e.getPos()-this.dataOffsets.get(this.#u),r=this.#e.getPos();this.#e.seek(this.offsets.get(this.#u)+4),this.writeEBMLVarInt(e,ut),this.#e.seek(r);let o=this.offsets.get(this.#u)-this.#y;d(this.#d),this.#d.data.push({id:187,data:[{id:179,data:this.#m},...[...this.#b].map(s=>({id:183,data:[{id:247,data:s.track.id},{id:241,data:o}]}))]})}onTrackClose(){this.#S()}finalize(){this.#a||(this.#E(),this.#O());for(let e of this.#s)for(;e.chunkQueue.length>0;)this.#v(e,e.chunkQueue.shift());if(!this.#r.options.streamable&&this.#u&&this.#M(),d(this.#d),this.writeEBML(this.#d),!this.#r.options.streamable){let e=this.#e.getPos(),r=this.#e.getPos()-this.#y;this.#e.seek(this.offsets.get(this.#a)+4),this.writeEBMLVarInt(r,at),this.#o.data=new j(this.#T),this.#e.seek(this.offsets.get(this.#o)),this.writeEBML(this.#o),this.#l.data[0].data[1].data=this.offsets.get(this.#d)-this.#y,this.#l.data[1].data[1].data=this.offsets.get(this.#c)-this.#y,this.#l.data[2].data[1].data=this.offsets.get(this.#n)-this.#y,this.#e.seek(this.offsets.get(this.#l)),this.writeEBML(this.#l),this.#e.seek(e)}}};var P=class{},Ve=class extends P{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 ge(e,this)}},ye=class extends P{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 Ce(e,this)}},Q=class extends ye{};var ie=["avc","hevc","vp8","vp9","av1"],oe=["aac","opus"],Ie=["webvtt"],K=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)}},E=class extends K{constructor(e){super();this._connectedTrack=null;if(!ie.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ie.join(", ")}.`);this._codec=e}},Ue=class extends E{constructor(t){super(t)}digest(t,e){if(!(t instanceof EncodedVideoChunk))throw new TypeError("chunk must be an EncodedVideoChunk.");this._ensureValidDigest(),this._connectedTrack?.output._muxer.addEncodedVideoChunk(this._connectedTrack,t,e)}},fr=5,mr=i=>{if(!i||typeof i!="object")throw new TypeError("Codec config must be an object.");if(!ie.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${ie.join(", ")}.`);if(!Number.isInteger(i.bitrate)||i.bitrate<=0)throw new TypeError("config.bitrate must be a positive integer.");if(i.latencyMode!==void 0&&["quality","realtime"].includes(i.latencyMode))throw new TypeError("config.latencyMode, when provided, must be 'quality' or 'realtime'.")},se=class{constructor(t,e){this.source=t;this.codecConfig=e;this.encoder=null;this.lastMultipleOfKeyFrameInterval=-1;this.lastWidth=null;this.lastHeight=null;mr(e)}digest(t){if(this.source._ensureValidDigest(),this.lastWidth!==null&&this.lastHeight!==null){if(t.codedWidth!==this.lastWidth||t.codedHeight!==this.lastHeight)throw new Error(`Video frame size must remain constant. Expected ${this.lastWidth}x${this.lastHeight}, got ${t.codedWidth}x${t.codedHeight}.`)}else this.lastWidth=t.codedWidth,this.lastHeight=t.codedHeight;this.ensureEncoder(t),d(this.encoder);let e=Math.floor(t.timestamp/1e6/fr);this.encoder.encode(t,{keyFrame:e!==this.lastMultipleOfKeyFrameInterval}),this.lastMultipleOfKeyFrameInterval=e}ensureEncoder(t){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:it(this.codecConfig.codec,t.codedWidth,t.codedHeight),width:t.codedWidth,height:t.codedHeight,bitrate:this.codecConfig.bitrate,framerate:this.source._connectedTrack?.metadata.frameRate,latencyMode:this.codecConfig.latencyMode}))}async flush(){return this.encoder?.flush()}},ze=class extends E{constructor(t){super(t.codec),this._encoder=new se(this,t)}digest(t){if(!(t instanceof VideoFrame))throw new TypeError("videoFrame must be a VideoFrame.");this._encoder.digest(t)}_flush(){return this._encoder.flush()}},Pe=class extends E{constructor(t,e){if(!(t instanceof HTMLCanvasElement))throw new TypeError("canvas must be an HTMLCanvasElement.");super(e.codec),this._encoder=new se(this,e),this._canvas=t}digest(t,e=0){if(!Number.isFinite(t)||t<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*t),duration:Math.round(1e6*e),alpha:"discard"});this._encoder.digest(r),r.close()}_flush(){return this._encoder.flush()}},Re=class extends E{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 se(this,r),this._track=e}_start(){this._abortController=new AbortController;let e=new MediaStreamTrackProcessor({track:this._track}),r=new WritableStream({write:o=>{this._encoder.digest(o),o.close()}});e.readable.pipeTo(r,{signal:this._abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||console.error("Pipe error:",o)})}async _flush(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flush()}},O=class extends K{constructor(e){super();this._connectedTrack=null;if(!oe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${oe.join(", ")}.`);this._codec=e}},Be=class extends O{constructor(t){super(t)}digest(t,e){if(!(t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedAudioChunk.");this._ensureValidDigest(),this._connectedTrack?.output._muxer.addEncodedAudioChunk(this._connectedTrack,t,e)}},hr=i=>{if(!i||typeof i!="object")throw new TypeError("Codec config must be an object.");if(!oe.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${oe.join(", ")}.`);if(!Number.isInteger(i.bitrate)||i.bitrate<=0)throw new TypeError("config.bitrate must be a positive integer.")},ne=class{constructor(t,e){this.source=t;this.codecConfig=e;this.encoder=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;hr(e)}digest(t){if(this.source._ensureValidDigest(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;this.ensureEncoder(t),d(this.encoder),this.encoder.encode(t)}ensureEncoder(t){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,t.numberOfChannels,t.sampleRate),numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate,bitrate:this.codecConfig.bitrate}))}async flush(){return this.encoder?.flush()}},Ne=class extends O{constructor(t){super(t.codec),this._encoder=new ne(this,t)}digest(t){if(!(t instanceof AudioData))throw new TypeError("audioData must be an AudioData.");this._encoder.digest(t)}_flush(){return this._encoder.flush()}},De=class extends O{constructor(e){super(e.codec);this._accumulatedFrameCount=0;this._encoder=new ne(this,e)}digest(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=e.numberOfChannels,o=e.sampleRate,s=e.length,n=new Float32Array(r*s);for(let u=0;u{this._encoder.digest(o),o.close()}});e.readable.pipeTo(r,{signal:this._abortController.signal}).catch(o=>{o instanceof DOMException&&o.name==="AbortError"||console.error("Pipe error:",o)})}async _flush(){this._abortController&&(this._abortController.abort(),this._abortController=null),await this._encoder.flush()}},L=class extends K{constructor(e){super();this._connectedTrack=null;if(!Ie.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ie.join(", ")}.`);this._codec=e}},We=class extends L{constructor(t){super(t),this._parser=new ue({codec:t,output:(e,r)=>this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,e,r),error:e=>console.error("Subtitle parse error:",e)})}digest(t){if(typeof t!="string")throw new TypeError("text must be a string.");this._ensureValidDigest(),this._parser.parse(t)}};var He=class{constructor(t){this._tracks=[];this._started=!1;this._finalizing=!1;if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.format instanceof P))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof M))throw new TypeError("options.target must be a Target.");if(t.target.output)throw new Error("Target is already used for another output.");t.target.output=this,this._writer=t.target._createWriter(),this._muxer=t.format._createMuxer(this)}addVideoTrack(t,e={}){if(!(t instanceof E))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",t,e)}addAudioTrack(t,e={}){if(!(t instanceof O))throw new TypeError("source must be an AudioSource.");if(!e||typeof e!="object")throw new TypeError("metadata must be an object.");this._addTrack("audio",t,e)}addSubtitleTrack(t,e={}){if(!(t instanceof L))throw new TypeError("source must be a SubtitleSource.");if(!e||typeof e!="object")throw new TypeError("metadata must be an object.");this._addTrack("subtitle",t,e)}_addTrack(t,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 o={id:this._tracks.length+1,output:this,type:t,source:e,metadata:r};this._muxer.beforeTrackAdd(o),this._tracks.push(o),e._connectedTrack=o}start(){if(this._started)throw new Error("Output already started.");this._started=!0,this._muxer.start();for(let t of this._tracks)t.source._start()}async finalize(){if(this._finalizing)throw new Error("Cannot call finalize twice.");this._finalizing=!0;let t=this._tracks.map(e=>e.source._flush());await Promise.all(t),this._muxer.finalize(),this._writer.flush(),this._writer.finalize()}};export{oe as AUDIO_CODECS,Y as ArrayBufferTarget,De as AudioBufferSource,Ne as AudioDataSource,O as AudioSource,Pe as CanvasSource,Be as EncodedAudioChunkSource,Ue as EncodedVideoChunkSource,Ee as FileSystemWritableFileStreamTarget,K as MediaSource,Fe as MediaStreamAudioTrackSource,Re as MediaStreamVideoTrackSource,ye as MkvOutputFormat,Ve as Mp4OutputFormat,He as Output,P as OutputFormat,Ie as SUBTITLE_CODECS,Z as StreamTarget,L as SubtitleSource,M as Target,We as TextSubtitleSource,ie as VIDEO_CODECS,ze as VideoFrameSource,E as VideoSource,Q as WebMOutputFormat};