polotno-node 3.13.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import"./rolldown-runtime-XKyaHtl9.js";import{$ as e,A as t,At as n,B as r,Bt as i,C as a,Ct as o,D as s,Dt as c,E as l,Et as u,F as d,Ft as f,G as p,Gt as m,H as h,Ht as g,I as _,It as v,J as y,Jt as b,K as x,Kt as ee,L as te,Lt as ne,M as re,Mt as S,N as ie,Nt as ae,O as oe,Ot as se,P as C,Pt as ce,Q as le,R as ue,Rt as de,S as w,St as fe,T,Tt as pe,U as me,Ut as E,V as he,Vt as ge,W as _e,Wt as ve,X as ye,Xt as be,Y as xe,Yt as Se,Z as Ce,_ as we,_t as Te,a as Ee,at as De,b as Oe,bt as ke,c as Ae,ct as je,d as Me,dt as Ne,et as Pe,f as Fe,ft as Ie,g as Le,gt as Re,h as ze,ht as D,i as Be,it as Ve,j as He,jt as Ue,k as We,kt as Ge,l as Ke,lt as qe,m as Je,mt as Ye,n as Xe,nt as Ze,o as Qe,ot as $e,p as et,pt as tt,q as nt,qt as rt,r as it,rt as at,s as ot,st,tt as ct,u as O,ut as lt,v as ut,vt as dt,w as k,wt as ft,x as A,xt as pt,y as mt,yt as j,z as ht,zt as gt}from"./index-DO5siyU6.js";var _t=`Mediabunny v1.61.6`,vt=new Map,yt=new Map,bt=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!l.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${l.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.flip!==void 0&&typeof e.transform.flip!=`boolean`)throw TypeError(`config.transform.flip, when provided, must be a boolean.`);if(e.transform.crop!==void 0&&et(e.transform.crop,`config.transform.`),e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`);if(e.transform.frameRate!==void 0&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError(`config.transform.frameRate, when provided, must be a finite positive number.`);if(e.transform.force!==void 0&&typeof e.transform.force!=`boolean`)throw TypeError(`config.transform.force, when provided, must be a boolean.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);xt(e.codec,e)},xt=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&ie(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},St=e=>{let t=e.bitrateMode,n=e.quality._toVideoRateControl(e.codec,e.width,e.height,t),r=(t,n,r)=>({codec:e.fullCodecString??oe(e.codec,e.width,e.height,r,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:n,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...re(e.codec)}),i=[];return n.quantizer!==null&&i.push({config:r(void 0,`quantizer`,n.bitrate),quantizer:n.quantizer}),n.bitrateMode!==`quantizer`&&i.push({config:r(n.bitrate,n.bitrateMode,n.bitrate),quantizer:null}),D(i.length>0),i},Ct=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!w.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${w.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(k.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.quality must be provided for compressed audio codecs.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);wt(e.codec,e)},wt=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);let n=t.bitrateMode;if(n!==void 0&&![`constant`,`variable`].includes(n))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&ie(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},Tt=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??s(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...He(e.codec)}},M=class{constructor(e){if((typeof e==`number`||typeof e==`string`)&&(e={quality:e}),!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.bitrateMode!==void 0&&![`constant`,`variable`].includes(e.bitrateMode))throw TypeError(`options.bitrateMode, when provided, must be 'constant' or 'variable'.`);if(`quality`in e){if(typeof e.quality==`string`?!(e.quality in Et):typeof e.quality!=`number`||Number.isNaN(e.quality))throw TypeError(`options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.`);if(e.preferBitrate!==void 0&&typeof e.preferBitrate!=`boolean`)throw TypeError(`options.preferBitrate, when provided, must be a boolean.`);if(`bitrate`in e||`quantizer`in e)throw TypeError(`options.quality cannot be combined with options.bitrate or options.quantizer.`);this._quality=typeof e.quality==`string`?Et[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.bitrate, when provided, must be a positive integer.`);if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw TypeError(`options.quantizer, when provided, must be a non-negative integer.`);if(e.bitrate===void 0&&e.quantizer===void 0)throw TypeError(`At least one of options.bitrate or options.quantizer must be set.`);if(`preferBitrate`in e)throw TypeError(`options.preferBitrate can only be combined with options.quality.`);this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,n,r){let i=Dt[e],a=null,o=this._bitrateMode??r??`variable`;if(this._quantizer!==void 0){if(!i){if(this._bitrate===void 0)throw Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else if(this._quantizer<i.min||this._quantizer>i.max){if(this._bitrate===void 0)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${i.min} and ${i.max}.`)}else a=this._quantizer,this._bitrate===void 0&&(o=`quantizer`)}else this._bitrate===void 0&&i&&!this._preferBitrate&&(D(this._quality!==void 0),a=j(Math.round(ae(i.worst,i.best,this._quality)),i.min,i.max));let s;if(this._bitrate!==void 0)s=this._bitrate;else{let r=this._quality;r===void 0&&(D(a!==null&&i),r=j((a-i.worst)/(i.best-i.worst),0,1)),s=kt(e,t,n,Ot(r))}return{quantizer:a,bitrate:s,bitrateMode:o}}_toVideoBitrate(e,t,n){return this._bitrate===void 0?(D(this._quality!==void 0),kt(e,t,n,Ot(this._quality))):this._bitrate}_toAudioBitrate(e){if(k.includes(e)||e===`flac`)return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw Error(`This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.`);let t=Ot(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!n)throw Error(`Unhandled codec: ${e}`);let r=n*t;return e===`aac`?r=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e):e===`opus`||e===`vorbis`?r=Math.max(6e3,r):e===`mp3`&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)),Math.round(r/1e3)*1e3}},Et={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Dt={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(o()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},Ot=e=>.3*Math.exp(2.5538*e),kt=(e,t,n,r)=>{let i=t*n,a=3e6,o=a*(i/2073600)**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a}[e]*r;return Math.ceil(o/1e3)*1e3},At=(e,t)=>{if(e===`avc`)return{avc:{quantizer:t}};if(e===`hevc`)return{hevc:{quantizer:t}};if(e===`vp9`)return{vp9:{quantizer:t}};if(e===`av1`)return{av1:{quantizer:t}};D(!1)},jt=new M(`high`),Mt=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!l.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof M))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof M)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw TypeError(`frameRate, when provided, must be a finite positive number.`);xt(e,s);let c=Pt(i,a)??new M(`medium`),u;try{u=St({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let d=JSON.stringify(u),f=vt.get(d);if(f)return f;let p=(async()=>{for(let{config:t}of u)if(Ae.some(n=>n.supports(e,t)))return!0;if(typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`))return!1;for(let{config:t,quantizer:i}of u){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!pe()||await new Promise(async a=>{try{let o=new VideoEncoder({output:()=>{},error:()=>a(!1)});o.configure(t);let s=new Uint8Array(n*r*4),c=new VideoFrame(s,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});o.encode(c,i===null?void 0:At(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return vt.set(d,p),p},Nt=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:a,...o}=t;if(!w.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(i!==void 0&&!(i instanceof M))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof M)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer.`);wt(e,o);let s=Tt({codec:e,numberOfChannels:n,sampleRate:r,quality:Pt(i,a)??new M(`medium`),...o}),c=JSON.stringify(s),l=yt.get(c);if(l)return l;let u=(async()=>{if(ot.some(t=>t.supports(e,s))||k.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(s)).supported===!0}catch{return!1}})();return yt.set(c,u),u},Pt=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof M?t:new M({bitrate:t})},Ft=async(e,t)=>{for(let n of e)if(await Nt(n,t))return n;return null},It=class{constructor(e){this.mutex=new je,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Lt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Rt=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},zt=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);D(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},N=new Uint8Array(8),P=new DataView(N.buffer),F=e=>[(e%256+256)%256],I=e=>(P.setUint16(0,e,!1),[N[0],N[1]]),Bt=e=>(P.setInt16(0,e,!1),[N[0],N[1]]),Vt=e=>(P.setUint32(0,e,!1),[N[1],N[2],N[3]]),L=e=>(P.setUint32(0,e,!1),[N[0],N[1],N[2],N[3]]),R=e=>(P.setInt32(0,e,!1),[N[0],N[1],N[2],N[3]]),z=e=>(P.setUint32(0,Math.floor(e/2**32),!1),P.setUint32(4,e,!1),[N[0],N[1],N[2],N[3],N[4],N[5],N[6],N[7]]),Ht=e=>(P.setInt32(0,Math.floor(e/2**32),!1),P.setUint32(4,e,!1),[N[0],N[1],N[2],N[3],N[4],N[5],N[6],N[7]]),Ut=e=>(P.setInt16(0,256*e,!1),[N[0],N[1]]),B=e=>(P.setInt32(0,2**16*e,!1),[N[0],N[1],N[2],N[3]]),Wt=e=>(P.setInt32(0,2**30*e,!1),[N[0],N[1],N[2],N[3]]),Gt=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},V=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},Kt=e=>[B(e[0]),B(e[1]),Wt(e[2]),B(e[3]),B(e[4]),Wt(e[5]),B(e[6]),B(e[7]),Wt(e[8])],H=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),U=(e,t,n,r,i)=>H(e,[F(t),Vt(n),r??[]],i),qt=e=>e.isQuickTime?H(`ftyp`,[V(`qt `),L(512),V(`qt `)]):e.fragmented?e.cmaf?H(`ftyp`,[V(`iso5`),L(512),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]):H(`ftyp`,[V(`iso5`),L(512),V(`iso5`),V(`iso6`),V(`mp41`)]):H(`ftyp`,[V(`isom`),L(512),V(`isom`),e.holdsAvc?V(`avc1`):[],V(`mp41`)]),Jt=()=>H(`styp`,[V(`iso5`),L(0),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]),Yt=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),U(`sidx`,1,0,[L(1),L(X),z(Z(n,X)),z(0),I(0),I(1),L(t&2147483647),L(Z(r,X)),L(0)])},Xt=e=>({type:`mdat`,largeSize:e}),Zt=e=>({type:`free`,size:e}),W=e=>H(`moov`,void 0,[Qt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>$t(t,e.creationTime)),e.isFragmented?Vn(e.trackDatas):null,nr(e)]),Qt=(e,t)=>{let r=Math.max(0,...t.map(e=>Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)))),i=Math.max(0,...t.map(e=>e.track.id))+1,a=!n(e)||!n(r),o=a?z:L;return U(`mvhd`,+a,0,[o(e),o(e),L(X),o(r),B(1),Ut(1),Array(10).fill(0),Kt(Ie),Array(24).fill(0),L(i)])},$t=(e,t)=>{let n=Sr(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return H(`trak`,void 0,[en(e,t),r?tn(e):null,nn(e,t),n.name===void 0?null:H(`udta`,void 0,[H(`name`,[...E.encode(n.name)])])])},en=(e,t)=>{let r=Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)),i=!n(t)||!n(r),a=i?z:L,o;if(e.type===`video`&&e.track.metadata.transformationMatrix)o=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=f(ne(t??0),gt(n?-1:1,1));o=dt(r,e.info.width,e.info.height)}else o=Ie;let s=2;e.track.metadata.disposition?.default!==!1&&(s|=1);let c=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Re(e);return U(`tkhd`,+i,s,[a(t),a(t),L(e.track.id),L(0),a(r),Array(8).fill(0),I(0),I(c),Ut(+(e.type===`audio`)),I(0),Kt(o),B(e.type===`video`?e.info.width:0),B(e.type===`video`?e.info.height:0)])},tn=e=>{let t=e.startTimestampOffset;if(D(t!==null),t>0){let r=Z(t,X),i=Z(Q(e),X),a=!n(r)||!n(i),o=a?z:L,s=a?Ht:R;return H(`edts`,void 0,[U(`elst`,+!!a,0,[L(2),o(r),s(-1),B(1),o(i),s(0),B(1)])])}{let r=Z(-t,e.timescale),i=Math.max(0,Z(Q(e),X)+Z(t,X)),a=!u(r)||!n(i),o=a?z:L,s=a?Ht:R;return H(`edts`,void 0,[U(`elst`,+!!a,0,[L(1),o(i),s(r),B(1)])])}},nn=(e,t)=>H(`mdia`,void 0,[rn(e,t),sn(!0,an[e.type],on[e.type]),cn(e)]),rn=(e,t)=>{let r=Z(Q(e),e.timescale),i=!n(t)||!n(r),a=i?z:L;return U(`mdhd`,+i,0,[a(t),a(t),L(e.timescale),a(r),I(mr(e.track.metadata.languageCode??`und`)),I(0)])},an={video:`vide`,audio:`soun`,subtitle:`text`},on={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},sn=(e,t,n,r=`\0\0\0\0`)=>U(`hdlr`,0,0,[e?V(`mhlr`):L(0),V(t),V(r),L(0),L(0),V(n,!0)]),cn=e=>H(`minf`,void 0,[ln[e.type](),un(),pn(e)]),ln={video:()=>U(`vmhd`,0,1,[I(0),I(0),I(0),I(0)]),audio:()=>U(`smhd`,0,0,[I(0),I(0)]),subtitle:()=>U(`nmhd`,0,0)},un=()=>H(`dinf`,void 0,[dn()]),dn=()=>U(`dref`,0,0,[L(1)],[fn()]),fn=()=>U(`url `,0,1),pn=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return H(`stbl`,void 0,[mn(e),Pn(e),t?zn(e):null,t?Bn(e):null,In(e),Ln(e),Rn(e),Fn(e)])},mn=e=>{let t;if(e.type===`video`)t=hn(cr(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=ur(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);D(n),t=Cn(n,e)}else e.type===`subtitle`&&(t=Mn(fr[e.track.source._codec],e));return D(t),U(`stsd`,0,0,[L(1)],[t])},hn=(e,t)=>H(e,[[,,,,,,].fill(0),I(1),I(0),I(0),Array(12).fill(0),I(t.info.width),I(t.info.height),L(4718592),L(4718592),L(0),I(1),F(_t.length),V(_t),Array(31-_t.length).fill(0),I(t.info.hasAlphaChannel?32:24),Bt(65535)],[lr[t.track.source._codec]?.(t)??null,_n(t),ke(t.info.decoderConfig.colorSpace)?null:vn(t),gn(t)]),gn=e=>e.avgBitrate===0&&e.maxBitrate===0?null:H(`btrt`,[L(0),L(e.maxBitrate),L(e.avgBitrate)]),_n=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:H(`pasp`,[L(e.info.pixelAspectRatio.num),L(e.info.pixelAspectRatio.den)]),vn=e=>{let t=e.info.decoderConfig.colorSpace;return H(`colr`,[V(e.muxer.isQuickTime?`nclc`:`nclx`),I(t?.primaries==null?2:qe[t.primaries]),I(t?.transfer==null?2:Ye[t.transfer]),I(t?.matrix==null?2:tt[t.matrix]),e.muxer.isQuickTime?[]:F(!!t?.fullRange<<7)])},yn=e=>e.info.decoderConfig&&H(`avcC`,[...m(e.info.decoderConfig.description)]),bn=e=>e.info.decoderConfig&&H(`hvcC`,[...m(e.info.decoderConfig.description)]),xn=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?qe[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Ye[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?tt[t.colorSpace.matrix]:1;return U(`vpcC`,1,0,[F(r),F(i),F(c),F(l),F(u),F(d),I(0)])},Sn=e=>H(`av1C`,t(e.info.decoderConfig.codec)),Cn=(e,t)=>{let n=0,r,i=16,a=k.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=C(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(i),I(0),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(Math.min(i,16)),Bt(e),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0),a?[L(1),L(i/8),L(t.info.numberOfChannels*i/8)]:[L(0),L(0),L(0)],L(2)]}return H(e,r,[dr(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,gn(t)])},wn=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...F(t),...F(21),...Vt(0),...L(e.maxBitrate),...L(e.avgBitrate)];if(e.info.decoderConfig.description){let t=m(e.info.decoderConfig.description);n=[...n,...F(5),...Gt(t.byteLength),...t]}return n=[...I(1),...F(0),...F(4),...Gt(n.length),...n,...F(6),...F(1),...F(2)],n=[...F(3),...Gt(n.length),...n],U(`esds`,0,0,n)},G=e=>H(`wave`,void 0,[Tn(e),En(e),H(`\0\0\0\0`)]),Tn=e=>H(`frma`,[V(ur(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),En=e=>{let{littleEndian:t}=C(e.track.source._codec);return H(`enda`,[I(+t)])},Dn=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){D(s.byteLength>=18);let e=m(s),c=ye(e);t=c.outputChannelCount,n=c.preSkip,r=c.inputSampleRate,i=c.outputGain,a=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return H(`dOps`,[F(0),F(t),I(n),L(r),Bt(i),F(a),...o])},On=e=>{let t=e.info.decoderConfig?.description;return D(t),U(`dfLa`,0,0,[...m(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=C(e.track.source._codec);return U(`pcmC`,0,0,[F(+t),F(8*n)])},kn=e=>{D(e.info.primingPacket);let t=nt(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new at(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),H(`dac3`,[...n])},An=e=>{D(e.info.primingPacket);let t=xe(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new at(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return H(`dec3`,[...i])},jn=e=>{D(e.info.primingPacket);let t=y(e.info.primingPacket.data);if(!t)throw Error(`Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.`);return H(`ddts`,[...ue(t)])},Mn=(e,t)=>H(e,[[,,,,,,].fill(0),I(1)],[pr[t.track.source._codec](t),gn(t)]),Nn=e=>H(`vttC`,[...E.encode(e.info.config.description)]),Pn=e=>U(`stts`,0,0,[L(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[L(e.sampleCount),L(e.sampleDelta)])]),Fn=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return U(`stss`,0,0,[L(t.length),t.map(([e])=>L(e+1))])},In=e=>U(`stsc`,0,0,[L(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[L(e.firstChunk),L(e.samplesPerChunk),L(1)])]),Ln=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=C(e.track.source._codec);return U(`stsz`,0,0,[L(t*e.info.numberOfChannels),L(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return U(`stsz`,0,0,[L(0),L(e.samples.length),e.samples.map(e=>L(e.size))])},Rn=e=>e.finalizedChunks.length>0&&S(e.finalizedChunks).offset>=2**32?U(`co64`,0,0,[L(e.finalizedChunks.length),e.finalizedChunks.map(e=>z(e.offset))]):U(`stco`,0,0,[L(e.finalizedChunks.length),e.finalizedChunks.map(e=>L(e.offset))]),zn=e=>U(`ctts`,1,0,[L(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[L(e.sampleCount),R(e.sampleCompositionTimeOffset)])]),Bn=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;D(e.compositionTimeOffsetTable.length>0),D(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:U(`cslg`,0,0,[R(a),R(t),R(n),R(r),R(i)])},Vn=e=>H(`mvex`,void 0,e.map(Hn)),Hn=e=>U(`trex`,0,0,[L(e.track.id),L(1),L(0),L(0),L(0)]),Un=(e,t)=>H(`moof`,void 0,[Wn(e),...t.map(Kn)]),Wn=e=>U(`mfhd`,0,0,[L(e)]),Gn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16},Kn=e=>H(`traf`,void 0,[qn(e),Jn(e),Yn(e)]),qn=e=>{D(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Gn(n)};return U(`tfhd`,0,t,[L(e.track.id),L(r.duration),L(r.size),L(r.flags)])},Jn=e=>(D(e.currentChunk),U(`tfdt`,1,0,[z(Z(e.currentChunk.startTimestamp,e.timescale))])),Yn=e=>{D(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Gn),i=e.currentChunk.samples.map(t=>Z(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,U(`trun`,1,m,[L(e.currentChunk.samples.length),L(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?L(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?L(t[a]):[],d?L(n[a]):[],f?L(r[a]):[],p?R(i[a]):[]])])},Xn=e=>H(`mfra`,void 0,[...e.map(Zn),Qn()]),Zn=e=>U(`tfra`,1,0,[L(e.track.id),L(63),L(e.finalizedChunks.length),e.finalizedChunks.map(t=>[z(Z(t.samples[0].timestamp,e.timescale)),z(t.moofOffset),L(t.trafIndex+1),L(1),L(1)])]),Qn=()=>U(`mfro`,0,0,[L(0)]),$n=()=>H(`vtte`),er=(e,t,n,r,i)=>H(`vttc`,void 0,[i===null?null:H(`vsid`,[R(i)]),n===null?null:H(`iden`,[...E.encode(n)]),t===null?null:H(`ctim`,[...E.encode(Rt(t))]),r===null?null:H(`sttg`,[...E.encode(r)]),H(`payl`,[...E.encode(e)])]),tr=e=>H(`vtta`,[...E.encode(e)]),nr=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=or(r);e&&t.push(e)}else if(n===`mdta`){let e=sr(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&rr(t,e.output._metadataTags);return t.length===0?null:H(`udta`,void 0,t)},rr=(e,t)=>{for(let{key:n,value:r}of Ue(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`beatsPerMinute`:case`images`:break;default:Re(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(q(n,r)):r instanceof Uint8Array&&e.push(H(n,Array.from(r))))}},q=(e,t)=>{let n=E.encode(t);return H(e,[I(n.length),I(mr(`und`)),Array.from(n)])},ir={"image/jpeg":13,"image/png":14,"image/bmp":27},ar=(e,t)=>{let n=[];for(let{key:r,value:i}of Ue(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:J(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:J(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:J(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:J(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:J(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:J(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:J(i)});break;case`beatsPerMinute`:t||n.push({key:`tmpo`,value:H(`data`,[L(21),L(0),I(i)])});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:J(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:H(`data`,[L(ir[e.mimeType]??0),L(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:J(t)})}else n.push({key:`trkn`,value:H(`data`,[L(0),L(0),I(0),I(i),I(e.tracksTotal??0),I(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:H(`data`,[L(0),L(0),I(0),I(i),I(e.discsTotal??0),I(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Re(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:J(i)}):i instanceof Uint8Array?n.push({key:r,value:H(`data`,[L(0),L(0),Array.from(i)])}):i instanceof Ve&&n.push({key:r,value:H(`data`,[L(ir[i.mimeType]??0),L(0),Array.from(i.data)])}))}return n},or=e=>{let t=ar(e,!1);return t.length===0?null:U(`meta`,0,0,void 0,[sn(!1,`mdir`,``,`appl`),H(`ilst`,void 0,t.map(e=>H(e.key,void 0,[e.value])))])},sr=e=>{let t=ar(e,!0);return t.length===0?null:H(`meta`,void 0,[sn(!1,`mdta`,``),U(`keys`,0,0,[L(t.length)],t.map(e=>H(`mdta`,[...E.encode(e.key)]))),H(`ilst`,void 0,t.map((e,t)=>H(String.fromCharCode(...L(t+1)),void 0,[e.value])))])},J=e=>H(`data`,[L(1),L(0),...E.encode(e)]),cr=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`;case`prores`:return t}},lr={avc:yn,hevc:bn,vp8:xn,vp9:xn,av1:Sn,prores:null},ur=(e,t,n)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`;case`dts`:return t}if(n)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},dr=(e,t)=>{switch(e){case`aac`:return wn;case`mp3`:return wn;case`opus`:return Dn;case`vorbis`:return wn;case`flac`:return On;case`ac3`:return kn;case`eac3`:return An;case`dts`:return jn}if(t)switch(e){case`pcm-s24`:return G;case`pcm-s24be`:return G;case`pcm-s32`:return G;case`pcm-s32be`:return G;case`pcm-f32`:return G;case`pcm-f32be`:return G;case`pcm-f64`:return G;case`pcm-f64be`:return G}else switch(e){case`pcm-s16`:return K;case`pcm-s16be`:return K;case`pcm-s24`:return K;case`pcm-s24be`:return K;case`pcm-s32`:return K;case`pcm-s32be`:return K;case`pcm-f32`:return K;case`pcm-f32be`:return K;case`pcm-f64`:return K;case`pcm-f64be`:return K}return null},fr={webvtt:`wvtt`},pr={webvtt:Nn},mr=e=>{D(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},hr=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){D(!this.started),this.target._start(),this.started=!0}write(e){D(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return D(this.started&&!this.finalized),this.target._flush()}async finalize(){D(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};we();var Y=class extends Ne{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit(`write`,{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);return new yr(this,e)}},gr=2**16,_r=2**32,vr=class extends Y{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(gr,{maxByteLength:_r})}catch{this._buffer=new ArrayBuffer(gr),this._supportsResize=!1}else this._buffer=new ArrayBuffer(gr);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>_r)throw Error(`ArrayBuffer exceeded maximum size of ${_r} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit(`finalized`)}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}},yr=class extends Y{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},br=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},X=57600,xr=2082844800,Sr=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Q=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},Cr=class extends It{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new vr,this.auxWriter=new hr(this.auxTarget,!1),this.auxBoxWriter=new zt(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=v(),this.creationTime=Math.floor(Date.now()/1e3)+xr,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof Gr,this.isCmaf=t instanceof Wr,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Wr?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.formatOptions.fastStart===void 0?e instanceof vr:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new zt(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof vr&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new hr(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new zt(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(D(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(qt({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(D(this.writer),D(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xt(!0),this.boxWriter.writeBox(this.mdat))}await this.writer?.flush();for(let e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return Oe({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;te(n,e.source._codec),D(n),D(n.decoderConfig);let i={...n.decoderConfig};D(i.codedWidth!==void 0),D(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=me(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Ce(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=_e(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=le(e),a=!0}let o=pt(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:g({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,n,r){let i=this.trackDatas.find(e=>e.track===t);if(i)return i;d(r,t.source._codec),D(r),D(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(t.source._codec===`aac`&&!a.description){if(!n)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let t=ut(Xe.tempFromBytes(n.data));if(!t)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let r=Pe[t.samplingFrequencyIndex],i=e[t.channelConfiguration];if(r===void 0||i===void 0)throw Error(`Invalid ADTS frame header.`);a.description=ct({objectType:t.objectType,outputSampleRate:r,outputNumberOfChannels:i}),o=!0}if(!n){if(t.source._codec===`ac3`||t.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(t.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let s={muxer:this,track:t,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&k.includes(t.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:n},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:t.source._nominalBitrate??t.metadata.averageBitrate??0,maxBitrate:t.source._nominalBitrate??t.metadata.bitrate??0};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;_(t),D(t),D(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...x(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=ht(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=ut(Xe.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=C(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=C(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let r of e.cueQueue)D(r.timestamp<=t),D(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=$n();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;Lt.lastIndex=0;let r=Lt.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=tr(n.notes);this.auxBoxWriter.writeBox(e)}let c=er(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){D(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=S(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){D(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(D(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=S(e.timeToSampleTable);if(D(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=S(e.compositionTimeOffsetTable);D(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,D(e.lastSample),D(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){D(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(D(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),D(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(D(!this.isFragmented),D(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||S(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`)e.currentChunk.offset=0;else{e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)D(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}}async interleaveSamples(e=!1){if(D(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(D(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;D(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){D(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new zt(this.writer);let e=this.boxWriter.measureBox(Jt()),t=this.boxWriter.measureBox(Yt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}D(this.writer),D(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=Un(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];D(n.currentChunk),D(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=Un(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}D(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Xt(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){D(this.writer),D(this.boxWriter),this.ensureOneEnabledTrack();let e=W(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;D(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xt(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){D(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;D(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){D(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=Q(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(D(this.writer),D(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Xt(!1);let e;for(let t=0;t<2;t++){let t=W(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)D(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=W(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)D(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(Jt()),this.boxWriter.writeBox(Yt(this,e))}else{let e=this.writer.getPos(),t=Xn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{D(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);D(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=W(this);if(this.fastStart===`reserve`){D(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Zt(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},wr=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){D(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>r<2?t[n*e+r]:0:e===4&&t===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;let t=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+t,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}D(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor((i-1/this.sourceSampleRate)*this.targetSampleRate)+1,s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;D(n<this.bufferCapacityInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=this.maxWrittenFrame===null?n:Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;D(this.startTime!==null);let e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new Ke({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}},Tr=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},Er=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r}),Dr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Or=class extends Dr{constructor(e){if(super(),!l.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${l.join(`, `)}.`);this._codec=e}},kr=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Ar=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new lt,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,n){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let i=this.encodingConfig,a=i.sizeChangeBehavior??`deny`,o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(i.transform?.width!==void 0||i.transform?.height!==void 0||i.transform?.rotate!==void 0||i.transform?.flip!==void 0||i.transform?.crop!==void 0||i.transform?.force===!0||o&&a!==`passThrough`){let n=i.transform?.width,r=i.transform?.height,s=i.transform?.fit??`fill`;o&&a!==`passThrough`&&(D(this.outputWidth),D(this.outputHeight),D(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,flip:i.transform?.flip,fit:s,alpha:i.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let s=i.transform?.frameRate;if(s!==void 0){let i=e.timestamp+e.duration,a=fe(e.timestamp,s);if(this.frameRateLastSample!==null){if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=i;return}await this.padFrameRate(a,n)}e===r&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/s),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=i}await this.processAndEncode(e,n)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig,r;if(n.transform?.process){let t=n.transform.process(e);if(Ge(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let i=[];try{for(let n of t)n instanceof O?i.push(n):typeof VideoFrame<`u`&&n instanceof VideoFrame?i.push(new O(n)):i.push(new O(n,{timestamp:e.timestamp,duration:e.duration}))}catch(n){for(let t of i)t!==e&&t.close();for(let n of t)(n instanceof O&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw n}r=i}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),D(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...this.defaultEncodeOptions,...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{D(this.encoder);let t=e.toVideoFrame(),n=Te(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),r=n===-1?null:this.preciseTimings[n];if(r&&r.microsecondTimestamp===t.timestamp?(r.timestamp!==e.timestamp&&(r.timestampIsValid=!1),r.duration!==e.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(n+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)try{this.encoder.encode(t,a)}finally{t.close()}else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(t,a)}finally{t.close()}}else{this.splitter||=new Pr;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n);try{this.encoder.encode(e,a)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;D(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r={stack:[],error:void 0,hasError:!1};try{let i=Tr(r,this.frameRateLastSample.clone(),!1);i.setTimestamp(this.frameRateLastTimestamp+e/n),i.setDuration(1/n),await this.processAndEncode(i,t)}catch(e){r.error=e,r.hasError=!0}finally{Er(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=Pt(this.encodingConfig.quality,this.encodingConfig.bitrate);D(t!==void 0);let n=St({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),r=null,i;for(let e of n){let t=e.config;if(this.encodingConfig.onEncoderConfig?.(t),i=Ae.find(e=>e.supports(this.encodingConfig.codec,t)),i){r=e;break}if(typeof VideoEncoder<`u`){if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(t)).supported){r=e;break}}catch{}}}if(!r){if(typeof VideoEncoder>`u`)throw Error(ce(`VideoEncoder`));let e=n[0].config,t=n.map(({config:e,quantizer:t})=>t===null?`${e.bitrate} bps`:`quantizer ${t}`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(` / `)}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??`no-preference`}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let a=r.config;r.quantizer===null?this.source._nominalBitrate=a.bitrate??null:this.defaultEncodeOptions=At(this.encodingConfig.codec,r.quantizer),i?(this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof A))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);kr(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init()):(this.encoderConfig=a,this.encodingConfig.codec===`avc`&&pe()&&(this.chunkTimestampsAreShiftedByDuration=await Mr()),this.createWebCodecsEncoders()),D(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let e=this.encoderConfig;D(e);let t=[],n=[],r=0,i=0,a=(e,t)=>{ft(e)?this.encodersReclaimed=!0:(e.stack=t,this.setError(e))},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(e,a)=>{if(!this.alphaEncoder){this.addPacket(e,null,a);return}let o=this.alphaFrameQueue.shift();D(o!==void 0),o?(this.alphaEncoder.encode(o,{...this.defaultEncodeOptions,keyFrame:e.type===`key`}),i++,o.close(),t.push({chunk:e,meta:a})):i===0?this.addPacket(e,null,a):(n.push(r+i),t.push({chunk:e,meta:a}))},error:e=>a(e,o)}),this.encoder.configure(e),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(e,a)=>{i--;let o=t.shift();for(D(o!==void 0),this.addPacket(o.chunk,e,o.meta),r++;n.length>0&&n[0]===r;){n.shift();let e=t.shift();D(e!==void 0),this.addPacket(e.chunk,null,e.meta)}},error:e=>a(e,o)}),this.alphaEncoder.configure(e)}}addPacket(e,t,n){let i={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}let a=A.fromEncodedChunk(e,i),o=this.encoderConfig;if(D(o),n?.decoderConfig&&(n.decoderConfig.codec=We({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:n.decoderConfig.description?m(n.decoderConfig.description):null,colorSpace:n.decoderConfig.colorSpace??null,avcType:o.codec.includes(`avc1.`)?1:o.codec.includes(`avc3.`)?3:null,avcCodecInfo:this.encodingConfig.codec===`avc`&&!n.decoderConfig.description?me(a.data):null,hevcCodecInfo:this.encodingConfig.codec===`hevc`&&!n.decoderConfig.description?_e(a.data):null,vp9CodecInfo:this.encodingConfig.codec===`vp9`?p(a.data):null,av1CodecInfo:this.encodingConfig.codec===`av1`?h(a.data):null,proresFormat:null}),this.encodingConfig.codec===`avc`&&n.decoderConfig.description&&pe())){let e=r(m(n.decoderConfig.description)),t=e?.sequenceParameterSets[0];if(t&&t[0]===t[1]){D(e),t=t.subarray(1);let r=e.pictureParameterSets[0];r&&=r.subarray(1);let i=Ce({...e,sequenceParameterSets:[t],pictureParameterSets:r?[r]:[]});n.decoderConfig.description=i}}let s=e.timestamp;this.chunkTimestampsAreShiftedByDuration&&(s-=e.duration??0,a=a.clone({timestamp:s/1e6}));let c=Te(this.preciseTimings,s,e=>e.microsecondTimestamp),l=c===-1?null:this.preciseTimings[c],u=null;this.emittedEncoderPackets===0&&a.type===`delta`&&n?.decoderConfig&&(u=he(this.encodingConfig.codec,n.decoderConfig,a.data)),(l&&l.microsecondTimestamp===s||u!==null)&&(a=a.clone({timestamp:l?.timestampIsValid?l.timestamp:void 0,duration:l?.durationIsValid?l.duration:void 0,type:u??void 0})),kr(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,n).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){D(this.encoder),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=fe(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await ee(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},jr=null,Mr=()=>jr??=(async()=>{let e=null,t=new VideoEncoder({output:t=>{e??=t.timestamp},error:()=>{}});try{t.configure({codec:`avc1.64001f`,width:1280,height:720});let e=new VideoFrame(new Uint8Array(1382400),{format:`I420`,codedWidth:1280,codedHeight:720,timestamp:0,duration:500});t.encode(e,{keyFrame:!0}),e.close(),await t.flush()}catch{return!1}finally{t.state!==`closed`&&t.close()}return e===500})(),Nr=null,Pr=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Nr){let e=new Blob([`(${Fr.toString()})()`],{type:`application/javascript`});Nr=URL.createObjectURL(e)}this.worker=new Worker(Nr),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=v();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}},Fr=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,ee=a?512:o?2048:128;s===1?y.fill(ee,x):new Uint16Array(y.buffer,x,2*_).fill(ee);let te=a?`I420P10`:o?`I420P12`:`I420`,ne=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),re={format:te,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[y.buffer]};return{colorFrame:ne,alphaFrame:new VideoFrame(y,re)}}},Ir=class extends Or{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);bt(t),super(t.codec),this._encoder=new Ar(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e))throw TypeError(`timestamp must be a finite number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new O(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Lr=class extends Dr{constructor(e){if(super(),!w.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${w.join(`, `)}.`);this._codec=e}},Rr=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new lt,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new wr({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&Fe(e.format)!==n.transform.sampleFormat){let r=Me(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(Ge(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof Ke))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);for(let e of t)await this.encodeSample(e,!0)}finally{for(let e of t)e instanceof Ke&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),D(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new Ke({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{D(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){D(this.outputSampleSize),D(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.format===`s32`||e.format===`s32-planar`,l=c?`s32-planar`:`f32-planar`,u=c?1/2147483648:1,d=e.allocationSize({planeIndex:0,format:l}),f=c?new Int32Array(d/4):new Float32Array(d/4);for(let t=0;t<n;t++){e.copyTo(f,{planeIndex:t,format:l});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,f[e*o+a]*u)}}t&&e.close();let p={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,c=e*o,l=new A(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,p),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,p)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=Pt(this.encodingConfig.quality,this.encodingConfig.bitrate),i=Tt({numberOfChannels:t,sampleRate:n,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(i),this.source._nominalBitrate=i.bitrate??null;let a=ot.find(e=>e.supports(this.encodingConfig.codec,i));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof A))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(k.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(ce(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(i)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.numberOfChannels} channels, ${i.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let t=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){if(t.decoderConfig.description&&t.decoderConfig.description.byteLength>0&&m(t.decoderConfig.description)[0]===3){let{decoderSpecificInfo:e}=mt(Xe.tempFromBytes(m(t.decoderConfig.description)));t.decoderConfig.description=e??void 0}let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||Ze(m(t.decoderConfig.description)).objectType===0,e){let e=Number(S(i.codec.split(`.`)));t.decoderConfig.description=ct({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=A.fromEncodedChunk(e);n=n.clone({timestamp:de(n.timestamp,i.sampleRate),duration:e.duration==null?void 0:de(n.duration,i.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.setError(e)})},error:e=>{e.stack=t,this.setError(e)}}),this.encoder.configure(i)}D(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=C(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,j(Math.round(n*128)+128,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,j(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=j(Math.round(n*32768),-32768,32767);e.setUint8(t,Qe(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=j(Math.round(n*32768),-32768,32767);e.setUint8(t,Ee(r))}:D(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,j(Math.round(n*32768)+32768,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,j(Math.round(n*32768),-32768,32767),r):D(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>ge(e,t,j(Math.round(n*8388608)+8388608,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>i(e,t,j(Math.round(n*8388608),-8388608,8388607),r):D(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,j(Math.round(n*2147483648)+2147483648,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,j(Math.round(n*2147483648),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):D(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):D(!1);break;default:Re(n),D(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},zr=class extends Lr{constructor(e,t={}){if(Ct(e),typeof t!=`object`||!t)throw TypeError(`options must be an object.`);if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw TypeError(`options.startTimestamp, when provided, must be a finite number.`);super(e.codec),this._encoder=new Rr(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=Ke._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Br=class extends Dr{constructor(e){if(super(),!T.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${T.join(`, `)}.`);this._codec=e}},Vr=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>l.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>w.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>T.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Hr=class extends Vr{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!se(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new Cr(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Ur=class extends Hr{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...l,...a,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...T]}_codecUnsupportedHint(e){return new Gr().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Wr=class extends Hr{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...l,...a,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...T]}},Gr=class extends Hr{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...l,...w]}_codecUnsupportedHint(e){return new Ur().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Kr=[`video`,`audio`,`subtitle`],qr=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=ve(this.metadata.group),r=ve(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Jr=class extends qr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Yr=class extends qr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Xr=class extends qr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Zr=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},Qr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!c(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&$e(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof Zr)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Zr))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},$r=class extends Ne{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(Ge(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Zr,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new je,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Vr))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof br))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Y&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Y)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Y&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){D(this._target instanceof br);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return Ge(t)?t.then(n):n(t)}async _getTarget(e){D(this._target instanceof br);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(D(this._initTarget!==null),this._initTarget instanceof Y)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Y)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return Ge(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new hr(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Or))throw TypeError(`source must be a VideoSource.`);if(Qr(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!=`boolean`)throw TypeError(`metadata.hasOnlyKeyPackets, when provided, must be a boolean.`);if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!=`boolean`)throw TypeError(`metadata.canBeTransparent, when provided, must be a boolean.`);if(t.decoderConfig!==void 0&&te({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof A))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Jr(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Lr))throw TypeError(`source must be an AudioSource.`);if(Qr(t),t.decoderConfig!==void 0&&d({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof A))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Yr(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Br))throw TypeError(`source must be a SubtitleSource.`);Qr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Xr(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(De(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this.tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of Kr)if(this.tracks.reduce((e,n)=>e+ +(n.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of Kr){let n=this.tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(st._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`)this.state===`finalized`&&st._warn(`Output has already been finalized.`);else return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(st._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},ei=be,ti=[{levelIdc:10,maxMacroblocks:99,maxMacroblocksPerSecond:1485},{levelIdc:11,maxMacroblocks:396,maxMacroblocksPerSecond:3e3},{levelIdc:12,maxMacroblocks:396,maxMacroblocksPerSecond:6e3},{levelIdc:13,maxMacroblocks:396,maxMacroblocksPerSecond:11880},{levelIdc:21,maxMacroblocks:792,maxMacroblocksPerSecond:19800},{levelIdc:22,maxMacroblocks:1620,maxMacroblocksPerSecond:20250},{levelIdc:30,maxMacroblocks:1620,maxMacroblocksPerSecond:40500},{levelIdc:31,maxMacroblocks:3600,maxMacroblocksPerSecond:108e3},{levelIdc:32,maxMacroblocks:5120,maxMacroblocksPerSecond:216e3},{levelIdc:40,maxMacroblocks:8192,maxMacroblocksPerSecond:245760},{levelIdc:42,maxMacroblocks:8704,maxMacroblocksPerSecond:522240},{levelIdc:50,maxMacroblocks:22080,maxMacroblocksPerSecond:589824},{levelIdc:51,maxMacroblocks:36864,maxMacroblocksPerSecond:983040},{levelIdc:52,maxMacroblocks:36864,maxMacroblocksPerSecond:2073600},{levelIdc:60,maxMacroblocks:139264,maxMacroblocksPerSecond:4177920},{levelIdc:61,maxMacroblocks:139264,maxMacroblocksPerSecond:8355840},{levelIdc:62,maxMacroblocks:139264,maxMacroblocksPerSecond:16711680}];function ni(e,t,n,r){if(e!==`avc`)return;let i=Math.ceil(t/16),a=Math.ceil(n/16),o=i*a,s=e=>o<=e.maxMacroblocks,c=ti.find(s),l=ti.find(e=>s(e)&&o*r<=e.maxMacroblocksPerSecond&&Math.max(i,a)<=Math.sqrt(e.maxMacroblocks*8))??ti[ti.length-1];if(c&&l!==c)return`avc1.6400${l.levelIdc.toString(16).padStart(2,`0`)}`}function ri(e){return e instanceof Error&&/is not (supported|available) in this environment/.test(e.message)}async function ii({codecs:e,attempt:t,probe:n,...r}){let i,a=[];for(let[o,s]of e.entries())if(!(o>0&&!await n(s))){a.push(s);try{let e=await Se(()=>t(s),{...r,shouldRetry:ri});return i&&console.warn(`[polotno-video-export] Encoding with ${s}: ${i.message}`),e}catch(e){if(!ri(e))throw e;i=e}}throw ei(`VIDEO_FAILED`,`Your browser doesn't support video encoding. Tried ${a.join(`, `)}; last error: ${i?.message}`,{reason:`no-encoder`},i)}function ai(){return typeof DOMException<`u`?new DOMException(`The operation was aborted.`,`AbortError`):Object.assign(Error(`The operation was aborted.`),{name:`AbortError`})}function $(e){return!!e&&typeof e==`object`&&`name`in e&&e.name===`AbortError`}function oi(e){return Math.round(e/2)*2}function si(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function ci(e){let t=0;return e.pages.map(e=>{let n=t,r=e.duration||5e3;return t=n+r,{id:e.id,startTime:n,duration:r}})}function li(e){let t=e.width,n=e.height;for(let r of e.pages){let i=r.width===`auto`?e.width:r.width,a=r.height===`auto`?e.height:r.height;t=Math.max(t,i),n=Math.max(n,a)}return{width:oi(t),height:oi(n)}}function ui(e){let t=[],n=0;for(let r of e.pages){let e=r.duration||5e3;for(let i of r.children)if(i.type===`video`){let r=i.volume===void 0?1:i.volume;if(r===0)continue;let a=i.startTime||0,o=i.endTime||1,s=i.duration||5e3,c=i.speed||1;t.push({id:i.id,src:i.src,volume:r,startTime:a,endTime:o,duration:s,speed:c,pageStartTime:n,pageDuration:e,animations:i.animations})}n+=e}return t}function di(e,t){let n=[];for(let r of e.pages)n.push({pageId:r.id,width:r.width,height:r.height}),r.set({width:t.width,height:t.height});return n}function fi(e,t){for(let{pageId:n,width:r,height:i}of t){let t=e.pages.find(e=>e.id===n);t&&t.set({width:r,height:i})}}function pi(e,t){let n=b(),r=n.sceneCanvas._canvas;if(r.width=e.width*t,r.height=e.height*t,r.width<=0||r.height<=0)throw ei(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}var mi=e=>e.cancel().catch(()=>{});function hi(e,t,n){let{width:r,height:i}=t;return Mt(e,{width:r,height:i,quality:jt,fullCodecString:ni(e,r,i,n)})}async function gi(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=ui(t).length>0;if(!r&&!i)return{audioBufferSource:null};let a=e.format.getSupportedAudioCodecs(),o=[`aac`,`mp3`,`flac`],s=[...o.filter(e=>a.includes(e)),...a.filter(e=>!o.includes(e))],c=await Ft(s,{numberOfChannels:2,sampleRate:44100,quality:jt});if(!c)return console.warn(`[polotno-video-export] Browser doesn't support audio encoding, video will be generated without audio. Tried codecs: `+s.join(`, `)),{audioBufferSource:null};let l=new zr({codec:c,quality:jt});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function _i(e,t,n){let r=t[n];return r&&e>=r.startTime&&e<r.startTime+r.duration?n:t.findIndex(t=>e>=t.startTime&&e<t.startTime+t.duration)}async function vi(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_exportCanvases:i})}async function yi(e,t,n,r,i,a,o,s,c){let l=1e3/a,u=Math.floor(i/1e3*a)||1;s?.(0,void 0,{stage:`frames`,completed:0,total:u});let d=e.timingPreview;e.setTimingPreview(`playhead`);try{c?.throwIfAborted(),e.setElementsPixelRatio(o);let d=-1,f=0;for(let p=0;p<u;p++){c?.throwIfAborted();let m=Date.now(),h=p/a,g=1/a,_=h*1e3;p===0&&(_=1),p===u-1&&(_=Math.min(i-1,(p+1)*l-1));let v=_i(_,r,d);if(v!==d&&v>=0&&(e.activePage.set({_rendering:!1}),e.selectPage(e.pages[v].id),e.activePage.set({_rendering:!0}),await e.waitLoading(),c?.throwIfAborted(),d=v),await vi(e,_,v,o,n),c?.throwIfAborted(),await t(h,g),s){let e=Date.now();if(p===u-1||e-f>=300){let t=e-m;s((p+1)/u*.95,t,{stage:`frames`,completed:p+1,total:u}),f=e,await new Promise(e=>setTimeout(e,0))}}}}finally{e.pages.forEach(e=>{e.set({_rendering:!1})}),e.setCurrentTime(0),e.setTimingPreview(d)}}async function bi(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw ei(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function xi(e,t){return e.decodeAudioData(t)}function Si(e){return e.startsWith(`data:`)}function Ci(e){return e.startsWith(`file://`)}function wi(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function Ti(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}async function Ei(e,t){try{if(wi(e))return new it({source:new Le(e),formats:Je});if(Si(e)){let t=Ti(e);return new it({source:new ze(t),formats:Je})}if(Ci(e)){let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new it({source:new ze(n),formats:Je})}{let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new it({source:new ze(n),formats:Je})}}catch(n){return $(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function Di(e,t){try{t?.throwIfAborted();let n=await Ei(e,t);if(!n)return console.log(`[polotno-video-export] checkVideoAudio: createInputFromSource returned null for ${e.slice(0,80)}`),{hasAudio:!1,input:null};let r=await n.getAudioTracks();if(t?.aborted)throw n.dispose(),ai();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if($(n))throw n;if(t?.aborted)throw ai();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function Oi(e,t){let n=e.audios||[],r=ui(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:bi(e.src,t).catch(n=>($(n)||t?.aborted||console.error(`Failed to download audio ${e.src}:`,n),null))})),videoAudios:r.map(e=>({video:e,inputPromise:Di(e.src,t).catch(e=>{if($(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function ki(e,t,n){let r=(e.delay||0)/1e3,i=e.volume===void 0?1:e.volume,a=e.startTime||0,o=e.endTime||1,s=e.speed||1,c=e.duration||n.totalDuration,l=a*c/1e3,u=c*(o-a)/1e3,d=r,f=l,p=Math.min(u,t.duration-l);if(d<0){let e=Math.abs(d)*s;f+=e,p-=e,d=0}if(p<=0||f>=t.duration)return;let m=n.offlineContext.createBufferSource();m.buffer=t;let h=n.offlineContext.createGain();h.gain.value=i,m.connect(h),h.connect(n.offlineContext.destination),m.playbackRate.value=s,m.start(d,f,p)}function Ai(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=rt(e.animations,e.pageDuration),s=(o-a)/1e3,c=Math.max(0,(e.pageStartTime+a)/1e3),l=Math.max(0,r),u=Math.min(i,t.duration-l);if(u<=0||s<=0||l>=t.duration)return;let d=n.offlineContext.createBufferSource();d.buffer=t,d.playbackRate.value=e.speed,d.loop=!0,d.loopStart=l,d.loopEnd=l+u;let f=n.offlineContext.createGain();f.gain.value=e.volume,d.connect(f),f.connect(n.offlineContext.destination),d.start(c,l),d.stop(c+s)}async function ji(e,t,n,r,i,a,o){o?.throwIfAborted();let s=i||Oi(e,o),c=s.storeAudios.length+s.videoAudios.length;if(c===0)return;let l=44100,u=r?.includes(`opus`)?960:1024,d=r===`aac`?3:r?.includes(`opus`)?2:0,f=Math.floor(n/1e3*l),p=Math.floor(f/u)*u,m=d*u,h=Math.max(u,p-m),g=new OfflineAudioContext(2,h,l),_={offlineContext:g,sampleRate:l,totalDuration:n},v=0,y=()=>{v++,a?.(.95+v/c*.02,void 0,{stage:`audio-decode`,completed:v,total:c})};a?.(.95,void 0,{stage:`audio-decode`,completed:0,total:c});let[b,x]=await Promise.all([Promise.all(s.storeAudios.map(async({audio:e,bufferPromise:t})=>{try{o?.throwIfAborted();let n=await t;return o?.throwIfAborted(),n?{audio:e,audioBuffer:await xi(g,n)}:null}catch(t){if($(t))throw t;return console.error(`Failed to process audio ${e.src}:`,t),null}finally{y()}})),Promise.all(s.videoAudios.map(async({video:e,inputPromise:t})=>{try{o?.throwIfAborted();let{hasAudio:n,input:r}=await t;if(o?.throwIfAborted(),!n||!r)return console.log(`[polotno-video-export] Video ${e.id} has no audio track or input failed. hasAudio=${n}, input=${!!r}`),null;let i=await r.getPrimaryAudioTrack();if(!i)return console.log(`[polotno-video-export] Video ${e.id} getPrimaryAudioTrack returned null`),r.dispose(),null;let a=new Be(i),s=[];for await(let e of a.buffers())o?.throwIfAborted(),s.push(e.buffer);if(r.dispose(),o?.throwIfAborted(),s.length===0)return console.log(`[polotno-video-export] Video ${e.id} AudioBufferSink returned 0 buffers`),null;let c=s.reduce((e,t)=>e+t.length,0),l=g.createBuffer(s[0].numberOfChannels,c,s[0].sampleRate),u=0;for(let e of s){for(let t=0;t<e.numberOfChannels;t++)l.getChannelData(t).set(e.getChannelData(t),u);u+=e.length}return{video:e,audioBuffer:l}}catch(t){if($(t))throw t;return console.error(`Failed to extract video audio ${e.src}:`,t),null}finally{y()}}))]);o?.throwIfAborted();for(let e of b)e&&ki(e.audio,e.audioBuffer,_);for(let e of x)e&&Ai(e.video,e.audioBuffer,_);o?.throwIfAborted(),a?.(.97,void 0,{stage:`audio-render`});let ee=await g.startRendering();o?.throwIfAborted(),a?.(.99,void 0,{stage:`audio-encode`}),await t.add(ee)}async function Mi({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){r?.(0,void 0,{stage:`setup`});let o=li(e),s=di(e,o),c=null,l=null,u=!1;if(a){let e=()=>{try{c?.canvasSource.close()}catch{}try{c?.audioBufferSource?.close()}catch{}c&&mi(c.output)};a.addEventListener(`abort`,e,{once:!0}),l=()=>a.removeEventListener(`abort`,e)}try{a?.throwIfAborted();let s=si(e);if(s===0)throw ei(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let l=ci(e),{canvas:d,canvases:f}=pi(o,n),p=async(n,r,a)=>{let o=new $r({target:new vr,format:new Ur});try{let s=new Ir(d,{codec:n,quality:jt,fullCodecString:ni(n,d.width,d.height,t)});o.addVideoTrack(s,{frameRate:t});let c=await gi(o,e,i);return await o.start(),await s.add(r,a),{output:o,canvasSource:s,...c}}catch(e){throw await mi(o),e}},m=new Ur().getSupportedVideoCodecs();await yi(e,async(e,n)=>{c?await c.canvasSource.add(e,n):c=await ii({codecs:m,probe:e=>hi(e,d,t),attempt:t=>p(t,e,n),signal:a})},f,l,s,t,n,r,a);let{output:h,canvasSource:g,audioBufferSource:_,audioCodec:v}=c;g.close();let y=_?Oi(e,a):null;_&&y&&(await ji(e,_,s,v,y,r,a),_.close()),a?.throwIfAborted(),r?.(.99,void 0,{stage:`finalize`}),await h.finalize();let b=h.target,x=new Blob([b.buffer],{type:h.format.mimeType});return u=!0,x}catch(e){throw $(e)?e:a?.aborted?ai():e}finally{l?.(),!u&&c&&await mi(c.output),fi(e,s)}}export{Mi as storeToVideo};
package/dist/index.html CHANGED
@@ -3,7 +3,7 @@
3
3
  <title>Canvas editor</title>
4
4
  <style>body{margin:0;padding:0}</style>
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <script type="module" crossorigin src="./assets/index-DODDd0dH.js"></script>
6
+ <script type="module" crossorigin src="./assets/index-DO5siyU6.js"></script>
7
7
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
8
8
  </head>
9
9
  <body>
package/lib/errors.d.ts CHANGED
@@ -51,6 +51,11 @@ export interface PolotnoErrorDetailsMap {
51
51
  reason: 'busy';
52
52
  } | {
53
53
  reason: 'pdfx';
54
+ } | {
55
+ reason: 'empty-output';
56
+ pageId?: string;
57
+ mimeType: string;
58
+ pixelRatio: number;
54
59
  }) & RenderContext;
55
60
  IMAGE_FAILED: ({
56
61
  reason: 'load';
@@ -83,6 +88,10 @@ export interface PolotnoErrorDetailsMap {
83
88
  reason: 'fetch-failed' | 'decode-failed';
84
89
  family: string;
85
90
  src?: string;
91
+ } | {
92
+ reason: 'load-timeout';
93
+ label: string;
94
+ timeoutMs: number;
86
95
  }) & RenderContext;
87
96
  VIDEO_FAILED: ({
88
97
  reason: 'load';
@@ -1,3 +1,4 @@
1
+ export declare const isHttpsHost: (url: string, hosts: readonly string[]) => boolean;
1
2
  declare const tryRespond: (request: any) => boolean;
2
3
  declare const capture: (response: any) => Promise<void>;
3
4
  export { tryRespond, capture };
package/lib/font-cache.js CHANGED
@@ -13,9 +13,29 @@ import crypto from 'crypto';
13
13
  // 1. an in-memory Map for the lifetime of the process, and
14
14
  // 2. a disk cache shared between processes and across runs (e.g. parallel
15
15
  // test workers), so even a cold process doesn't re-download.
16
+ //
17
+ // A cached URL is answered before the caller's requestInterceptor, so only
18
+ // Google's own hosts may enter: a design names any URL it likes.
16
19
  const FONT_HOSTS = ['fonts.googleapis.com', 'fonts.gstatic.com'];
17
- const isFontUrl = (url) => FONT_HOSTS.some((host) => url.includes(host));
20
+ export const isHttpsHost = (url, hosts) => {
21
+ try {
22
+ const { protocol, hostname } = new URL(url);
23
+ return protocol === 'https:' && hosts.includes(hostname);
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ };
29
+ const isFontUrl = (url) => isHttpsHost(url, FONT_HOSTS);
18
30
  const memoryCache = new Map(); // url -> { contentType, body }
31
+ // Distinct Google URLs are unbounded (any `text=` query is a 200).
32
+ const MAX_MEMORY_ENTRIES = 1000;
33
+ const remember = (url, entry) => {
34
+ if (memoryCache.size >= MAX_MEMORY_ENTRIES) {
35
+ memoryCache.delete(memoryCache.keys().next().value);
36
+ }
37
+ memoryCache.set(url, entry);
38
+ };
19
39
  const FONT_CACHE_DIR = path.join(os.tmpdir(), 'polotno-node-font-cache');
20
40
  const FONT_CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
21
41
  const fontCacheDiskPath = (url) => path.join(FONT_CACHE_DIR, crypto.createHash('sha1').update(url).digest('hex') + '.json');
@@ -62,7 +82,7 @@ const tryRespond = (request) => {
62
82
  if (!cached) {
63
83
  cached = readFontCacheFromDisk(url);
64
84
  if (cached) {
65
- memoryCache.set(url, cached);
85
+ remember(url, cached);
66
86
  }
67
87
  }
68
88
  if (!cached)
@@ -97,7 +117,7 @@ const capture = async (response) => {
97
117
  contentType: response.headers()['content-type'] || '',
98
118
  body,
99
119
  };
100
- memoryCache.set(url, entry);
120
+ remember(url, entry);
101
121
  writeFontCacheToDisk(url, entry);
102
122
  }
103
123
  catch (e) {
package/lib/instance.d.ts CHANGED
@@ -14,6 +14,12 @@ declare global {
14
14
  }
15
15
  }
16
16
  export { URL_FIELDS, forEveryUrlField } from '@polotno/schema/asset-urls';
17
+ /**
18
+ * `allowLocalFiles: false`: reject a design that names any `file:` source,
19
+ * before anything is downloaded or rendered. A design that may not read this
20
+ * host's disk is invalid input, so the error is DESIGN_INVALID.
21
+ */
22
+ export declare const assertNoLocalFiles: (json: any) => void;
17
23
  /**
18
24
  * Rewrite every `file:` source in a design to a URL the client can load with
19
25
  * any API. Designs without one — the common case — come back untouched, so this
@@ -22,7 +28,6 @@ export { URL_FIELDS, forEveryUrlField } from '@polotno/schema/asset-urls';
22
28
  */
23
29
  export declare const serveLocalFiles: (json: any) => {
24
30
  json: any;
25
- serving: boolean;
26
31
  release: () => void;
27
32
  };
28
33
  export declare const guessExtension: (contentType: any, kind: any) => any;