polotno-node 3.9.0 → 3.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{html2canvas-Cm_vP64m.js → html2canvas-Dn6bw578.js} +1 -1
- package/dist/assets/index-CpBN0dhf.js +660 -0
- package/dist/assets/{index.es-BGauYEGb.js → index.es-2ncnHwRp.js} +1 -1
- package/dist/assets/{jspdf.es.min-7Xedaaef.js → jspdf.es.min-B1nUIUxR.js} +4 -4
- package/dist/assets/lib-qW6sgCha.js +1 -0
- package/dist/assets/purify.es-7fJ1DZ6H.js +3 -0
- package/dist/index.html +2 -7
- package/lib/instance.d.ts +1 -10
- package/lib/instance.js +7 -45
- package/package.json +17 -19
- package/dist/assets/index-DMNDOkTi.js +0 -648
- package/dist/assets/lib-B5Aq9qTO.js +0 -1
- package/dist/assets/purify.es-ChwZkWde.js +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./rolldown-runtime-hePW80VL.js";import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,Ft as d,G as f,H as p,I as m,It as h,J as g,K as _,L as v,Lt as y,M as b,Mt as x,N as S,Nt as C,O as ee,Ot as te,P as ne,Pt as re,Q as ie,R as ae,Rt as oe,S as se,St as ce,T as w,Tt as le,U as ue,V as de,W as fe,X as pe,Y as me,Z as he,_ as ge,_t as _e,a as ve,at as ye,b as T,bt as E,c as be,ct as xe,d as Se,dt as Ce,et as we,f as Te,ft as D,g as Ee,gt as De,h as Oe,ht as ke,i as Ae,it as je,j as Me,jt as O,k as Ne,kt as Pe,l as k,lt as A,m as Fe,mt as Ie,n as Le,nt as Re,o as ze,ot as Be,p as Ve,pt as He,q as Ue,r as We,rt as Ge,s as Ke,st as qe,tt as Je,u as Ye,ut as Xe,v as Ze,vt as Qe,w as $e,wt as et,x as j,xt as M,y as tt,yt as nt,z as rt}from"./index-CpBN0dhf.js";var it=new Map,at=new Map,ot=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!w.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${w.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 N))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof N)&&(!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.crop!==void 0&&Ve(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.`);st(e.codec,e)},st=(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&&Me(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.`)},ct=e=>{let n=e.bitrateMode,r=e.quality._toVideoRateControl(e.codec,e.width,e.height,n),i=(n,r,i)=>({codec:e.fullCodecString??o(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}),A(a.length>0),a},lt=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!j.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${j.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(i.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 N))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof N)&&(!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.`);ut(e.codec,e)},ut=(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&&Me(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},dt=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??c(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...Ne(e.codec)}},N=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 ft):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`?ft[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=pt[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&&(A(this._quality!==void 0),a=D(Math.round(et(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&&(A(a!==null&&i),r=D((a-i.worst)/(i.best-i.worst),0,1)),s=ht(e,t,n,mt(r))}return{quantizer:a,bitrate:s,bitrateMode:o}}_toVideoBitrate(e,t,n){return this._bitrate===void 0?(A(this._quality!==void 0),ht(e,t,n,mt(this._quality))):this._bitrate}_toAudioBitrate(e){if(i.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=mt(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}},ft={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},pt={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}},mt=e=>.3*Math.exp(2.5538*e),ht=(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},gt=(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}};A(!1)},_t=new N(`high`),vt=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,...o}=t;if(!w.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 N))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 N)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);st(e,o);let s=bt(i,a)??new N(`medium`),c;try{c=ct({codec:e,width:n,height:r,quality:s,framerate:void 0,...o,alpha:`discard`})}catch{return!1}let l=JSON.stringify(c),u=it.get(l);if(u)return u;let d=(async()=>{for(let{config:t}of c)if(be.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 c){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!De()||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:gt(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return it.set(l,d),d},yt=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:a,bitrate:o,...s}=t;if(!j.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(a!==void 0&&!(a instanceof N))throw TypeError(`quality, when provided, must be a Quality.`);if(a!==void 0&&o!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(o!==void 0&&!(o instanceof N)&&(!Number.isInteger(o)||o<=0))throw TypeError(`bitrate must be a positive integer.`);ut(e,s);let c=dt({codec:e,numberOfChannels:n,sampleRate:r,quality:bt(a,o)??new N(`medium`),...s}),l=JSON.stringify(c),u=at.get(l);if(u)return u;let d=(async()=>{if(Ke.some(t=>t.supports(e,c))||i.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return at.set(l,d),d},bt=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof N?t:new N({bitrate:t})},xt=async(e,t)=>{for(let n of e)if(await yt(n,t))return n;return null},St=class{constructor(e){this.mutex=new Ge,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)}}},Ct=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,wt=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`)},Tt=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);A(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}}},P=new Uint8Array(8),F=new DataView(P.buffer),I=e=>[(e%256+256)%256],L=e=>(F.setUint16(0,e,!1),[P[0],P[1]]),Et=e=>(F.setInt16(0,e,!1),[P[0],P[1]]),Dt=e=>(F.setUint32(0,e,!1),[P[1],P[2],P[3]]),R=e=>(F.setUint32(0,e,!1),[P[0],P[1],P[2],P[3]]),z=e=>(F.setInt32(0,e,!1),[P[0],P[1],P[2],P[3]]),B=e=>(F.setUint32(0,Math.floor(e/2**32),!1),F.setUint32(4,e,!1),[P[0],P[1],P[2],P[3],P[4],P[5],P[6],P[7]]),Ot=e=>(F.setInt32(0,Math.floor(e/2**32),!1),F.setUint32(4,e,!1),[P[0],P[1],P[2],P[3],P[4],P[5],P[6],P[7]]),kt=e=>(F.setInt16(0,256*e,!1),[P[0],P[1]]),V=e=>(F.setInt32(0,2**16*e,!1),[P[0],P[1],P[2],P[3]]),At=e=>(F.setInt32(0,2**30*e,!1),[P[0],P[1],P[2],P[3]]),jt=(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()},H=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},Mt=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},Nt=Mt(0),Pt=e=>[V(e[0]),V(e[1]),At(e[2]),V(e[3]),V(e[4]),At(e[5]),V(e[6]),V(e[7]),At(e[8])],U=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),W=(e,t,n,r,i)=>U(e,[I(t),Dt(n),r??[]],i),Ft=e=>e.isQuickTime?U(`ftyp`,[H(`qt `),R(512),H(`qt `)]):e.fragmented?e.cmaf?U(`ftyp`,[H(`iso5`),R(512),H(`iso5`),H(`iso6`),H(`mp41`),H(`cmfc`),H(`dash`)]):U(`ftyp`,[H(`iso5`),R(512),H(`iso5`),H(`iso6`),H(`mp41`)]):U(`ftyp`,[H(`isom`),R(512),H(`isom`),e.holdsAvc?H(`avc1`):[],H(`mp41`)]),It=()=>U(`styp`,[H(`iso5`),R(0),H(`iso5`),H(`iso6`),H(`mp41`),H(`cmfc`),H(`dash`)]),Lt=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),W(`sidx`,1,0,[R(1),R(Z),B(Q(n,Z)),B(0),L(0),L(1),R(t&2147483647),R(Q(r,Z)),R(0)])},Rt=e=>({type:`mdat`,largeSize:e}),zt=e=>({type:`free`,size:e}),G=e=>U(`moov`,void 0,[Bt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Ht(t,e.creationTime)),e.isFragmented?kn(e.trackDatas):null,Wn(e)]),Bt=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,Q(Vt(e),Z)+Q(e.startTimestampOffset??0,Z)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!M(e)||!M(n),a=i?B:R;return W(`mvhd`,+i,0,[a(e),a(e),R(Z),a(n),V(1),kt(1),Array(10).fill(0),Pt(Nt),Array(24).fill(0),R(r)])},Vt=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},Ht=(e,t)=>{let n=ur(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return U(`trak`,void 0,[Ut(e,t),r?Wt(e):null,Gt(e,t),n.name===void 0?null:U(`udta`,void 0,[U(`name`,[...O.encode(n.name)])])])},Ut=(e,t)=>{let n=Math.max(0,Q(Vt(e),Z)+Q(e.startTimestampOffset??0,Z)),r=!M(t)||!M(n),i=r?B:R,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=Mt(t??0)}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:Xe(e);return W(`tkhd`,+r,o,[i(t),i(t),R(e.track.id),R(0),i(n),Array(8).fill(0),L(0),L(s),kt(+(e.type===`audio`)),L(0),Pt(a),V(e.type===`video`?e.info.width:0),V(e.type===`video`?e.info.height:0)])},Wt=e=>{let t=e.startTimestampOffset;if(A(t!==null),t>0){let n=Q(t,Z),r=Q(Vt(e),Z),i=!M(n)||!M(r),a=i?B:R,o=i?Ot:z;return U(`edts`,void 0,[W(`elst`,+!!i,0,[R(2),a(n),o(-1),V(1),a(r),o(0),V(1)])])}{let n=Q(-t,e.timescale),r=Math.max(0,Q(Vt(e),Z)+Q(t,Z)),i=!_e(n)||!M(r),a=i?B:R,o=i?Ot:z;return U(`edts`,void 0,[W(`elst`,+!!i,0,[R(1),a(r),o(n),V(1)])])}},Gt=(e,t)=>U(`mdia`,void 0,[Kt(e,t),Yt(!0,qt[e.type],Jt[e.type]),Xt(e)]),Kt=(e,t)=>{let n=Q(Vt(e),e.timescale),r=!M(t)||!M(n),i=r?B:R;return W(`mdhd`,+r,0,[i(t),i(t),R(e.timescale),i(n),L(nr(e.track.metadata.languageCode??`und`)),L(0)])},qt={video:`vide`,audio:`soun`,subtitle:`text`},Jt={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Yt=(e,t,n,r=`\0\0\0\0`)=>W(`hdlr`,0,0,[e?H(`mhlr`):R(0),H(t),H(r),R(0),R(0),H(n,!0)]),Xt=e=>U(`minf`,void 0,[Zt[e.type](),Qt(),tn(e)]),Zt={video:()=>W(`vmhd`,0,1,[L(0),L(0),L(0),L(0)]),audio:()=>W(`smhd`,0,0,[L(0),L(0)]),subtitle:()=>W(`nmhd`,0,0)},Qt=()=>U(`dinf`,void 0,[$t()]),$t=()=>W(`dref`,0,0,[R(1)],[en()]),en=()=>W(`url `,0,1),tn=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return U(`stbl`,void 0,[nn(e),Sn(e),t?Dn(e):null,t?On(e):null,wn(e),Tn(e),En(e),Cn(e)])},nn=e=>{let t;if(e.type===`video`)t=rn(Xn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Qn(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);A(n),t=dn(n,e)}else e.type===`subtitle`&&(t=bn(er[e.track.source._codec],e));return A(t),W(`stsd`,0,0,[R(1)],[t])},rn=(e,t)=>U(e,[[,,,,,,].fill(0),L(1),L(0),L(0),Array(12).fill(0),L(t.info.width),L(t.info.height),R(4718592),R(4718592),R(0),L(1),I(10),H(`Mediabunny`),Array(21).fill(0),L(t.info.hasAlphaChannel?32:24),Et(65535)],[Zn[t.track.source._codec]?.(t)??null,an(t),He(t.info.decoderConfig.colorSpace)?null:on(t)]),an=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:U(`pasp`,[R(e.info.pixelAspectRatio.num),R(e.info.pixelAspectRatio.den)]),on=e=>{let t=e.info.decoderConfig.colorSpace;return U(`colr`,[H(e.muxer.isQuickTime?`nclc`:`nclx`),L(t?.primaries==null?2:je[t.primaries]),L(t?.transfer==null?2:xe[t.transfer]),L(t?.matrix==null?2:qe[t.matrix]),e.muxer.isQuickTime?[]:I(!!t?.fullRange<<7)])},sn=e=>e.info.decoderConfig&&U(`avcC`,[...C(e.info.decoderConfig.description)]),cn=e=>e.info.decoderConfig&&U(`hvcC`,[...C(e.info.decoderConfig.description)]),ln=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?je[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?xe[t.colorSpace.transfer]:1,d=n[7]?Number(n[7]):t.colorSpace?.matrix?qe[t.colorSpace.matrix]:1;return W(`vpcC`,1,0,[I(r),I(i),I(c),I(l),I(u),I(d),L(0)])},un=e=>U(`av1C`,ee(e.info.decoderConfig.codec)),dn=(e,t)=>{let n=0,r,a=16,o=i.includes(t.track.source._codec);if(o){let e=t.track.source._codec,{sampleSize:r}=b(e);a=8*r,a>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),L(1),L(n),L(0),R(0),L(t.info.numberOfChannels),L(a),L(0),L(0),L(t.info.sampleRate<2**16?t.info.sampleRate:0),L(0)];else{let e=o?0:-2;r=[[,,,,,,].fill(0),L(1),L(n),L(0),R(0),L(t.info.numberOfChannels),L(Math.min(a,16)),Et(e),L(0),L(t.info.sampleRate<2**16?t.info.sampleRate:0),L(0),o?[R(1),R(a/8),R(t.info.numberOfChannels*a/8)]:[R(0),R(0),R(0)],R(2)]}return U(e,r,[$n(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},fn=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=[...I(t),...I(21),...Dt(0),...R(0),...R(0)];if(e.info.decoderConfig.description){let t=C(e.info.decoderConfig.description);n=[...n,...I(5),...jt(t.byteLength),...t]}return n=[...L(1),...I(0),...I(4),...jt(n.length),...n,...I(6),...I(1),...I(2)],n=[...I(3),...jt(n.length),...n],W(`esds`,0,0,n)},K=e=>U(`wave`,void 0,[pn(e),mn(e),U(`\0\0\0\0`)]),pn=e=>U(`frma`,[H(Qn(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),mn=e=>{let{littleEndian:t}=b(e.track.source._codec);return U(`enda`,[L(+t)])},hn=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){A(s.byteLength>=18);let e=C(s),c=f(e);t=c.outputChannelCount,n=c.preSkip,r=c.inputSampleRate,i=c.outputGain,a=c.channelMappingFamily,c.channelMappingTable&&(o=c.channelMappingTable)}return U(`dOps`,[I(0),I(t),L(n),R(r),Et(i),I(a),...o])},gn=e=>{let t=e.info.decoderConfig?.description;return A(t),W(`dfLa`,0,0,[...C(t).subarray(4)])},q=e=>{let{littleEndian:t,sampleSize:n}=b(e.track.source._codec);return W(`pcmC`,0,0,[I(+t),I(8*n)])},_n=e=>{A(e.info.primingPacket);let t=p(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 ie(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),U(`dac3`,[...n])},vn=e=>{A(e.info.primingPacket);let t=fe(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 ie(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 U(`dec3`,[...i])},yn=e=>{A(e.info.primingPacket);let t=ue(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 U(`ddts`,[...m(t)])},bn=(e,t)=>U(e,[[,,,,,,].fill(0),L(1)],[tr[t.track.source._codec](t)]),xn=e=>U(`vttC`,[...O.encode(e.info.config.description)]),Sn=e=>W(`stts`,0,0,[R(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[R(e.sampleCount),R(e.sampleDelta)])]),Cn=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return W(`stss`,0,0,[R(t.length),t.map(([e])=>R(e+1))])},wn=e=>W(`stsc`,0,0,[R(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[R(e.firstChunk),R(e.samplesPerChunk),R(1)])]),Tn=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=b(e.track.source._codec);return W(`stsz`,0,0,[R(t*e.info.numberOfChannels),R(e.samples.reduce((t,n)=>t+Q(n.duration,e.timescale),0))])}return W(`stsz`,0,0,[R(0),R(e.samples.length),e.samples.map(e=>R(e.size))])},En=e=>e.finalizedChunks.length>0&&a(e.finalizedChunks).offset>=2**32?W(`co64`,0,0,[R(e.finalizedChunks.length),e.finalizedChunks.map(e=>B(e.offset))]):W(`stco`,0,0,[R(e.finalizedChunks.length),e.finalizedChunks.map(e=>R(e.offset))]),Dn=e=>W(`ctts`,1,0,[R(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[R(e.sampleCount),z(e.sampleCompositionTimeOffset)])]),On=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;A(e.compositionTimeOffsetTable.length>0),A(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,Q(n.timestamp,e.timescale)),i=Math.max(i,Q(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:W(`cslg`,0,0,[z(a),z(t),z(n),z(r),z(i)])},kn=e=>U(`mvex`,void 0,e.map(An)),An=e=>W(`trex`,0,0,[R(e.track.id),R(1),R(0),R(0),R(0)]),jn=(e,t)=>U(`moof`,void 0,[Mn(e),...t.map(Pn)]),Mn=e=>W(`mfhd`,0,0,[R(e)]),Nn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Pn=e=>U(`traf`,void 0,[Fn(e),In(e),Ln(e)]),Fn=e=>{A(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:Nn(n)};return W(`tfhd`,0,t,[R(e.track.id),R(r.duration),R(r.size),R(r.flags)])},In=e=>(A(e.currentChunk),W(`tfdt`,1,0,[B(Q(e.currentChunk.startTimestamp,e.timescale))])),Ln=e=>{A(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Nn),i=e.currentChunk.samples.map(t=>Q(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,W(`trun`,1,m,[R(e.currentChunk.samples.length),R(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?R(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?R(t[a]):[],d?R(n[a]):[],f?R(r[a]):[],p?z(i[a]):[]])])},Rn=e=>U(`mfra`,void 0,[...e.map(zn),Bn()]),zn=e=>W(`tfra`,1,0,[R(e.track.id),R(63),R(e.finalizedChunks.length),e.finalizedChunks.map(t=>[B(Q(t.samples[0].timestamp,e.timescale)),B(t.moofOffset),R(t.trafIndex+1),R(1),R(1)])]),Bn=()=>W(`mfro`,0,0,[R(0)]),Vn=()=>U(`vtte`),Hn=(e,t,n,r,i)=>U(`vttc`,void 0,[i===null?null:U(`vsid`,[z(i)]),n===null?null:U(`iden`,[...O.encode(n)]),t===null?null:U(`ctim`,[...O.encode(wt(t))]),r===null?null:U(`sttg`,[...O.encode(r)]),U(`payl`,[...O.encode(e)])]),Un=e=>U(`vtta`,[...O.encode(e)]),Wn=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Jn(r);e&&t.push(e)}else if(n===`mdta`){let e=Yn(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Gn(t,e.output._metadataTags);return t.length===0?null:U(`udta`,void 0,t)},Gn=(e,t)=>{for(let{key:n,value:r}of ce(t))switch(n){case`title`:e.push(J(`©nam`,r));break;case`description`:e.push(J(`©des`,r));break;case`artist`:e.push(J(`©ART`,r));break;case`album`:e.push(J(`©alb`,r));break;case`albumArtist`:e.push(J(`albr`,r));break;case`genre`:e.push(J(`©gen`,r));break;case`date`:e.push(J(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(J(`©cmt`,r));break;case`lyrics`:e.push(J(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:Xe(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(J(n,r)):r instanceof Uint8Array&&e.push(U(n,Array.from(r))))}},J=(e,t)=>{let n=O.encode(t);return U(e,[L(n.length),L(nr(`und`)),Array.from(n)])},Kn={"image/jpeg":13,"image/png":14,"image/bmp":27},qn=(t,n)=>{let r=[];for(let{key:e,value:i}of ce(t))switch(e){case`title`:r.push({key:n?`title`:`©nam`,value:Y(i)});break;case`description`:r.push({key:n?`description`:`©des`,value:Y(i)});break;case`artist`:r.push({key:n?`artist`:`©ART`,value:Y(i)});break;case`album`:r.push({key:n?`album`:`©alb`,value:Y(i)});break;case`albumArtist`:r.push({key:n?`album_artist`:`aART`,value:Y(i)});break;case`comment`:r.push({key:n?`comment`:`©cmt`,value:Y(i)});break;case`genre`:r.push({key:n?`genre`:`©gen`,value:Y(i)});break;case`lyrics`:r.push({key:n?`lyrics`:`©lyr`,value:Y(i)});break;case`date`:r.push({key:n?`date`:`©day`,value:Y(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&r.push({key:`covr`,value:U(`data`,[R(Kn[e.mimeType]??0),R(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:Y(e)})}else r.push({key:`trkn`,value:U(`data`,[R(0),R(0),L(0),L(i),L(t.tracksTotal??0),L(0)])});break;case`discNumber`:n||r.push({key:`disc`,value:U(`data`,[R(0),R(0),L(0),L(i),L(t.discsTotal??0),L(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Xe(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:Y(a)}):a instanceof Uint8Array?r.push({key:i,value:U(`data`,[R(0),R(0),Array.from(a)])}):a instanceof e&&r.push({key:i,value:U(`data`,[R(Kn[a.mimeType]??0),R(0),Array.from(a.data)])}))}return r},Jn=e=>{let t=qn(e,!1);return t.length===0?null:W(`meta`,0,0,void 0,[Yt(!1,`mdir`,``,`appl`),U(`ilst`,void 0,t.map(e=>U(e.key,void 0,[e.value])))])},Yn=e=>{let t=qn(e,!0);return t.length===0?null:U(`meta`,void 0,[Yt(!1,`mdta`,``),W(`keys`,0,0,[R(t.length)],t.map(e=>U(`mdta`,[...O.encode(e.key)]))),U(`ilst`,void 0,t.map((e,t)=>U(String.fromCharCode(...R(t+1)),void 0,[e.value])))])},Y=e=>U(`data`,[R(1),R(0),...O.encode(e)]),Xn=(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}},Zn={avc:sn,hevc:cn,vp8:ln,vp9:ln,av1:un,prores:null},Qn=(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`}},$n=(e,t)=>{switch(e){case`aac`:return fn;case`mp3`:return fn;case`opus`:return hn;case`vorbis`:return fn;case`flac`:return gn;case`ac3`:return _n;case`eac3`:return vn;case`dts`:return yn}if(t)switch(e){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}else switch(e){case`pcm-s16`:return q;case`pcm-s16be`:return q;case`pcm-s24`:return q;case`pcm-s24be`:return q;case`pcm-s32`:return q;case`pcm-s32be`:return q;case`pcm-f32`:return q;case`pcm-f32be`:return q;case`pcm-f64`:return q;case`pcm-f64be`:return q}return null},er={webvtt:`wvtt`},tr={webvtt:xn},nr=e=>{A(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},rr=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(){A(!this.started),this.target._start(),this.started=!0}write(e){A(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 A(this.started&&!this.finalized),this.target._flush()}async finalize(){A(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}};ge();var X=class extends Be{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 sr(this,e)}},ir=2**16,ar=2**32,or=class extends X{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(ir,{maxByteLength:ar})}catch{this._buffer=new ArrayBuffer(ir),this._supportsResize=!1}else this._buffer=new ArrayBuffer(ir);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>ar)throw Error(`ArrayBuffer exceeded maximum size of ${ar} 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)}},sr=class extends X{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)}},cr=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.`)}},Z=57600,lr=2082844800,ur=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Q=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},dr=class extends St{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new or,this.auxWriter=new rr(this.auxTarget,!1),this.auxBoxWriter=new Tt(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=l(),this.creationTime=Math.floor(Date.now()/1e3)+lr,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 jr,this.isCmaf=t instanceof Ar,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof Ar?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 or:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new Tt(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof or&&`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 rr(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Tt(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(A(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Ft({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||(A(this.writer),A(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Rt(!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 tt({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,i){let a=this.trackDatas.find(t=>t.track===e);if(a)return a;u(i,e.source._codec),A(i),A(i.decoderConfig);let o={...i.decoderConfig};A(o.codedWidth!==void 0),A(o.codedHeight!==void 0);let s=!1;if(e.source._codec===`avc`&&!o.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=rt(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.`);o.description=_(e),s=!0}else if(e.source._codec===`hevc`&&!o.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.`);o.description=Ue(e),s=!0}let c=Ie(1/(e.metadata.frameRate??57600),1e6).den,l=o.displayAspectWidth,d=o.displayAspectHeight,f=l===void 0||d===void 0?{num:1,den:1}:n({num:l*o.codedHeight,den:d*o.codedWidth}),p=o.codec===`ap4h`||o.codec===`ap4x`,m={muxer:this,track:e,type:`video`,info:{width:o.codedWidth,height:o.codedHeight,pixelAspectRatio:f,decoderConfig:o,requiresAnnexBTransformation:s,hasAlphaChannel:p},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(m),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),m}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;S(n,e.source._codec),A(n),A(n.decoderConfig);let a={...n.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){if(!t)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let e=Ze(Le.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=me[e.samplingFrequencyIndex],r=g[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=pe({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:a,requiresPcmTransformation:!this.isFragmented&&i.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:t},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};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;ne(t),A(t),A(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,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=[...de(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=v(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=Ze(Le.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=b(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=Q(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=b(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)A(r.timestamp<=t),A(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=Vn();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;Ct.lastIndex=0;let r=Ct.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=Un(n.notes);this.auxBoxWriter.writeBox(e)}let c=Hn(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:Q(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){A(!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=Q(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=a(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=Q(r.timestamp-r.decodeTimestamp,e.timescale),o=Q(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){A(e.lastSample);let t=Q(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(A(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=a(e.timeToSampleTable);if(A(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===o?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let r=a(e.compositionTimeOffsetTable);A(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Q(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,A(e.lastSample),A(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){A(t.type===`key`);let n=Q(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(A(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}),A(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(A(!this.isFragmented),A(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+Q(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||a(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)A(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(A(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(A(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;A(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=G(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){A(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Tt(this.writer);let e=this.boxWriter.measureBox(It()),t=this.boxWriter.measureBox(Lt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}A(this.writer),A(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=jn(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];A(n.currentChunk),A(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=jn(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}A(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Rt(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(){A(this.writer),A(this.boxWriter),this.ensureOneEnabledTrack();let e=G(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;A(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Rt(!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(){A(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;A(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(){A(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)if(await this.finalizeCurrentChunk(e),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(A(this.writer),A(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Rt(!1);let e;for(let t=0;t<2;t++){let t=G(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)A(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=G(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)A(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(It()),this.boxWriter.writeBox(Lt(this,e))}else{let e=this.writer.getPos(),t=Rn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{A(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);A(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=G(this);if(this.fastStart===`reserve`){A(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(zt(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}},fr=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,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){A(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){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),A(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.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;A(n<this.bufferSizeInFrames);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;A(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new k({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},pr=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},mr=(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}),hr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_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})()}},gr=class extends hr{constructor(e){if(super(),this._connectedTrack=null,!w.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${w.join(`, `)}.`);this._codec=e}},_r=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},vr=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.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 ye,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?.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`&&(A(this.outputWidth),A(this.outputHeight),A(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,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=ke(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(E(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let i=[];try{for(let n of t)n instanceof Ye?i.push(n):typeof VideoFrame<`u`&&n instanceof VideoFrame?i.push(new Ye(n)):i.push(new Ye(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 Ye&&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),A(this.encoderInitialized),this.closed)break;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{A(this.encoder);let t=e.toVideoFrame(),n=Ce(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 br;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;A(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=pr(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{mr(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=bt(this.encodingConfig.quality,this.encodingConfig.bitrate);A(t!==void 0);let n=ct({...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=be.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(le(`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;if(r.quantizer!==null&&(this.defaultEncodeOptions=gt(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 T))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.`);_r(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();else{let e=[],t=[],n=0,r=0,i=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=T.fromEncodedChunk(e,r),a=Ce(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=ae(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})),_r(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++},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(a,o)=>{if(!this.alphaEncoder){i(a,null,o);return}let s=this.alphaFrameQueue.shift();A(s!==void 0),s?(this.alphaEncoder.encode(s,{...this.defaultEncodeOptions,keyFrame:a.type===`key`}),r++,s.close(),e.push({chunk:a,meta:o})):r===0?i(a,null,o):(t.push(n+r),e.push({chunk:a,meta:o}))},error:e=>{e.stack=o,this.setError(e)}}),this.encoder.configure(a),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(a,o)=>{r--;let s=e.shift();for(A(s!==void 0),i(s.chunk,a,s.meta),n++;t.length>0&&t[0]===n;){t.shift();let n=e.shift();A(n!==void 0),i(n.chunk,null,n.meta)}},error:e=>{e.stack=o,this.setError(e)}}),this.alphaEncoder.configure(a)}}A(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=ke(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await re(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}},yr=null,br=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!yr){let e=new Blob([`(${xr.toString()})()`],{type:`application/javascript`});yr=URL.createObjectURL(e)}this.worker=new Worker(yr),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=l();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}},xr=()=>{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,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 C=a?`I420P10`:o?`I420P12`:`I420`,ee=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),te={format:C,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[y.buffer]};return{colorFrame:ee,alphaFrame:new VideoFrame(y,te)}}},Sr=class extends gr{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.`);ot(t),super(t.codec),this._encoder=new vr(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 Ye(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Cr=class extends hr{constructor(e){if(super(),this._connectedTrack=null,!j.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${j.join(`, `)}.`);this._codec=e}},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.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new ye,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 fr({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&&Te(e.format)!==n.transform.sampleFormat){let r=Se(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(E(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof k))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 k&&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),A(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 k({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{A(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){A(this.outputSampleSize),A(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.allocationSize({planeIndex:0,format:`f32-planar`}),l=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(l,{planeIndex:t,format:`f32-planar`});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,l[e*o+a])}}t&&e.close();let u={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 T(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=bt(this.encodingConfig.quality,this.encodingConfig.bitrate),o=dt({numberOfChannels:t,sampleRate:n,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(o);let c=Ke.find(e=>e.supports(this.encodingConfig.codec,o));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof T))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(i.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(le(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.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||he(C(t.decoderConfig.description)).objectType===0,e){let e=Number(a(o.codec.split(`.`)));t.decoderConfig.description=pe({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=T.fromEncodedChunk(e);n=n.clone({timestamp:s(n.timestamp,o.sampleRate),duration:e.duration==null?void 0:s(n.duration,o.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(o)}A(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}=b(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,D((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,D(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=D(Math.floor(n*32767),-32768,32767);e.setUint8(t,ze(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=D(Math.floor(n*32767),-32768,32767);e.setUint8(t,ve(r))}:A(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,D((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,D(Math.round(n*32767),-32768,32767),r):A(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>Pe(e,t,D((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>te(e,t,D(Math.round(n*8388607),-8388608,8388607),r):A(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,D((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,D(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):A(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):A(!1);break;default:Xe(n),A(!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}},Tr=class extends Cr{constructor(e,t={}){if(lt(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 wr(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=k._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)}},Er=class extends hr{constructor(e){if(super(),this._connectedTrack=null,!$e.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${$e.join(`, `)}.`);this._codec=e}},Dr=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>w.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>j.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>$e.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Or=class extends Dr{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&&(!nt(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 supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new dr(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},kr=class extends Or{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...w,...se,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...$e]}_codecUnsupportedHint(e){return new jr().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Ar=class extends Or{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...w,...se,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...$e]}},jr=class extends Or{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...w,...j]}_codecUnsupportedHint(e){return new kr().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Mr=[`video`,`audio`,`subtitle`],Nr=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=x(this.metadata.group),r=x(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}},Pr=class extends Nr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Fr=class extends Nr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Ir=class extends Nr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Lr=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)}},Rr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!Qe(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&&Je(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.group!==void 0&&!(e.group instanceof Lr)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Lr))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},zr=class extends Be{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(E(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Lr,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Ge,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 Dr))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof X||e.target instanceof cr))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof X&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof X)&&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 X&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){A(this._target instanceof cr);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof X))throw TypeError(`getTarget must return a Target.`);return e};return E(t)?t.then(n):n(t)}async _getTarget(e){A(this._target instanceof cr);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(A(this._initTarget!==null),this._initTarget instanceof X)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 X)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 E(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new rr(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof gr))throw TypeError(`source must be a VideoSource.`);if(Rr(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(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);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.decoderConfig!==void 0&&u({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof T))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 Pr(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Cr))throw TypeError(`source must be an AudioSource.`);if(Rr(t),t.decoderConfig!==void 0&&S({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof T))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 Fr(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Er))throw TypeError(`source must be a SubtitleSource.`);Rr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Ir(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(we(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 Mr)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 Mr){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?(Re._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._cancelPromise)return Re._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&Re._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?(Re._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`}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},Br=oe,Vr=[{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 Hr(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=Vr.find(s),l=Vr.find(e=>s(e)&&o*r<=e.maxMacroblocksPerSecond&&Math.max(i,a)<=Math.sqrt(e.maxMacroblocks*8))??Vr[Vr.length-1];if(c&&l!==c)return`avc1.6400${l.levelIdc.toString(16).padStart(2,`0`)}`}function Ur(e){return e instanceof Error&&/is not (supported|available) in this environment/.test(e.message)}async function Wr({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 y(()=>t(s),{...r,shouldRetry:Ur});return i&&console.warn(`[polotno-video-export] Encoding with ${s}: ${i.message}`),e}catch(e){if(!Ur(e))throw e;i=e}}throw Br(`VIDEO_FAILED`,`Your browser doesn't support video encoding. Tried ${a.join(`, `)}; last error: ${i?.message}`,{reason:`no-encoder`},i)}function Gr(){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 Kr(e){return Math.round(e/2)*2}function qr(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function Jr(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 Yr(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:Kr(t),height:Kr(n)}}function Xr(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 Zr(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 Qr(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 $r(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 Br(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}var ei=e=>e.cancel().catch(()=>{});function ti(e,t,n){let{width:r,height:i}=t;return vt(e,{width:r,height:i,quality:_t,fullCodecString:Hr(e,r,i,n)})}async function ni(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=Xr(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 xt(s,{numberOfChannels:2,sampleRate:44100,quality:_t});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 Tr({codec:c,quality:_t});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function ri(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 ii(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function ai(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=ri(_,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 ii(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 oi(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw Br(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function si(e,t){return e.decodeAudioData(t)}function ci(e){return e.startsWith(`data:`)}function li(e){return e.startsWith(`file://`)}function ui(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function di(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 fi(e,t){try{if(ui(e))return new We({source:new Ee(e),formats:Fe});if(ci(e)){let t=di(e);return new We({source:new Oe(t),formats:Fe})}if(li(e)){let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new We({source:new Oe(n),formats:Fe})}{let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new We({source:new Oe(n),formats:Fe})}}catch(n){return $(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function pi(e,t){try{t?.throwIfAborted();let n=await fi(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(),Gr();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if($(n))throw n;if(t?.aborted)throw Gr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function mi(e,t){let n=e.audios||[],r=Xr(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:oi(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:pi(e.src,t).catch(e=>{if($(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function hi(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 gi(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=d(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 f=n.offlineContext.createBufferSource();f.buffer=t,f.playbackRate.value=e.speed,f.loop=!0,f.loopStart=l,f.loopEnd=l+u;let p=n.offlineContext.createGain();p.gain.value=e.volume,f.connect(p),p.connect(n.offlineContext.destination),f.start(c,l),f.stop(c+s)}async function _i(e,t,n,r,i,a,o){o?.throwIfAborted();let s=i||mi(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 si(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 Ae(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&&hi(e.audio,e.audioBuffer,_);for(let e of x)e&&gi(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 vi({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){r?.(0,void 0,{stage:`setup`});let o=Yr(e),s=Zr(e,o),c=null,l=null,u=!1;if(a){let e=()=>{try{c?.canvasSource.close()}catch{}try{c?.audioBufferSource?.close()}catch{}c&&ei(c.output)};a.addEventListener(`abort`,e,{once:!0}),l=()=>a.removeEventListener(`abort`,e)}try{a?.throwIfAborted();let s=qr(e);if(s===0)throw Br(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let l=Jr(e),{canvas:d,canvases:f}=$r(o,n),p=async(n,r,a)=>{let o=new zr({target:new or,format:new kr});try{let s=new Sr(d,{codec:n,quality:_t,fullCodecString:Hr(n,d.width,d.height,t)});o.addVideoTrack(s,{frameRate:t});let c=await ni(o,e,i);return await o.start(),await s.add(r,a),{output:o,canvasSource:s,...c}}catch(e){throw await ei(o),e}},m=new kr().getSupportedVideoCodecs();await ai(e,async(e,n)=>{if(c){await c.canvasSource.add(e,n);return}c=await Wr({codecs:m,probe:e=>ti(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=_?mi(e,a):null;_&&y&&(await _i(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?Gr():e}finally{l?.(),!u&&c&&await ei(c.output),Qr(e,s)}}export{vi as storeToVideo};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
function e(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 t(e){if(Array.isArray(e))return e}function n(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)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 r(){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 i(e,i){return t(e)||n(e,i)||a(e,i)||r()}function a(t,n){if(t){if(typeof t==`string`)return e(t,n);var r={}.toString.call(t).slice(8,-1);return r===`Object`&&t.constructor&&(r=t.constructor.name),r===`Map`||r===`Set`?Array.from(t):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var o=Object.entries,s=Object.setPrototypeOf,c=Object.isFrozen,l=Object.getPrototypeOf,u=Object.getOwnPropertyDescriptor,d=Object.freeze,f=Object.seal,p=Object.create,m=typeof Reflect<`u`&&Reflect,h=m.apply,ee=m.construct;d||=function(e){return e},f||=function(e){return e},h||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},ee||=function(e){return new e(...[...arguments].slice(1))};var g=w(Array.prototype.forEach),te=w(Array.prototype.lastIndexOf),ne=w(Array.prototype.pop),re=w(Array.prototype.push),ie=w(Array.prototype.splice),_=Array.isArray,ae=w(String.prototype.toLowerCase),oe=w(String.prototype.toString),se=w(String.prototype.match),v=w(String.prototype.replace),ce=w(String.prototype.indexOf),le=w(String.prototype.trim),ue=w(Number.prototype.toString),de=w(Boolean.prototype.toString),fe=typeof BigInt>`u`?null:w(BigInt.prototype.toString),y=typeof Symbol>`u`?null:w(Symbol.prototype.toString),b=w(Object.prototype.hasOwnProperty),x=w(Object.prototype.toString),S=w(RegExp.prototype.test),C=pe(TypeError);function w(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return h(e,t,n)}}function pe(e){return function(){return ee(e,[...arguments])}}function T(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ae;if(s&&s(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&&(c(t)||(t[r]=e),i=e)}e[i]=!0}return e}function E(e){for(let t=0;t<e.length;t++)b(e,t)||(e[t]=null);return e}function D(e){let t=p(null);for(let r of o(e)){var n=i(r,2);let a=n[0],o=n[1];b(e,a)&&(t[a]=_(o)?E(o):o&&typeof o==`object`&&o.constructor===Object?D(o):o)}return t}function me(e){switch(typeof e){case`string`:return e;case`number`:return ue(e);case`boolean`:return de(e);case`bigint`:return fe?fe(e):`0`;case`symbol`:return y?y(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=u(e,t);if(n){if(n.get)return w(n.get);if(typeof n.value==`function`)return w(n.value)}e=l(e)}function n(){return null}return n}function he(e){try{return S(e,``),!0}catch{return!1}}var ge=d(`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(`.`)),_e=d(`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(`.`)),ve=d([`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`]),ye=d([`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`]),be=d(`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(`.`)),xe=d([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Se=d([`#text`]),Ce=d(`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(`.`)),we=d(`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(`.`)),Te=d(`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(`.`)),Ee=d([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),De=f(/{{[\w\W]*|^[\w\W]*}}/g),Oe=f(/<%[\w\W]*|^[\w\W]*%>/g),ke=f(/\${[\w\W]*/g),Ae=f(/^data-[\-\w.\u00B7-\uFFFF]+$/),je=f(/^aria-[\-\w]+$/),Me=f(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ne=f(/^(?:\w+script|data):/i),Pe=f(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Fe=f(/^html$/i),Ie=f(/^[a-z][.\w]*(-[.\w]+)+$/i),Le=f(/<[/\w!]/g),Re=f(/<[/\w]/g),ze=f(/<\/no(script|embed|frames)/i),Be=f(/\/>/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`],Ve=d(T({},A)),He=function(){let e={};return g(A,t=>{e[t]=f(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),d(e)}(),Ue=function(){return typeof window>`u`?null:window},We=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}},Ge=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},j=function(e,t,n,r){return b(e,t)&&_(e[t])?T(r.base?D(r.base):{},e[t],r.transform):n},Ke=function(e,t,n){let r=b(e,t)?e[t]:void 0;return r&&typeof r==`object`?D(r):n()};function qe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ue(),t=e=>qe(e);if(t.version=`3.4.15`,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,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,m=e.trustedTypes,h=c.prototype,ee=O(h,`cloneNode`),ue=O(h,`remove`),de=O(h,`removeAttributeNode`),fe=O(h,`nextSibling`),y=O(h,`childNodes`),x=O(h,`parentNode`),w=O(h,`shadowRoot`),pe=O(h,`attributes`),E=s&&s.prototype?O(s.prototype,`nodeType`):null,A=s&&s.prototype?O(s.prototype,`nodeName`):null,Je=s&&s.prototype?O(s.prototype,`ownerDocument`):null,Ye=function(e){return E?E(e):e.nodeType},Xe=function(e){return A?A(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=We(m,i),!0),Ze},rt=n,it=rt.implementation,at=rt.createNodeIterator,ot=rt.createDocumentFragment,st=rt.getElementsByTagName,ct=r.importNode,F=Ge();t.isSupported=typeof o==`function`&&typeof x==`function`&&it&&it.createHTMLDocument!==void 0;let lt=De,ut=Oe,dt=ke,ft=Ae,pt=je,mt=Ne,ht=Pe,gt=Ie,_t=Me,I=null,vt=T({},[...ge,..._e,...ve,...be,...Se]),L=null,yt=T({},[...Ce,...we,...Te,...Ee]),R=Object.seal(p(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(p(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=T({},`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=T({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Bt=null,Vt=T({},[`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=T({},[Ht,Ut,K],oe),qt=d([`mi`,`mo`,`mn`,`ms`,`mtext`]),Jt=T({},qt),Yt=d([`annotation-xml`]),Xt=T({},Yt),Zt=T({},[`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`?oe:ae,I=j(e,`ALLOWED_TAGS`,vt,{transform:J}),L=j(e,`ALLOWED_ATTR`,yt,{transform:J}),Gt=j(e,`ALLOWED_NAMESPACES`,Kt,{transform:oe}),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=he(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Me,q=typeof e.NAMESPACE==`string`?e.NAMESPACE:K,Jt=Ke(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>T({},qt)),Xt=Ke(e,`HTML_INTEGRATION_POINTS`,()=>T({},Yt));let t=Ke(e,`CUSTOM_ELEMENT_HANDLING`,()=>p(null));if(R=p(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),f(R),B&&(Ct=!1),At&&(U=!0),W&&(I=T({},Se),L=p(null),W.html===!0&&(T(I,ge),T(L,Ce)),W.svg===!0&&(T(I,_e),T(L,we),T(L,Ee)),W.svgFilters===!0&&(T(I,ve),T(L,we),T(L,Ee)),W.mathMl===!0&&(T(I,be),T(L,Te),T(L,Ee))),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)),T(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)),T(L,e.ADD_ATTR,J))),b(e,`ADD_FORBID_CONTENTS`)&&_(e.ADD_FORBID_CONTENTS)&&(G===Lt&&(G=D(G)),T(G,e.ADD_FORBID_CONTENTS,J)),Ft&&(I[`#text`]=!0),H&&T(I,[`html`,`head`,`body`]),I.table&&(T(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(``)));d&&d(e),Y=e},rn=T({},[..._e,...ve,...ye]),an=T({},[...be,...xe]),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=x(e);(!t||!t.tagName)&&(t={namespaceURI:q,tagName:`template`});let n=ae(e.tagName),r=ae(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){re(t.removed,{element:e});try{x(e).removeChild(e)}catch{if(ue(e),!x(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{de(e,t)}catch{try{e.removeAttribute(n)}catch{}}},dn=function(e){pn(e);let t=y(e);if(t){let e=[];g(t,t=>{re(e,t)}),g(e,e=>{try{ue(e)}catch{}})}let n=pe(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}re(t.removed,{attribute:r||null,from:n});try{r?de(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=pe(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();Ye(e)===k.element&&fn(e);let n=y(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=Ye(e);if(n===k.processingInstruction||n===k.comment&&S(Re,e.data)){try{ue(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=y(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=se(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=Je?Je(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=v(e,lt,` `),e=v(e,ut,` `),e=v(e,dt,` `),e},yn=function(e){e.normalize();let t=Je?Je(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=>{Q(e.content)&&yn(e.content)})},bn=function(e){let t=A?A(e):null;return typeof t!=`string`||J(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==pe(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!==E(e)||e.childNodes!==y(e)},Q=function(e){if(!E||typeof e!=`object`||!e)return!1;try{return E(e)===k.documentFragment}catch{return!1}},xn=function(e){if(!E||typeof e!=`object`||!e)return!1;try{return typeof E(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&g(e,e=>{e.call(t,n,r,Y)})}let Sn=function(e,t){return!!(V&&e.hasChildNodes()&&!xn(e.firstElementChild)&&S(Le,e.textContent)&&S(Le,e.innerHTML)||V&&e.namespaceURI===K&&Ve[t]&&(xn(e.firstElementChild)||typeof e.textContent==`string`&&S(He[t],e.textContent))||e.nodeType===k.processingInstruction||V&&e.nodeType===k.comment&&S(Re,e.data))},Cn=function(e,t){return e instanceof RegExp?S(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},wn=function(e,t,n){if(!bt[t]&&An(t)&&Cn(R.tagNameCheck,t))return!1;if(Ft&&!G[t]){let t=x(e),r=y(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,fe(e))}}}return X(e),!0},Tn=function(e,t,n,r){return e.length===0?t:t===n||t===r?D(t):t},En=function(e,t){return e===t||x(e)!==null?!1:(It&&pn(e),!0)},Dn=function(e,n){if($(F.beforeSanitizeElements,e,null),En(e,n))return!0;if(bn(e))return X(e),!0;let r=J(Xe(e));if(I=Tn(F.uponSanitizeElement,I,vt,Dt),$(F.uponSanitizeElement,e,{tagName:r,allowedTags:I}),En(e,n))return!0;if(Sn(e,r))return X(e),!0;if(bt[r]||!(z.tagCheck instanceof Function&&z.tagCheck(r))&&!I[r]){let t=wn(e,r,n);return t===!1&&$(F.afterSanitizeElements,e,null),t}if(Ye(e)===k.element&&!ln(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&S(ze,e.innerHTML))return X(e),!0;if(B&&e.nodeType===k.text){let n=vn(e.textContent);e.textContent!==n&&(re(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(F.afterSanitizeElements,e,null),!1},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,v(r,ht,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&ce(r,`data:`)===0&&Rt[e]||wt&&!S(mt,v(r,ht,``))?!0:!r:An(e)&&Cn(R.tagNameCheck,e)&&Cn(R.attributeNameCheck,t,e)||t===`is`&&R.allowCustomizedBuiltInElements&&Cn(R.tagNameCheck,r)},kn=T({},[`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[ae(e)]&&S(gt,e)},jn=function(e,t,n,r){if(M&&typeof m==`object`&&typeof m.getAttributeType==`function`&&!n)switch(m.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){$(F.beforeSanitizeAttributes,e,null);let n=e.attributes;if(!n||bn(e))return;L=Tn(F.uponSanitizeAttribute,L,yt,Ot);let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0},i=n.length,a=J(e.nodeName);for(;i--;){let o=n[i],s=o.name,c=o.namespaceURI,l=o.value,u=J(s),d=l,f=s===`value`?d:le(d),p=!1;if(r.attrName=u,r.attrValue=f,r.keepAttr=!0,r.forceKeepAttr=void 0,$(F.uponSanitizeAttribute,e,r),f=r.attrValue,Nt&&(u===`id`||u===`name`)&&ce(f,Pt)!==0&&(Z(s,e,o),f=Pt+f,p=!0),V&&S(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,f)){Z(s,e,o);continue}if(u===`attributename`&&se(f,`href`)){Z(s,e,o);continue}if(!r.forceKeepAttr){if(!r.keepAttr){Z(s,e,o);continue}if(!Tt&&S(Be,f)){Z(s,e,o);continue}if(B&&(f=vn(f)),!On(a,u,f)){Z(s,e,o);continue}f=jn(a,u,c,f),f!==d&&Mn(e,s,c,f)&&p&&ne(t.removed)}}$(F.afterSanitizeAttributes,e,null)},Pn=function(e){let t=null,n=_n(e);for($(F.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(F.uponSanitizeShadowNode,t,null),Dn(t,e),Nn(t),Q(t.content)&&Pn(t.content),Ye(t)===k.element){let e=w(t);Q(e)&&(Fn(e),Pn(e))}$(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=Ye(n)===k.element,i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=A?A(n):null;if(typeof e==`string`&&J(e)===`template`){let e=n.content;Q(e)&&t.push({node:e,shadow:null})}}if(r){let e=w(n);Q(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`&&!xn(e)&&(e=me(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`&&xn(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(xn(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),Q(o.content)&&Pn(o.content)}catch(n){throw c&&(dn(e),g(t.removed,e=>{e.element&&pn(e.element)})),n}if(c)return g(t.removed,e=>{e.element&&pn(e.element)}),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(Fe,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)&&re(F[e],t)},t.removeHook=function(e,t){if(b(F,e)){if(t!==void 0){let n=te(F[e],t);return n===-1?void 0:ie(F[e],n,1)[0]}return ne(F[e])}},t.removeHooks=function(e){b(F,e)&&(F[e]=[])},t.removeAllHooks=function(){F=Ge()},t}var Je=qe();export{Je as default};
|
package/dist/index.html
CHANGED
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
<html>
|
|
2
2
|
<head>
|
|
3
3
|
<title>Canvas editor</title>
|
|
4
|
-
<style>
|
|
5
|
-
body {
|
|
6
|
-
padding: 0;
|
|
7
|
-
margin: 0;
|
|
8
|
-
}
|
|
9
|
-
</style>
|
|
4
|
+
<style>body{margin:0;padding:0}</style>
|
|
10
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
11
|
-
<script type="module" crossorigin src="./assets/index-
|
|
6
|
+
<script type="module" crossorigin src="./assets/index-CpBN0dhf.js"></script>
|
|
12
7
|
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-hePW80VL.js">
|
|
13
8
|
</head>
|
|
14
9
|
<body>
|
package/lib/instance.d.ts
CHANGED
|
@@ -13,16 +13,7 @@ declare global {
|
|
|
13
13
|
__polotnoVideoHeartbeat?: () => Promise<void>;
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
export
|
|
17
|
-
/**
|
|
18
|
-
* Visit every URL-holding field in a design: `visit(node, key, value)` for each
|
|
19
|
-
* string under one of `URL_FIELDS`, `custom` skipped whole.
|
|
20
|
-
*
|
|
21
|
-
* Exported because `@polotno/fidelity` inlines a fixture's local assets over
|
|
22
|
-
* the same fields — which subtrees a rewrite may enter is one rule, and two
|
|
23
|
-
* copies of it drift. Changing either one needs that package's `test:unit`.
|
|
24
|
-
*/
|
|
25
|
-
export declare const forEveryUrlField: (node: any, visit: any) => void;
|
|
16
|
+
export { URL_FIELDS, forEveryUrlField } from '@polotno/schema/asset-urls';
|
|
26
17
|
/**
|
|
27
18
|
* Rewrite every `file:` source in a design to a URL the client can load with
|
|
28
19
|
* any API. Designs without one — the common case — come back untouched, so this
|
package/lib/instance.js
CHANGED
|
@@ -7,6 +7,7 @@ import { pathToFileURL, fileURLToPath } from 'url';
|
|
|
7
7
|
import { Readable } from 'stream';
|
|
8
8
|
import { pipeline } from 'stream/promises';
|
|
9
9
|
import { assertValidDesign } from '@polotno/schema';
|
|
10
|
+
import { forEveryUrlField } from '@polotno/schema/asset-urls';
|
|
10
11
|
import * as fontCache from './font-cache.js';
|
|
11
12
|
import * as localMedia from './local-media.js';
|
|
12
13
|
import { polotnoError, rehydrateError } from './errors.js';
|
|
@@ -53,48 +54,8 @@ const collectMediaSourcePointers = (json) => {
|
|
|
53
54
|
}
|
|
54
55
|
return pointers;
|
|
55
56
|
};
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
// for why the browser must never see that scheme. Every other value is passed
|
|
59
|
-
// through exactly as the caller wrote it.
|
|
60
|
-
//
|
|
61
|
-
// A list, rather than "rewrite every `file:` string anywhere", because a design
|
|
62
|
-
// carries text: a text element whose content reads `file:///notes.txt` is
|
|
63
|
-
// content, and rewriting it corrupts the render. `custom` is arbitrary caller
|
|
64
|
-
// data with the same problem, so the walk does not enter it at all. And
|
|
65
|
-
// `test/unit/local-media.test.mjs` fails when the schema grows a field named
|
|
66
|
-
// like one that is missing here.
|
|
67
|
-
export const URL_FIELDS = ['src', 'clipSrc', 'maskSrc', 'background', 'url'];
|
|
68
|
-
const URL_FIELD_SET = new Set(URL_FIELDS);
|
|
69
|
-
/**
|
|
70
|
-
* Visit every URL-holding field in a design: `visit(node, key, value)` for each
|
|
71
|
-
* string under one of `URL_FIELDS`, `custom` skipped whole.
|
|
72
|
-
*
|
|
73
|
-
* Exported because `@polotno/fidelity` inlines a fixture's local assets over
|
|
74
|
-
* the same fields — which subtrees a rewrite may enter is one rule, and two
|
|
75
|
-
* copies of it drift. Changing either one needs that package's `test:unit`.
|
|
76
|
-
*/
|
|
77
|
-
export const forEveryUrlField = (node, visit) => {
|
|
78
|
-
if (!node || typeof node !== 'object')
|
|
79
|
-
return;
|
|
80
|
-
if (Array.isArray(node)) {
|
|
81
|
-
for (const item of node)
|
|
82
|
-
forEveryUrlField(item, visit);
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
for (const key of Object.keys(node)) {
|
|
86
|
-
if (key === 'custom')
|
|
87
|
-
continue;
|
|
88
|
-
const value = node[key];
|
|
89
|
-
if (typeof value === 'string') {
|
|
90
|
-
if (URL_FIELD_SET.has(key))
|
|
91
|
-
visit(node, key, value);
|
|
92
|
-
}
|
|
93
|
-
else if (value && typeof value === 'object') {
|
|
94
|
-
forEveryUrlField(value, visit);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
};
|
|
57
|
+
// Keep the published deep-import API while schema owns the asset vocabulary.
|
|
58
|
+
export { URL_FIELDS, forEveryUrlField } from '@polotno/schema/asset-urls';
|
|
98
59
|
// Not `toLowerCase().startsWith`: a `src` is routinely a data URL of several
|
|
99
60
|
// MB, and that would copy every one of them on every render.
|
|
100
61
|
const isFileUrl = (value) => /^file:/i.test(value);
|
|
@@ -1160,11 +1121,12 @@ export const createInstance = async ({ key, url, useParallelPages = true, browse
|
|
|
1160
1121
|
});
|
|
1161
1122
|
const jsonToVideoDataURL = (json, attrs = {}) => renderVideoString(json, attrs, true);
|
|
1162
1123
|
const jsonToVideoBase64 = (json, attrs = {}) => renderVideoString(json, attrs, false);
|
|
1124
|
+
let closing;
|
|
1163
1125
|
const instance = {
|
|
1164
|
-
close: async () => {
|
|
1126
|
+
close: () => (closing ?? (closing = (async () => {
|
|
1165
1127
|
createdInstances.splice(createdInstances.indexOf(instance), 1);
|
|
1166
1128
|
await browser.close();
|
|
1167
|
-
},
|
|
1129
|
+
})())),
|
|
1168
1130
|
firstPage,
|
|
1169
1131
|
browser,
|
|
1170
1132
|
run,
|
|
@@ -1185,7 +1147,7 @@ export const createInstance = async ({ key, url, useParallelPages = true, browse
|
|
|
1185
1147
|
};
|
|
1186
1148
|
// Function to close all created instances in parallel
|
|
1187
1149
|
const closeAllInstances = async () => {
|
|
1188
|
-
await Promise.all(createdInstances.map((instance) => instance.close()));
|
|
1150
|
+
await Promise.all([...createdInstances].map((instance) => instance.close()));
|
|
1189
1151
|
};
|
|
1190
1152
|
// Also handle other termination signals
|
|
1191
1153
|
['SIGINT', 'SIGTERM', 'SIGQUIT', 'exit'].forEach((signal) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno-node",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.11.0",
|
|
4
4
|
"description": "Polotno workflow from NodeJS",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
@@ -35,25 +35,23 @@
|
|
|
35
35
|
"@polotno/video-export"
|
|
36
36
|
],
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@
|
|
39
|
-
"
|
|
38
|
+
"@polotno/design-fixtures": "0.0.0",
|
|
39
|
+
"@polotno/video-export": "0.4.0",
|
|
40
|
+
"@types/node": "^26.6.1",
|
|
40
41
|
"dotenv": "^17.4.2",
|
|
41
|
-
"fluent-ffmpeg": "^2.1.3",
|
|
42
42
|
"jspdf": "^4.2.1",
|
|
43
|
-
"konva": "^10.
|
|
44
|
-
"mediabunny": "^1.
|
|
43
|
+
"konva": "^10.7.0",
|
|
44
|
+
"mediabunny": "^1.56.3",
|
|
45
45
|
"pixelmatch": "^7.2.0",
|
|
46
46
|
"pngjs": "^7.0.0",
|
|
47
|
-
"
|
|
48
|
-
"react
|
|
47
|
+
"polotno": "4.14.0",
|
|
48
|
+
"react": "^19.3.0",
|
|
49
|
+
"react-dom": "^19.3.0",
|
|
49
50
|
"tmp": "^0.2.7",
|
|
50
51
|
"typescript": "~6.0.3",
|
|
51
|
-
"vite": "^8.
|
|
52
|
-
"vitest": "^
|
|
53
|
-
"web-audio-api": "^1.5.
|
|
54
|
-
"@polotno/design-fixtures": "0.0.0",
|
|
55
|
-
"@polotno/video-export": "0.3.0",
|
|
56
|
-
"polotno": "4.12.1"
|
|
52
|
+
"vite": "^8.3.0",
|
|
53
|
+
"vitest": "^5.0.1",
|
|
54
|
+
"web-audio-api": "^1.5.6"
|
|
57
55
|
},
|
|
58
56
|
"overrides": {
|
|
59
57
|
"@polotno/video-export": {
|
|
@@ -63,10 +61,10 @@
|
|
|
63
61
|
},
|
|
64
62
|
"author": "Anton Lavrenov",
|
|
65
63
|
"dependencies": {
|
|
66
|
-
"@
|
|
67
|
-
"
|
|
68
|
-
"puppeteer
|
|
69
|
-
"
|
|
64
|
+
"@polotno/schema": "0.7.0",
|
|
65
|
+
"@sparticuz/chromium": "^153.0.0",
|
|
66
|
+
"puppeteer": "25.11.0",
|
|
67
|
+
"puppeteer-core": "25.11.0"
|
|
70
68
|
},
|
|
71
69
|
"bugs": {
|
|
72
70
|
"url": "https://github.com/polotno-project/polotno-node/issues"
|
|
@@ -78,7 +76,7 @@
|
|
|
78
76
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
79
77
|
"test": "if [ -z \"$TURBO_HASH\" ]; then pnpm exec turbo run build --filter=polotno-node --output-logs=new-only --log-order=stream; fi && vitest run test/unit test/static",
|
|
80
78
|
"test:update-goldens": "rm -f test/static/goldens/*.png test/static/goldens/matrix/*.png && pnpm run test",
|
|
81
|
-
"test:video": "pnpm exec turbo run build --filter=polotno-node &&
|
|
79
|
+
"test:video": "if [ -z \"$TURBO_HASH\" ]; then pnpm exec turbo run build --filter=polotno-node --output-logs=new-only; fi && vitest run test/video/video.test.mjs",
|
|
82
80
|
"test:all": "pnpm exec turbo run build --filter=polotno-node && vitest run test/unit test/static test/video",
|
|
83
81
|
"dev": "vite ./client.html"
|
|
84
82
|
}
|