polotno-node 3.11.0 → 3.12.1

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-hePW80VL.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,H as m,Ht as h,I as g,It as _,J as v,K as y,L as b,Lt as x,M as S,Mt as ee,N as te,Nt as ne,O as re,Ot as ie,P as ae,Pt as oe,Q as se,R as ce,Rt as le,S as ue,St as de,T as C,Tt as fe,U as pe,Ut as me,V as he,Vt as ge,W as _e,Wt as ve,X as ye,Y as be,Z as xe,_ as Se,_t as Ce,a as we,at as Te,b as w,bt as Ee,c as De,ct as Oe,d as ke,dt as Ae,et as je,f as Me,ft as Ne,g as Pe,gt as Fe,h as Ie,ht as Le,i as Re,it as ze,j as Be,jt as Ve,k as He,kt as Ue,l as T,lt as We,m as Ge,mt as E,n as Ke,nt as qe,o as Je,ot as Ye,p as Xe,pt as Ze,q as Qe,r as $e,rt as et,s as tt,st as nt,tt as rt,u as D,ut as O,v as it,vt as at,w as ot,wt as k,x as A,xt as st,y as ct,yt as lt,z as ut,zt as j}from"./index-BIKy_ifH.js";var dt=`Mediabunny v1.61.1`,ft=new Map,pt=new Map,mt=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!C.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${C.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&&Xe(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.`);ht(e.codec,e)},ht=(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&&Be(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.`)},gt=e=>{let n=e.bitrateMode,r=e.quality._toVideoRateControl(e.codec,e.width,e.height,n),i=(n,r,i)=>({codec:e.fullCodecString??s(e.codec,e.width,e.height,i,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:n,bitrateMode:r,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...t(e.codec)}),a=[];return r.quantizer!==null&&a.push({config:i(void 0,`quantizer`,r.bitrate),quantizer:r.quantizer}),r.bitrateMode!==`quantizer`&&a.push({config:i(r.bitrate,r.bitrateMode,r.bitrate),quantizer:null}),O(a.length>0),a},_t=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!A.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${A.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(a.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.`);vt(e.codec,e)},vt=(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&&Be(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},yt=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??l(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 bt):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`?bt[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=xt[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&&(O(this._quality!==void 0),a=E(Math.round(c(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&&(O(a!==null&&i),r=E((a-i.worst)/(i.best-i.worst),0,1)),s=Ct(e,t,n,St(r))}return{quantizer:a,bitrate:s,bitrateMode:o}}_toVideoBitrate(e,t,n){return this._bitrate===void 0?(O(this._quality!==void 0),Ct(e,t,n,St(this._quality))):this._bitrate}_toAudioBitrate(e){if(a.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=St(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}},bt={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},xt={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},St=e=>.3*Math.exp(2.5538*e),Ct=(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},wt=(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}};O(!1)},Tt=new M(`high`),Et=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!C.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.`);ht(e,s);let c=Ot(i,a)??new M(`medium`),l;try{l=gt({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let u=JSON.stringify(l),d=ft.get(u);if(d)return d;let f=(async()=>{for(let{config:t}of l)if(De.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 l){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!lt()||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:wt(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return ft.set(u,f),f},Dt=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:o,...s}=t;if(!A.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&&o!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(o!==void 0&&!(o instanceof M)&&(!Number.isInteger(o)||o<=0))throw TypeError(`bitrate must be a positive integer.`);vt(e,s);let c=yt({codec:e,numberOfChannels:n,sampleRate:r,quality:Ot(i,o)??new M(`medium`),...s}),l=JSON.stringify(c),u=pt.get(l);if(u)return u;let d=(async()=>{if(tt.some(t=>t.supports(e,c))||a.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return pt.set(l,d),d},Ot=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof M?t:new M({bitrate:t})},kt=async(e,t)=>{for(let n of e)if(await Dt(n,t))return n;return null},At=class{constructor(e){this.mutex=new et,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)}}},jt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Mt=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`)},Nt=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);O(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]]),Pt=e=>(P.setInt16(0,e,!1),[N[0],N[1]]),Ft=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]]),It=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]]),Lt=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]]),Rt=e=>(P.setInt32(0,2**30*e,!1),[N[0],N[1],N[2],N[3]]),zt=(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},Bt=e=>[B(e[0]),B(e[1]),Rt(e[2]),B(e[3]),B(e[4]),Rt(e[5]),B(e[6]),B(e[7]),Rt(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),Ft(n),r??[]],i),Vt=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`)]),Ht=()=>H(`styp`,[V(`iso5`),L(0),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]),Ut=(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)])},Wt=e=>({type:`mdat`,largeSize:e}),Gt=e=>({type:`free`,size:e}),W=e=>H(`moov`,void 0,[Kt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>qt(t,e.creationTime)),e.isFragmented?Fn(e.trackDatas):null,Xn(e)]),Kt=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!k(e)||!k(n),a=i?z:L;return U(`mvhd`,+i,0,[a(e),a(e),L(X),a(n),B(1),Lt(1),Array(10).fill(0),Bt(nt),Array(24).fill(0),L(r)])},qt=(e,t)=>{let n=gr(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return H(`trak`,void 0,[Jt(e,t),r?Yt(e):null,Xt(e,t),n.name===void 0?null:H(`udta`,void 0,[H(`name`,[...x.encode(n.name)])])])},Jt=(e,t)=>{let n=Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)),r=!k(t)||!k(n),i=r?z:L,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=Ue(Ve(t??0),ne(n?-1:1,1));a=Ze(r,e.info.width,e.info.height)}else a=nt;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let s=e.type===`video`?0:e.type===`audio`?1:e.type===`subtitle`?2:Ae(e);return U(`tkhd`,+r,o,[i(t),i(t),L(e.track.id),L(0),i(n),Array(8).fill(0),I(0),I(s),Lt(+(e.type===`audio`)),I(0),Bt(a),B(e.type===`video`?e.info.width:0),B(e.type===`video`?e.info.height:0)])},Yt=e=>{let t=e.startTimestampOffset;if(O(t!==null),t>0){let n=Z(t,X),r=Z(Q(e),X),i=!k(n)||!k(r),a=i?z:L,o=i?It:R;return H(`edts`,void 0,[U(`elst`,+!!i,0,[L(2),a(n),o(-1),B(1),a(r),o(0),B(1)])])}{let n=Z(-t,e.timescale),r=Math.max(0,Z(Q(e),X)+Z(t,X)),i=!Ee(n)||!k(r),a=i?z:L,o=i?It:R;return H(`edts`,void 0,[U(`elst`,+!!i,0,[L(1),a(r),o(n),B(1)])])}},Xt=(e,t)=>H(`mdia`,void 0,[Zt(e,t),en(!0,Qt[e.type],$t[e.type]),tn(e)]),Zt=(e,t)=>{let n=Z(Q(e),e.timescale),r=!k(t)||!k(n),i=r?z:L;return U(`mdhd`,+r,0,[i(t),i(t),L(e.timescale),i(n),I(cr(e.track.metadata.languageCode??`und`)),I(0)])},Qt={video:`vide`,audio:`soun`,subtitle:`text`},$t={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},en=(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)]),tn=e=>H(`minf`,void 0,[nn[e.type](),rn(),sn(e)]),nn={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)},rn=()=>H(`dinf`,void 0,[an()]),an=()=>U(`dref`,0,0,[L(1)],[on()]),on=()=>U(`url `,0,1),sn=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return H(`stbl`,void 0,[cn(e),On(e),t?Nn(e):null,t?Pn(e):null,An(e),jn(e),Mn(e),kn(e)])},cn=e=>{let t;if(e.type===`video`)t=ln(nr(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=ir(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);O(n),t=_n(n,e)}else e.type===`subtitle`&&(t=En(or[e.track.source._codec],e));return O(t),U(`stsd`,0,0,[L(1)],[t])},ln=(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(dt.length),V(dt),Array(31-dt.length).fill(0),I(t.info.hasAlphaChannel?32:24),Pt(65535)],[rr[t.track.source._codec]?.(t)??null,dn(t),Le(t.info.decoderConfig.colorSpace)?null:fn(t),un(t)]),un=e=>e.avgBitrate===0&&e.maxBitrate===0?null:H(`btrt`,[L(0),L(e.maxBitrate),L(e.avgBitrate)]),dn=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:H(`pasp`,[L(e.info.pixelAspectRatio.num),L(e.info.pixelAspectRatio.den)]),fn=e=>{let t=e.info.decoderConfig.colorSpace;return H(`colr`,[V(e.muxer.isQuickTime?`nclc`:`nclx`),I(t?.primaries==null?2:ze[t.primaries]),I(t?.transfer==null?2:We[t.transfer]),I(t?.matrix==null?2:Oe[t.matrix]),e.muxer.isQuickTime?[]:F(!!t?.fullRange<<7)])},pn=e=>e.info.decoderConfig&&H(`avcC`,[...j(e.info.decoderConfig.description)]),mn=e=>e.info.decoderConfig&&H(`hvcC`,[...j(e.info.decoderConfig.description)]),hn=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?ze[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?We[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Oe[t.colorSpace.matrix]:1;return U(`vpcC`,1,0,[F(r),F(i),F(c),F(l),F(u),F(d),I(0)])},gn=e=>H(`av1C`,re(e.info.decoderConfig.codec)),_n=(e,t)=>{let n=0,r,i=16,o=a.includes(t.track.source._codec);if(o){let e=t.track.source._codec,{sampleSize:r}=S(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=o?0:-2;r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(Math.min(i,16)),Pt(e),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0),o?[L(1),L(i/8),L(t.info.numberOfChannels*i/8)]:[L(0),L(0),L(0)],L(2)]}return H(e,r,[ar(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,un(t)])},vn=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),...Ft(0),...L(e.maxBitrate),...L(e.avgBitrate)];if(e.info.decoderConfig.description){let t=j(e.info.decoderConfig.description);n=[...n,...F(5),...zt(t.byteLength),...t]}return n=[...I(1),...F(0),...F(4),...zt(n.length),...n,...F(6),...F(1),...F(2)],n=[...F(3),...zt(n.length),...n],U(`esds`,0,0,n)},G=e=>H(`wave`,void 0,[yn(e),bn(e),H(`\0\0\0\0`)]),yn=e=>H(`frma`,[V(ir(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),bn=e=>{let{littleEndian:t}=S(e.track.source._codec);return H(`enda`,[I(+t)])},xn=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){O(s.byteLength>=18);let e=j(s),c=p(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),Pt(i),F(a),...o])},Sn=e=>{let t=e.info.decoderConfig?.description;return O(t),U(`dfLa`,0,0,[...j(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=S(e.track.source._codec);return U(`pcmC`,0,0,[F(+t),F(8*n)])},Cn=e=>{O(e.info.primingPacket);let t=m(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 se(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])},wn=e=>{O(e.info.primingPacket);let t=_e(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 se(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])},Tn=e=>{O(e.info.primingPacket);let t=pe(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`,[...g(t)])},En=(e,t)=>H(e,[[,,,,,,].fill(0),I(1)],[sr[t.track.source._codec](t),un(t)]),Dn=e=>H(`vttC`,[...x.encode(e.info.config.description)]),On=e=>U(`stts`,0,0,[L(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[L(e.sampleCount),L(e.sampleDelta)])]),kn=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))])},An=e=>U(`stsc`,0,0,[L(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[L(e.firstChunk),L(e.samplesPerChunk),L(1)])]),jn=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=S(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))])},Mn=e=>e.finalizedChunks.length>0&&u(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))]),Nn=e=>U(`ctts`,1,0,[L(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[L(e.sampleCount),R(e.sampleCompositionTimeOffset)])]),Pn=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;O(e.compositionTimeOffsetTable.length>0),O(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)])},Fn=e=>H(`mvex`,void 0,e.map(In)),In=e=>U(`trex`,0,0,[L(e.track.id),L(1),L(0),L(0),L(0)]),Ln=(e,t)=>H(`moof`,void 0,[Rn(e),...t.map(Bn)]),Rn=e=>U(`mfhd`,0,0,[L(e)]),zn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Bn=e=>H(`traf`,void 0,[Vn(e),Hn(e),Un(e)]),Vn=e=>{O(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:zn(n)};return U(`tfhd`,0,t,[L(e.track.id),L(r.duration),L(r.size),L(r.flags)])},Hn=e=>(O(e.currentChunk),U(`tfdt`,1,0,[z(Z(e.currentChunk.startTimestamp,e.timescale))])),Un=e=>{O(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(zn),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]):[]])])},Wn=e=>H(`mfra`,void 0,[...e.map(Gn),Kn()]),Gn=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)])]),Kn=()=>U(`mfro`,0,0,[L(0)]),qn=()=>H(`vtte`),Jn=(e,t,n,r,i)=>H(`vttc`,void 0,[i===null?null:H(`vsid`,[R(i)]),n===null?null:H(`iden`,[...x.encode(n)]),t===null?null:H(`ctim`,[...x.encode(Mt(t))]),r===null?null:H(`sttg`,[...x.encode(r)]),H(`payl`,[...x.encode(e)])]),Yn=e=>H(`vtta`,[...x.encode(e)]),Xn=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=er(r);e&&t.push(e)}else if(n===`mdta`){let e=tr(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Zn(t,e.output._metadataTags);return t.length===0?null:H(`udta`,void 0,t)},Zn=(e,t)=>{for(let{key:n,value:r}of fe(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:Ae(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=x.encode(t);return H(e,[I(n.length),I(cr(`und`)),Array.from(n)])},Qn={"image/jpeg":13,"image/png":14,"image/bmp":27},$n=(t,n)=>{let r=[];for(let{key:e,value:i}of fe(t))switch(e){case`title`:r.push({key:n?`title`:`©nam`,value:J(i)});break;case`description`:r.push({key:n?`description`:`©des`,value:J(i)});break;case`artist`:r.push({key:n?`artist`:`©ART`,value:J(i)});break;case`album`:r.push({key:n?`album`:`©alb`,value:J(i)});break;case`albumArtist`:r.push({key:n?`album_artist`:`aART`,value:J(i)});break;case`comment`:r.push({key:n?`comment`:`©cmt`,value:J(i)});break;case`genre`:r.push({key:n?`genre`:`©gen`,value:J(i)});break;case`beatsPerMinute`:n||r.push({key:`tmpo`,value:H(`data`,[L(21),L(0),I(i)])});break;case`lyrics`:r.push({key:n?`lyrics`:`©lyr`,value:J(i)});break;case`date`:r.push({key:n?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&r.push({key:`covr`,value:H(`data`,[L(Qn[e.mimeType]??0),L(0),Array.from(e.data)])});break;case`trackNumber`:if(n){let e=t.tracksTotal===void 0?i.toString():`${i}/${t.tracksTotal}`;r.push({key:`track`,value:J(e)})}else r.push({key:`trkn`,value:H(`data`,[L(0),L(0),I(0),I(i),I(t.tracksTotal??0),I(0)])});break;case`discNumber`:n||r.push({key:`disc`,value:H(`data`,[L(0),L(0),I(0),I(i),I(t.discsTotal??0),I(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ae(e)}if(t.raw)for(let i in t.raw){let a=t.raw[i];a==null||!n&&i.length!==4||r.some(e=>e.key===i)||(typeof a==`string`?r.push({key:i,value:J(a)}):a instanceof Uint8Array?r.push({key:i,value:H(`data`,[L(0),L(0),Array.from(a)])}):a instanceof e&&r.push({key:i,value:H(`data`,[L(Qn[a.mimeType]??0),L(0),Array.from(a.data)])}))}return r},er=e=>{let t=$n(e,!1);return t.length===0?null:U(`meta`,0,0,void 0,[en(!1,`mdir`,``,`appl`),H(`ilst`,void 0,t.map(e=>H(e.key,void 0,[e.value])))])},tr=e=>{let t=$n(e,!0);return t.length===0?null:H(`meta`,void 0,[en(!1,`mdta`,``),U(`keys`,0,0,[L(t.length)],t.map(e=>H(`mdta`,[...x.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),...x.encode(e)]),nr=(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}},rr={avc:pn,hevc:mn,vp8:hn,vp9:hn,av1:gn,prores:null},ir=(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`}},ar=(e,t)=>{switch(e){case`aac`:return vn;case`mp3`:return vn;case`opus`:return xn;case`vorbis`:return vn;case`flac`:return Sn;case`ac3`:return Cn;case`eac3`:return wn;case`dts`:return Tn}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},or={webvtt:`wvtt`},sr={webvtt:Dn},cr=e=>{O(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},lr=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(){O(!this.started),this.target._start(),this.started=!0}write(e){O(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 O(this.started&&!this.finalized),this.target._flush()}async finalize(){O(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}};Se();var Y=class extends Ye{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 pr(this,e)}},ur=2**16,dr=2**32,fr=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(ur,{maxByteLength:dr})}catch{this._buffer=new ArrayBuffer(ur),this._supportsResize=!1}else this._buffer=new ArrayBuffer(ur);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>dr)throw Error(`ArrayBuffer exceeded maximum size of ${dr} 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)}},pr=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)}},mr=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,hr=2082844800,gr=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},_r=class extends At{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new fr,this.auxWriter=new lr(this.auxTarget,!1),this.auxBoxWriter=new Nt(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=n(),this.creationTime=Math.floor(Date.now()/1e3)+hr,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 Lr,this.isCmaf=t instanceof Ir,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Ir?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 fr:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Nt(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof fr&&`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 lr(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Nt(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(O(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Vt({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||(O(this.writer),O(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Wt(!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 ct({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 i=this.trackDatas.find(t=>t.track===e);if(i)return i;d(n,e.source._codec),O(n),O(n.decoderConfig);let a={...n.decoderConfig};O(a.codedWidth!==void 0),O(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=ut(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.`);a.description=y(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=r(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.`);a.description=Qe(e),o=!0}let s=Fe(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:_({num:c*a.codedHeight,den:l*a.codedWidth}),f=a.codec===`ap4h`||a.codec===`ap4x`,p={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:o,hasAlphaChannel:f},timescale:s,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(p),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;te(n,e.source._codec),O(n),O(n.decoderConfig);let i={...n.decoderConfig},o=!1;if(e.source._codec===`aac`&&!i.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=it(Ke.tempFromBytes(t.data));if(!e)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 n=be[e.samplingFrequencyIndex],r=v[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=ye({objectType:e.objectType,outputSampleRate:n,outputNumberOfChannels:r}),o=!0}if(!t){if(e.source._codec===`ac3`||e.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(e.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let s={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&a.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:t},timescale:i.sampleRate,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(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;ae(t),O(t),O(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=[...he(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=b(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=it(Ke.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=S(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}=S(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)O(r.timestamp<=t),O(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=qn();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;jt.lastIndex=0;let r=jt.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=Yn(n.notes);this.auxBoxWriter.writeBox(e)}let c=Jn(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){O(!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=u(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){O(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(O(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=u(e.timeToSampleTable);if(O(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=u(e.compositionTimeOffsetTable);O(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,O(e.lastSample),O(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){O(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(O(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}),O(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(O(!this.isFragmented),O(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||u(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)O(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(O(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(O(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;O(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){O(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Nt(this.writer);let e=this.boxWriter.measureBox(Ht()),t=this.boxWriter.measureBox(Ut(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}O(this.writer),O(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=Ln(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];O(n.currentChunk),O(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=Ln(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}O(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Wt(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(){O(this.writer),O(this.boxWriter),this.ensureOneEnabledTrack();let e=W(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;O(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Wt(!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(){O(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;O(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(){O(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(O(this.writer),O(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Wt(!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)O(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)O(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(Ht()),this.boxWriter.writeBox(Ut(this,e))}else{let e=this.writer.getPos(),t=Wn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{O(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);O(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`){O(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(Gt(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()}},vr=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(){O(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()}O(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;O(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;O(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 T({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}},yr=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},br=(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}),xr=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})()}},Sr=class extends xr{constructor(e){if(super(),!C.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${C.join(`, `)}.`);this._codec=e}},Cr=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},wr=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.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 Te,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`&&(O(this.outputWidth),O(this.outputHeight),O(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=Ce(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(o(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let i=[];try{for(let n of t)n instanceof D?i.push(n):typeof VideoFrame<`u`&&n instanceof VideoFrame?i.push(new D(n)):i.push(new D(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 D&&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),O(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{O(this.encoder);let t=e.toVideoFrame(),n=Ne(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 Er;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;O(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=yr(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{br(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=Ot(this.encodingConfig.quality,this.encodingConfig.bitrate);O(t!==void 0);let n=gt({...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=De.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(ie(`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=wt(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 w))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.`);Cr(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.createWebCodecsEncoders()),O(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let e=this.encoderConfig;O(e);let t=[],n=[],r=0,i=0,a=(e,t)=>{if(at(e)){this.encodersReclaimed=!0;return}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();O(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(O(o!==void 0),this.addPacket(o.chunk,e,o.meta),r++;n.length>0&&n[0]===r;){n.shift();let e=t.shift();O(e!==void 0),this.addPacket(e.chunk,null,e.meta)}},error:e=>a(e,o)}),this.alphaEncoder.configure(e)}}addPacket(e,t,n){let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=w.fromEncodedChunk(e,r),a=Ne(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],s=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(s=ce(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||s!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:s??void 0})),Cr(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){O(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=Ce(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 i(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}},Tr=null,Er=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Tr){let e=new Blob([`(${Dr.toString()})()`],{type:`application/javascript`});Tr=URL.createObjectURL(e)}this.worker=new Worker(Tr),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++,r=n();return this.pendingRequests.set(t,r),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),r.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()}},Dr=()=>{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,S=a?512:o?2048:128;s===1?y.fill(S,x):new Uint16Array(y.buffer,x,2*_).fill(S);let ee=a?`I420P10`:o?`I420P12`:`I420`,te=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),ne={format:ee,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:te,alphaFrame:new VideoFrame(y,ne)}}},Or=class extends Sr{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.`);mt(t),super(t.codec),this._encoder=new wr(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 D(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},kr=class extends xr{constructor(e){if(super(),!A.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${A.join(`, `)}.`);this._codec=e}},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.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Te,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 vr({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&&Me(e.format)!==n.transform.sampleFormat){let r=ke(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(o(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof T))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 T&&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),O(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 T({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{O(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){O(this.outputSampleSize),O(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 w(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=Ot(this.encodingConfig.quality,this.encodingConfig.bitrate),i=yt({numberOfChannels:t,sampleRate:n,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(i),this.source._nominalBitrate=i.bitrate??null;let o=tt.find(e=>e.supports(this.encodingConfig.codec,i));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof w))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(a.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(ie(`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){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||xe(j(t.decoderConfig.description)).objectType===0,e){let e=Number(u(i.codec.split(`.`)));t.decoderConfig.description=ye({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=w.fromEncodedChunk(e);n=n.clone({timestamp:ee(n.timestamp,i.sampleRate),duration:e.duration==null?void 0:ee(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)}O(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}=S(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,E(Math.round(n*128)+128,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,E(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=E(Math.round(n*32768),-32768,32767);e.setUint8(t,Je(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=E(Math.round(n*32768),-32768,32767);e.setUint8(t,we(r))}:O(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,E(Math.round(n*32768)+32768,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,E(Math.round(n*32768),-32768,32767),r):O(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>f(e,t,E(Math.round(n*8388608)+8388608,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>oe(e,t,E(Math.round(n*8388608),-8388608,8388607),r):O(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,E(Math.round(n*2147483648)+2147483648,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,E(Math.round(n*2147483648),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):O(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):O(!1);break;default:Ae(n),O(!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}},jr=class extends kr{constructor(e,t={}){if(_t(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 Ar(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=T._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)}},Mr=class extends xr{constructor(e){if(super(),!ot.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ot.join(`, `)}.`);this._codec=e}},Nr=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>C.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>A.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ot.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Pr=class extends Nr{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&&(!de(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 _r(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Fr=class extends Pr{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...C,...ue,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...ot]}_codecUnsupportedHint(e){return new Lr().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Ir=class extends Pr{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...C,...ue,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...ot]}},Lr=class extends Pr{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...C,...A]}_codecUnsupportedHint(e){return new Fr().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Rr=[`video`,`audio`,`subtitle`],zr=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=le(this.metadata.group),r=le(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}},Br=class extends zr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Vr=class extends zr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Hr=class extends zr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Ur=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)}},Wr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!st(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&&rt(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 Ur)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Ur))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},Gr=class extends Ye{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(o(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Ur,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new et,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 Nr))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof mr))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){O(this._target instanceof mr);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return o(t)?t.then(n):n(t)}async _getTarget(e){O(this._target instanceof mr);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(O(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 o(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new lr(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Sr))throw TypeError(`source must be a VideoSource.`);if(Wr(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&&d({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof w))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 Br(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof kr))throw TypeError(`source must be an AudioSource.`);if(Wr(t),t.decoderConfig!==void 0&&te({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof w))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 Vr(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Mr))throw TypeError(`source must be a SubtitleSource.`);Wr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Hr(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(je(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 Rr)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 Rr){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?(qe._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`&&qe._warn(`Output has already been finalized.`);return}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?(qe._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()}})()}},Kr=ve,qr=[{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 Jr(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=qr.find(s),l=qr.find(e=>s(e)&&o*r<=e.maxMacroblocksPerSecond&&Math.max(i,a)<=Math.sqrt(e.maxMacroblocks*8))??qr[qr.length-1];if(c&&l!==c)return`avc1.6400${l.levelIdc.toString(16).padStart(2,`0`)}`}function Yr(e){return e instanceof Error&&/is not (supported|available) in this environment/.test(e.message)}async function Xr({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 me(()=>t(s),{...r,shouldRetry:Yr});return i&&console.warn(`[polotno-video-export] Encoding with ${s}: ${i.message}`),e}catch(e){if(!Yr(e))throw e;i=e}}throw Kr(`VIDEO_FAILED`,`Your browser doesn't support video encoding. Tried ${a.join(`, `)}; last error: ${i?.message}`,{reason:`no-encoder`},i)}function Zr(){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 Qr(e){return Math.round(e/2)*2}function $r(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function ei(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 ti(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:Qr(t),height:Qr(n)}}function ni(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 ri(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 ii(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 ai(e,t){let n=h(),r=n.sceneCanvas._canvas;if(r.width=e.width*t,r.height=e.height*t,r.width<=0||r.height<=0)throw Kr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}var oi=e=>e.cancel().catch(()=>{});function si(e,t,n){let{width:r,height:i}=t;return Et(e,{width:r,height:i,quality:Tt,fullCodecString:Jr(e,r,i,n)})}async function ci(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=ni(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 kt(s,{numberOfChannels:2,sampleRate:44100,quality:Tt});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 jr({codec:c,quality:Tt});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function li(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 ui(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function di(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=li(_,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 ui(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 fi(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw Kr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function pi(e,t){return e.decodeAudioData(t)}function mi(e){return e.startsWith(`data:`)}function hi(e){return e.startsWith(`file://`)}function gi(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function _i(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 vi(e,t){try{if(gi(e))return new $e({source:new Pe(e),formats:Ge});if(mi(e)){let t=_i(e);return new $e({source:new Ie(t),formats:Ge})}if(hi(e)){let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new $e({source:new Ie(n),formats:Ge})}{let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new $e({source:new Ie(n),formats:Ge})}}catch(n){return $(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function yi(e,t){try{t?.throwIfAborted();let n=await vi(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(),Zr();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if($(n))throw n;if(t?.aborted)throw Zr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function bi(e,t){let n=e.audios||[],r=ni(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:fi(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:yi(e.src,t).catch(e=>{if($(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function xi(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 Si(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=ge(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 Ci(e,t,n,r,i,a,o){o?.throwIfAborted();let s=i||bi(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 pi(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 Re(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&&xi(e.audio,e.audioBuffer,_);for(let e of x)e&&Si(e.video,e.audioBuffer,_);o?.throwIfAborted(),a?.(.97,void 0,{stage:`audio-render`});let S=await g.startRendering();o?.throwIfAborted(),a?.(.99,void 0,{stage:`audio-encode`}),await t.add(S)}async function wi({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){r?.(0,void 0,{stage:`setup`});let o=ti(e),s=ri(e,o),c=null,l=null,u=!1;if(a){let e=()=>{try{c?.canvasSource.close()}catch{}try{c?.audioBufferSource?.close()}catch{}c&&oi(c.output)};a.addEventListener(`abort`,e,{once:!0}),l=()=>a.removeEventListener(`abort`,e)}try{a?.throwIfAborted();let s=$r(e);if(s===0)throw Kr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let l=ei(e),{canvas:d,canvases:f}=ai(o,n),p=async(n,r,a)=>{let o=new Gr({target:new fr,format:new Fr});try{let s=new Or(d,{codec:n,quality:Tt,fullCodecString:Jr(n,d.width,d.height,t)});o.addVideoTrack(s,{frameRate:t});let c=await ci(o,e,i);return await o.start(),await s.add(r,a),{output:o,canvasSource:s,...c}}catch(e){throw await oi(o),e}},m=new Fr().getSupportedVideoCodecs();await di(e,async(e,n)=>{if(c){await c.canvasSource.add(e,n);return}c=await Xr({codecs:m,probe:e=>si(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=_?bi(e,a):null;_&&y&&(await Ci(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?Zr():e}finally{l?.(),!u&&c&&await oi(c.output),ii(e,s)}}export{wi as storeToVideo};
@@ -0,0 +1,3 @@
1
+ function e(e,t){this.v=e,this.k=t}function t(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function n(e){if(Array.isArray(e))return e}function r(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function i(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function a(e,t){return n(e)||r(e,t)||o(e,t)||i()}function o(e,n){if(e){if(typeof e==`string`)return t(e,n);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}function s(t){var n,r;function i(n,r){try{var o=t[n](r),s=o.value,c=s instanceof e;Promise.resolve(c?s.v:s).then(function(e){if(c){var r=n===`return`&&s.k?n:`next`;if(!s.k||e.done)return i(r,e);e=t[r](e).value}a(!!o.done,e)},function(e){i(`throw`,e)})}catch(e){a(2,e)}}function a(e,t){e===2?n.reject(t):n.resolve({value:t,done:e}),(n=n.next)?i(n.key,n.arg):r=null}this._invoke=function(e,t){return new Promise(function(a,o){var s={key:e,arg:t,resolve:a,reject:o,next:null};r?r=r.next=s:(n=r=s,i(e,t))})},typeof t.return!=`function`&&(this.return=void 0)}s.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},s.prototype.next=function(e){return this._invoke(`next`,e)},s.prototype.throw=function(e){return this._invoke(`throw`,e)},s.prototype.return=function(e){return this._invoke(`return`,e)};var c=Object.entries,l=Object.setPrototypeOf,u=Object.isFrozen,d=Object.getPrototypeOf,f=Object.getOwnPropertyDescriptor,p=Object.freeze,m=Object.seal,h=Object.create,ee=typeof Reflect<`u`&&Reflect,te=ee.apply,ne=ee.construct;p||=function(e){return e},m||=function(e){return e},te||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},ne||=function(e){return new e(...[...arguments].slice(1))};var g=w(Array.prototype.forEach);Array.prototype.indexOf;var re=w(Array.prototype.lastIndexOf),ie=w(Array.prototype.pop),ae=w(Array.prototype.push);Array.prototype.slice;var oe=w(Array.prototype.splice),_=Array.isArray,se=w(String.prototype.toLowerCase),ce=w(String.prototype.toString),le=w(String.prototype.match),ue=w(String.prototype.replace),de=w(String.prototype.indexOf),fe=w(String.prototype.trim),pe=w(Number.prototype.toString),v=w(Boolean.prototype.toString),y=typeof BigInt>`u`?null:w(BigInt.prototype.toString),me=typeof Symbol>`u`?null:w(Symbol.prototype.toString),b=w(Object.prototype.hasOwnProperty),x=w(Object.prototype.toString),S=w(RegExp.prototype.test),C=T(TypeError);function w(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return te(e,t,n)}}function T(e){return function(){return ne(e,[...arguments])}}function E(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:se;if(l&&l(e,null),!_(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(u(t)||(t[r]=e),i=e)}e[i]=!0}return e}function he(e){for(let t=0;t<e.length;t++)b(e,t)||(e[t]=null);return e}function D(e){let t=h(null);for(let r of c(e)){var n=a(r,2);let i=n[0],o=n[1];b(e,i)&&(t[i]=_(o)?he(o):o&&typeof o==`object`&&o.constructor===Object?D(o):o)}return t}function ge(e){switch(typeof e){case`string`:return e;case`number`:return pe(e);case`boolean`:return v(e);case`bigint`:return y?y(e):`0`;case`symbol`:return me?me(e):`Symbol()`;case`undefined`:return x(e);case`function`:case`object`:{if(e===null)return x(e);let t=e,n=O(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:x(e)}return x(e)}default:return x(e)}}function O(e,t){for(;e!==null;){let n=f(e,t);if(n){if(n.get)return w(n.get);if(typeof n.value==`function`)return w(n.value)}e=d(e)}function n(){return null}return n}function _e(e){try{return S(e,``),!0}catch{return!1}}var ve=p(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),ye=p(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),be=p([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),xe=p([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Se=p(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Ce=p([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),we=p([`#text`]),Te=p(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),Ee=p(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.pointer-events.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.vector-effect.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),De=p(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Oe=p([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),ke=m(/{{[\w\W]*|^[\w\W]*}}/g),Ae=m(/<%[\w\W]*|^[\w\W]*%>/g),je=m(/\${[\w\W]*/g),Me=m(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ne=m(/^aria-[\-\w]+$/),Pe=m(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Fe=m(/^(?:\w+script|data):/i),Ie=m(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Le=m(/^html$/i),Re=m(/^[a-z][.\w]*(-[.\w]+)+$/i),ze=m(/<[/\w!]/g),Be=m(/<[/\w]/g),Ve=m(/<\/no(script|embed|frames)/i),He=m(/\/>/i),k={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},A=[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`],Ue=p(E({},A)),We=function(){let e={};return g(A,t=>{e[t]=m(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),p(e)}(),Ge=function(){return typeof window>`u`?null:window},Ke=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},qe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},j=function(e,t,n,r){return b(e,t)&&_(e[t])?E(r.base?D(r.base):{},e[t],r.transform):n},Je=function(e,t,n){let r=b(e,t)?e[t]:void 0;return r&&typeof r==`object`?D(r):n()};function Ye(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ge(),t=e=>Ye(e);if(t.version=`3.4.16`,t.removed=[],!e||!e.document||e.document.nodeType!==k.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,d=e.trustedTypes,f=s.prototype,ee=O(f,`cloneNode`),te=O(f,`remove`),ne=O(f,`removeAttributeNode`),pe=O(f,`nextSibling`),v=O(f,`childNodes`),y=O(f,`parentNode`),me=O(f,`shadowRoot`),x=O(f,`attributes`),w=o&&o.prototype?O(o.prototype,`nodeType`):null,T=o&&o.prototype?O(o.prototype,`nodeName`):null,he=o&&o.prototype?O(o.prototype,`ownerDocument`):null,A=function(e){return w?w(e):e.nodeType},Xe=function(e){return T?T(e):e.nodeName};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let M,N=``,Ze,Qe=!1,$e=0,et=function(){if($e>0)throw C(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},P=function(e){et(),$e++;try{return M.createHTML(e)}finally{$e--}},tt=function(e){et(),$e++;try{return M.createScriptURL(e)}finally{$e--}},nt=function(){return Qe||=(Ze=Ke(d,i),!0),Ze},rt=n,it=rt.implementation,at=rt.createNodeIterator,ot=rt.createDocumentFragment,st=rt.getElementsByTagName,ct=r.importNode,F=qe();t.isSupported=typeof c==`function`&&typeof y==`function`&&it&&it.createHTMLDocument!==void 0;let lt=ke,ut=Ae,dt=je,ft=Me,pt=Ne,mt=Fe,ht=Ie,gt=Re,_t=Pe,I=null,vt=E({},[...ve,...ye,...be,...Se,...we]),L=null,yt=E({},[...Te,...Ee,...De,...Oe]),R=Object.seal(h(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),bt=null,xt=null,z=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),St=!0,Ct=!0,wt=!1,Tt=!0,B=!1,V=!0,H=!1,Et=!1,Dt=null,Ot=null,kt=!1,U=!1,At=!1,jt=!1,Mt=!0,Nt=!1,Pt=`user-content-`,Ft=!0,It=!1,W={},G=null,Lt=E({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),Rt=null,zt=E({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Bt=null,Vt=E({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ht=`http://www.w3.org/1998/Math/MathML`,Ut=`http://www.w3.org/2000/svg`,K=`http://www.w3.org/1999/xhtml`,q=K,Wt=!1,Gt=null,Kt=E({},[Ht,Ut,K],ce),qt=p([`mi`,`mo`,`mn`,`ms`,`mtext`]),Jt=E({},qt),Yt=p([`annotation-xml`]),Xt=E({},Yt),Zt=E({},[`title`,`style`,`font`,`a`,`script`]),Qt=null,$t=[`application/xhtml+xml`,`text/html`],J=null,Y=null,en=n.createElement(`form`),tn=function(e){return e instanceof RegExp||e instanceof Function},nn=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Y&&Y===e)return;(!e||typeof e!=`object`)&&(e={}),e=D(e),Qt=$t.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,J=Qt===`application/xhtml+xml`?ce:se,I=j(e,`ALLOWED_TAGS`,vt,{transform:J}),L=j(e,`ALLOWED_ATTR`,yt,{transform:J}),Gt=j(e,`ALLOWED_NAMESPACES`,Kt,{transform:ce}),Bt=j(e,`ADD_URI_SAFE_ATTR`,Vt,{transform:J,base:Vt}),Rt=j(e,`ADD_DATA_URI_TAGS`,zt,{transform:J,base:zt}),G=j(e,`FORBID_CONTENTS`,Lt,{transform:J}),bt=j(e,`FORBID_TAGS`,D({}),{transform:J}),xt=j(e,`FORBID_ATTR`,D({}),{transform:J}),W=b(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?D(e.USE_PROFILES):e.USE_PROFILES:!1,St=e.ALLOW_ARIA_ATTR!==!1,Ct=e.ALLOW_DATA_ATTR!==!1,wt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Tt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,B=e.SAFE_FOR_TEMPLATES||!1,V=e.SAFE_FOR_XML!==!1,H=e.WHOLE_DOCUMENT||!1,U=e.RETURN_DOM||!1,At=e.RETURN_DOM_FRAGMENT||!1,jt=e.RETURN_TRUSTED_TYPE||!1,kt=e.FORCE_BODY||!1,Mt=e.SANITIZE_DOM!==!1,Nt=e.SANITIZE_NAMED_PROPS||!1,Ft=e.KEEP_CONTENT!==!1,It=e.IN_PLACE||!1,_t=_e(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Pe,q=typeof e.NAMESPACE==`string`?e.NAMESPACE:K,Jt=Je(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>E({},qt)),Xt=Je(e,`HTML_INTEGRATION_POINTS`,()=>E({},Yt));let t=Je(e,`CUSTOM_ELEMENT_HANDLING`,()=>h(null));if(R=h(null),b(t,`tagNameCheck`)&&tn(t.tagNameCheck)&&(R.tagNameCheck=t.tagNameCheck),b(t,`attributeNameCheck`)&&tn(t.attributeNameCheck)&&(R.attributeNameCheck=t.attributeNameCheck),b(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(R.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),m(R),B&&(Ct=!1),At&&(U=!0),W&&(I=E({},we),L=h(null),W.html===!0&&(E(I,ve),E(L,Te)),W.svg===!0&&(E(I,ye),E(L,Ee),E(L,Oe)),W.svgFilters===!0&&(E(I,be),E(L,Ee),E(L,Oe)),W.mathMl===!0&&(E(I,Se),E(L,De),E(L,Oe))),z.tagCheck=null,z.attributeCheck=null,b(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?z.tagCheck=e.ADD_TAGS:_(e.ADD_TAGS)&&(I===vt&&(I=D(I)),E(I,e.ADD_TAGS,J))),b(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?z.attributeCheck=e.ADD_ATTR:_(e.ADD_ATTR)&&(L===yt&&(L=D(L)),E(L,e.ADD_ATTR,J))),b(e,`ADD_FORBID_CONTENTS`)&&_(e.ADD_FORBID_CONTENTS)&&(G===Lt&&(G=D(G)),E(G,e.ADD_FORBID_CONTENTS,J)),Ft&&(I[`#text`]=!0),H&&E(I,[`html`,`head`,`body`]),I.table&&(E(I,[`tbody`]),delete bt.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw C(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw C(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=M;M=e.TRUSTED_TYPES_POLICY;try{N=P(``)}catch(e){throw M=t,e}}else e.TRUSTED_TYPES_POLICY===null?(M=void 0,N=``):(M===void 0&&(M=nt()),M&&typeof N==`string`&&(N=P(``)));p&&p(e),Y=e},rn=E({},[...ye,...be,...xe]),an=E({},[...Se,...Ce]),on=function(e,t,n){return t.namespaceURI===K?e===`svg`:t.namespaceURI===Ht?e===`svg`&&(n===`annotation-xml`||Jt[n]):!!rn[e]},sn=function(e,t,n){return t.namespaceURI===K?e===`math`:t.namespaceURI===Ut?e===`math`&&Xt[n]:!!an[e]},cn=function(e,t,n){return t.namespaceURI===Ut&&!Xt[n]||t.namespaceURI===Ht&&!Jt[n]?!1:!an[e]&&(Zt[e]||!rn[e])},ln=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:q,tagName:`template`});let n=se(e.tagName),r=se(t.tagName);return Gt[e.namespaceURI]?e.namespaceURI===Ut?on(n,t,r):e.namespaceURI===Ht?sn(n,t,r):e.namespaceURI===K?cn(n,t,r):!!(Qt===`application/xhtml+xml`&&Gt[e.namespaceURI]):!1},X=function(e){ae(t.removed,{element:e});try{y(e).removeChild(e)}catch{if(te(e),!y(e))throw C(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},un=function(e,t,n){try{ne(e,t)}catch{try{e.removeAttribute(n)}catch{}}},dn=function(e){pn(e);let t=v(e);if(t){let e=[];g(t,t=>{ae(e,t)}),g(e,e=>{try{te(e)}catch{}})}let n=x(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&un(e,r,i)}},Z=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}ae(t.removed,{attribute:r||null,from:n});try{r?ne(n,r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(U||At)try{X(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},fn=function(e){let t=x(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||L[J(i)]||un(e,r,i)}},pn=function(e){let t=[e];for(;t.length>0;){let e=t.pop();A(e)===k.element&&fn(e);let n=v(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},mn=function(e,t){return V?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},hn=function(e){if(!V)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=A(e);if(n===k.processingInstruction||n===k.comment&&S(Be,e.data)){try{te(e)}catch{}continue}if(n===k.element){let t=e,n=J(Xe(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&mn(`for`,n)&&t.removeAttribute(`for`)}catch{}}let r=v(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},gn=function(e){let t=null,r=null;if(kt)e=`<remove></remove>`+e;else{let t=le(e,/^[\r\n\t ]+/);r=t&&t[0]}Qt===`application/xhtml+xml`&&q===K&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=M?P(e):e;if(q===K)try{t=new u().parseFromString(i,Qt)}catch{}if(!t||!t.documentElement){t=it.createDocument(q,`template`,null);try{t.documentElement.innerHTML=Wt?N:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),q===K?st.call(t,H?`html`:`body`)[0]:H?t.documentElement:a},_n=function(e){let t=he?he(e):e.ownerDocument;return at.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},vn=function(e){return e=ue(e,lt,` `),e=ue(e,ut,` `),e=ue(e,dt,` `),e},yn=function(e){e.normalize();let t=he?he(e):e.ownerDocument,n=at.call(t||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=vn(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&g(i,e=>{xn(e.content)&&yn(e.content)})},bn=function(e){let t=T?T(e):null;return typeof t!=`string`||J(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==x(e)||typeof e.removeAttribute!=`function`||typeof e.removeAttributeNode!=`function`||typeof e.getAttributeNode!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==w(e)||e.childNodes!==v(e)},xn=function(e){if(!w||typeof e!=`object`||!e)return!1;try{return w(e)===k.documentFragment}catch{return!1}},Sn=function(e){if(!w||typeof e!=`object`||!e)return!1;try{return typeof w(e)==`number`}catch{return!1}};function Q(e,n,r){e.length!==0&&g(e,e=>{e.call(t,n,r,Y)})}let Cn=function(e,t){return!!(V&&e.hasChildNodes()&&!Sn(e.firstElementChild)&&S(ze,e.textContent)&&S(ze,e.innerHTML)||V&&e.namespaceURI===K&&Ue[t]&&(Sn(e.firstElementChild)||typeof e.textContent==`string`&&S(We[t],e.textContent))||e.nodeType===k.processingInstruction||V&&e.nodeType===k.comment&&S(Be,e.data))},wn=function(e,t){return e instanceof RegExp?S(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},Tn=function(e,t,n){if(!bt[t]&&An(t)&&wn(R.tagNameCheck,t))return!1;if(Ft&&!G[t]){let t=y(e),r=v(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,pe(e))}}}return X(e),!0},En=function(e,t,n,r){return e.length===0?t:t===n||t===r?D(t):t},$=function(e,t){return e===t||y(e)!==null?!1:(It&&pn(e),!0)},Dn=function(e,n){if(Q(F.beforeSanitizeElements,e,null),$(e,n))return!0;if(bn(e))return X(e),!0;let r=J(Xe(e));if(I=En(F.uponSanitizeElement,I,vt,Dt),Q(F.uponSanitizeElement,e,{tagName:r,allowedTags:I}),$(e,n))return!0;if(Cn(e,r))return X(e),!0;if(bt[r]||!(z.tagCheck instanceof Function&&z.tagCheck(r))&&!I[r]){let t=Tn(e,r,n);return t===!1&&(Q(F.afterSanitizeElements,e,null),$(e,n))?!0:t}if(A(e)===k.element&&!ln(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&S(Ve,e.innerHTML))return X(e),!0;if(B&&e.nodeType===k.text){let n=vn(e.textContent);e.textContent!==n&&(ae(t.removed,{element:e.cloneNode()}),e.textContent=n)}return Q(F.afterSanitizeElements,e,null),$(e,n)},On=function(e,t,r){if(xt[t]||mn(t,e)||Mt&&(t===`id`||t===`name`)&&(r in n||r in en))return!1;let i=L[t]||z.attributeCheck instanceof Function&&z.attributeCheck(t,e);return Ct&&S(ft,t)||St&&S(pt,t)?!0:i?Bt[t]||S(_t,ue(r,ht,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&de(r,`data:`)===0&&Rt[e]||wt&&!S(mt,ue(r,ht,``))?!0:!r:An(e)&&wn(R.tagNameCheck,e)&&wn(R.attributeNameCheck,t,e)||t===`is`&&R.allowCustomizedBuiltInElements&&wn(R.tagNameCheck,r)},kn=E({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),An=function(e){return!kn[se(e)]&&S(gt,e)},jn=function(e,t,n,r){if(M&&typeof d==`object`&&typeof d.getAttributeType==`function`&&!n)switch(d.getAttributeType(e,t)){case`TrustedHTML`:return P(r);case`TrustedScriptURL`:return tt(r)}return r},Mn=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!bn(e)||(X(e),!1)}catch{return Z(t,e),!1}},Nn=function(e,n){if(Q(F.beforeSanitizeAttributes,e,null),$(e,n))return;let r=e.attributes;if(!r||bn(e))return;L=En(F.uponSanitizeAttribute,L,yt,Ot);let i={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0},a=r.length,o=J(e.nodeName);for(;a--;){let n=r[a],s=n.name,c=n.namespaceURI,l=n.value,u=J(s),d=l,f=s===`value`?d:fe(d),p=!1;if(i.attrName=u,i.attrValue=f,i.keepAttr=!0,i.forceKeepAttr=void 0,Q(F.uponSanitizeAttribute,e,i),f=i.attrValue,Nt&&(u===`id`||u===`name`)&&de(f,Pt)!==0&&(Z(s,e,n),f=Pt+f,p=!0),V&&S(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,f)){Z(s,e,n);continue}if(u===`attributename`&&le(f,`href`)){Z(s,e,n);continue}if(!i.forceKeepAttr){if(!i.keepAttr){Z(s,e,n);continue}if(!Tt&&S(He,f)){Z(s,e,n);continue}if(B&&(f=vn(f)),!On(o,u,f)){Z(s,e,n);continue}f=jn(o,u,c,f),f!==d&&Mn(e,s,c,f)&&p&&ie(t.removed)}}Q(F.afterSanitizeAttributes,e,null),$(e,n)},Pn=function(e){let t=null,n=_n(e);for(Q(F.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(Q(F.uponSanitizeShadowNode,t,null),Dn(t,e),Nn(t,e),xn(t.content)&&Pn(t.content),A(t)===k.element){let e=me(t);xn(e)&&(Fn(e),Pn(e))}Q(F.afterSanitizeShadowDOM,e,null)},Fn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Pn(e.shadow);continue}let n=e.node,r=A(n)===k.element,i=v(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=T?T(n):null;if(typeof e==`string`&&J(e)===`template`){let e=n.content;xn(e)&&t.push({node:e,shadow:null})}}if(r){let e=me(n);xn(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Wt=!e,Wt&&(e=`<!-->`),typeof e!=`string`&&!Sn(e)&&(e=ge(e),typeof e!=`string`))throw C(`dirty is not a string, aborting`);if(!t.isSupported)return e;Et?(I=Dt,L=Ot):nn(n),(F.uponSanitizeElement.length>0||F.uponSanitizeAttribute.length>0)&&(I=D(I)),F.uponSanitizeAttribute.length>0&&(L=D(L)),t.removed=[];let c=It&&typeof e!=`string`&&Sn(e);if(c){hn(e);let t=Xe(e);if(typeof t==`string`){let n=J(t);if(!I[n]||bt[n])throw dn(e),C(`root node is forbidden and cannot be sanitized in-place`)}if(bn(e))throw dn(e),C(`root node is clobbered and cannot be sanitized in-place`);try{Fn(e)}catch(t){throw dn(e),t}}else if(Sn(e))i=gn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===k.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Fn(i);else{if(!U&&!B&&!H&&e.indexOf(`<`)===-1)return M&&jt?P(e):e;if(i=gn(e),!i)return U?null:jt?N:``}i&&kt&&X(i.firstChild);let l=c?e:i;try{let e=_n(l);for(;o=e.nextNode();)Dn(o,l),Nn(o,l),xn(o.content)&&Pn(o.content)}catch(n){throw c&&(dn(e),g(t.removed,e=>{e.element&&pn(e.element)})),n}if(c){let n=!1;if(g(t.removed,t=>{t.element&&(t.element===e&&(n=!0),pn(t.element))}),n)throw C(`a node selected for removal could not be safely returned; refusing to sanitize in place`);return B&&yn(e),e}if(U){if(B&&yn(i),At)for(s=ot.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(L.shadowroot||L.shadowrootmode)&&(s=ct.call(r,s,!0)),s}let u=H?i.outerHTML:i.innerHTML;return H&&I[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&S(Le,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
3
+ `+u),B&&(u=vn(u)),M&&jt?P(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};nn(e),Et=!0,Dt=I,Ot=L},t.clearConfig=function(){Y=null,Et=!1,Dt=null,Ot=null,M=Ze,N=``},t.isValidAttribute=function(e,t,n){Y||nn({});let r=J(e),i=J(t);return On(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&b(F,e)&&ae(F[e],t)},t.removeHook=function(e,t){if(b(F,e)){if(t!==void 0){let n=re(F[e],t);return n===-1?void 0:oe(F[e],n,1)[0]}return ie(F[e])}},t.removeHooks=function(e){b(F,e)&&(F[e]=[])},t.removeAllHooks=function(){F=qe()},t}var Xe=Ye();export{Xe as default};
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-CpBN0dhf.js"></script>
6
+ <script type="module" crossorigin src="./assets/index-BIKy_ifH.js"></script>
7
7
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-hePW80VL.js">
8
8
  </head>
9
9
  <body>
package/lib/errors.d.ts CHANGED
@@ -5,10 +5,9 @@
5
5
  * release — never match on them. `PolotnoErrorDetailsMap` in
6
6
  * `@polotno/core/src/errors.ts` is the canonical list this mirrors.
7
7
  *
8
- * polotno-node renders through the polotno browser client inside Chromium, so
9
- * besides its own codes this union lists every code that can cross the
10
- * `page.evaluate` boundary from the core editor / schema / video-export —
11
- * that is the error surface a polotno-node consumer can actually catch.
8
+ * This package declares errors from its rendering API, including asset errors
9
+ * that cross the Chromium boundary. Editor-only tool errors are not part of
10
+ * this contract.
12
11
  */
13
12
  export type PolotnoErrorCode = 'DESIGN_INVALID' | 'EXPORT_FAILED' | 'IMAGE_FAILED' | 'FONT_FAILED' | 'VIDEO_FAILED' | 'FETCH_FAILED' | 'UNKNOWN';
14
13
  /**
@@ -16,8 +15,8 @@ export type PolotnoErrorCode = 'DESIGN_INVALID' | 'EXPORT_FAILED' | 'IMAGE_FAILE
16
15
  * `PolotnoErrorDetailsMap`, kept self-contained for the same
17
16
  * page.evaluate-boundary reason the code union above is (types are erased, but
18
17
  * keeping the whole error surface in one file documents exactly what a
19
- * polotno-node consumer can catch). Keep in sync with `PolotnoErrorDetailsMap`
20
- * in `@polotno/core/src/errors.ts`.
18
+ * polotno-node consumer can catch). Only this package's codes belong here.
19
+ * Their details match `PolotnoErrorDetailsMap` in `@polotno/core/src/errors.ts`.
21
20
  */
22
21
  interface RenderContext {
23
22
  label?: string;
package/lib/errors.js CHANGED
@@ -5,10 +5,9 @@
5
5
  * release — never match on them. `PolotnoErrorDetailsMap` in
6
6
  * `@polotno/core/src/errors.ts` is the canonical list this mirrors.
7
7
  *
8
- * polotno-node renders through the polotno browser client inside Chromium, so
9
- * besides its own codes this union lists every code that can cross the
10
- * `page.evaluate` boundary from the core editor / schema / video-export —
11
- * that is the error surface a polotno-node consumer can actually catch.
8
+ * This package declares errors from its rendering API, including asset errors
9
+ * that cross the Chromium boundary. Editor-only tool errors are not part of
10
+ * this contract.
12
11
  */
13
12
  export function polotnoError(code, message, details, cause) {
14
13
  const err = new Error(message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno-node",
3
- "version": "3.11.0",
3
+ "version": "3.12.1",
4
4
  "description": "Polotno workflow from NodeJS",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
@@ -35,22 +35,23 @@
35
35
  "@polotno/video-export"
36
36
  ],
37
37
  "devDependencies": {
38
+ "@polotno/core": "0.15.0",
38
39
  "@polotno/design-fixtures": "0.0.0",
39
40
  "@polotno/video-export": "0.4.0",
40
- "@types/node": "^26.6.1",
41
- "dotenv": "^17.4.2",
41
+ "@types/node": "^26.6.4",
42
+ "dotenv": "^18.0.5",
42
43
  "jspdf": "^4.2.1",
43
44
  "konva": "^10.7.0",
44
- "mediabunny": "^1.56.3",
45
+ "mediabunny": "^1.61.1",
45
46
  "pixelmatch": "^7.2.0",
46
47
  "pngjs": "^7.0.0",
47
- "polotno": "4.14.0",
48
+ "polotno": "4.15.2",
48
49
  "react": "^19.3.0",
49
50
  "react-dom": "^19.3.0",
50
51
  "tmp": "^0.2.7",
51
52
  "typescript": "~6.0.3",
52
- "vite": "^8.3.0",
53
- "vitest": "^5.0.1",
53
+ "vite": "^8.3.2",
54
+ "vitest": "^5.0.3",
54
55
  "web-audio-api": "^1.5.6"
55
56
  },
56
57
  "overrides": {
@@ -61,10 +62,10 @@
61
62
  },
62
63
  "author": "Anton Lavrenov",
63
64
  "dependencies": {
64
- "@polotno/schema": "0.7.0",
65
+ "@polotno/schema": "0.8.0",
65
66
  "@sparticuz/chromium": "^153.0.0",
66
- "puppeteer": "25.11.0",
67
- "puppeteer-core": "25.11.0"
67
+ "puppeteer": "25.12.0",
68
+ "puppeteer-core": "25.12.0"
68
69
  },
69
70
  "bugs": {
70
71
  "url": "https://github.com/polotno-project/polotno-node/issues"