polotno-node 3.7.0 → 3.8.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/README.md +15 -0
- package/dist/assets/html2canvas-Cm_vP64m.js +5 -0
- package/dist/assets/index-Bc1WTi4k.js +648 -0
- package/dist/assets/index.es-Dg88tupA.js +5 -0
- package/dist/assets/jspdf.es.min-CTt99xrZ.js +79 -0
- package/dist/assets/lib-C3mnf1jX.js +1 -0
- package/dist/assets/purify.es-ChwZkWde.js +3 -0
- package/dist/index.html +1 -3
- package/lib/instance.js +78 -46
- package/package.json +14 -12
- package/dist/assets/html2canvas-DCcDvdvP.js +0 -5
- package/dist/assets/id3-B1cFGCGS.js +0 -16
- package/dist/assets/index-ChlnlbAg.js +0 -647
- package/dist/assets/index.es-5v7ubLSO.js +0 -5
- package/dist/assets/jspdf.es.min-87BhH7b6.js +0 -79
- package/dist/assets/lib-Dlaz_6fT.js +0 -1
- package/dist/assets/preload-helper-HclGiUj8.js +0 -1
- package/dist/assets/purify.es-JEAr64Sr.js +0 -3
- package/dist/assets/typeof-B5XbjTb1.js +0 -1
|
@@ -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,M as y,Mt as b,N as ee,Nt as te,O as ne,Ot as re,P as ie,Pt as ae,Q as oe,R as se,S as ce,St as x,T as S,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 C,bt as w,c as be,ct as xe,d as Se,dt as Ce,et as we,f as Te,ft as T,g as Ee,gt as De,h as Oe,ht as ke,i as Ae,it as je,j as Me,jt as Ne,k as Pe,kt as Fe,l as E,lt as D,m as Ie,mt as Le,n as Re,nt as ze,o as Be,ot as Ve,p as He,pt as Ue,q as We,r as Ge,rt as Ke,s as qe,st as Je,tt as Ye,u as O,ut as Xe,v as Ze,vt as Qe,w as k,wt as $e,x as A,xt as et,y as tt,yt as j,z as nt}from"./index-Bc1WTi4k.js";var rt=new Map,it=new Map,at=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!S.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${S.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.crop!==void 0&&He(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.`);ot(e.codec,e)},ot=(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.`)},st=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}),D(a.length>0),a},ct=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!A.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${A.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(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 M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);lt(e.codec,e)},lt=(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}).`)},ut=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,...Pe(e.codec)}},M=class{constructor(e){if((typeof e==`number`||typeof e==`string`)&&(e={quality:e}),!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.bitrateMode!==void 0&&![`constant`,`variable`].includes(e.bitrateMode))throw TypeError(`options.bitrateMode, when provided, must be 'constant' or 'variable'.`);if(`quality`in e){if(typeof e.quality==`string`?!(e.quality in dt):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`?dt[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=ft[e],o=null,s=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 o=this._quantizer,this._bitrate===void 0&&(s=`quantizer`)}else this._bitrate===void 0&&i&&!this._preferBitrate&&(D(this._quality!==void 0),o=T(Math.round(a(i.worst,i.best,this._quality)),i.min,i.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let r=this._quality;r===void 0&&(D(o!==null&&i),r=T((o-i.worst)/(i.best-i.worst),0,1)),c=mt(e,t,n,pt(r))}return{quantizer:o,bitrate:c,bitrateMode:s}}_toVideoBitrate(e,t,n){return this._bitrate===void 0?(D(this._quality!==void 0),mt(e,t,n,pt(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=pt(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}},dt={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},ft={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}},pt=e=>.3*Math.exp(2.5538*e),mt=(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},ht=(e,t)=>{if(e===`avc`)return{avc:{quantizer:t}};if(e===`hevc`)return{hevc:{quantizer:t}};if(e===`vp9`)return{vp9:{quantizer:t}};if(e===`av1`)return{av1:{quantizer:t}};D(!1)},gt=new M(`high`),_t=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,...o}=t;if(!S.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof M))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof M)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);ot(e,o);let s=yt(i,a)??new M(`medium`),c;try{c=st({codec:e,width:n,height:r,quality:s,framerate:void 0,...o,alpha:`discard`})}catch{return!1}let l=JSON.stringify(c),u=rt.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:ht(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return rt.set(l,d),d},vt=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:a,bitrate:o,...s}=t;if(!A.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(a!==void 0&&!(a instanceof M))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 M)&&(!Number.isInteger(o)||o<=0))throw TypeError(`bitrate must be a positive integer.`);lt(e,s);let c=ut({codec:e,numberOfChannels:n,sampleRate:r,quality:yt(a,o)??new M(`medium`),...s}),l=JSON.stringify(c),u=it.get(l);if(u)return u;let d=(async()=>{if(qe.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 it.set(l,d),d},yt=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof M?t:new M({bitrate:t})},bt=async(e,t)=>{for(let n of e)if(await vt(n,t))return n;return null},xt=class{constructor(e){this.mutex=new Ke,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);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)}}},St=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ct=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`)},wt=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);D(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},N=new Uint8Array(8),P=new DataView(N.buffer),F=e=>[(e%256+256)%256],I=e=>(P.setUint16(0,e,!1),[N[0],N[1]]),Tt=e=>(P.setInt16(0,e,!1),[N[0],N[1]]),Et=e=>(P.setUint32(0,e,!1),[N[1],N[2],N[3]]),L=e=>(P.setUint32(0,e,!1),[N[0],N[1],N[2],N[3]]),R=e=>(P.setInt32(0,e,!1),[N[0],N[1],N[2],N[3]]),z=e=>(P.setUint32(0,Math.floor(e/2**32),!1),P.setUint32(4,e,!1),[N[0],N[1],N[2],N[3],N[4],N[5],N[6],N[7]]),Dt=e=>(P.setInt32(0,Math.floor(e/2**32),!1),P.setUint32(4,e,!1),[N[0],N[1],N[2],N[3],N[4],N[5],N[6],N[7]]),Ot=e=>(P.setInt16(0,256*e,!1),[N[0],N[1]]),B=e=>(P.setInt32(0,2**16*e,!1),[N[0],N[1],N[2],N[3]]),kt=e=>(P.setInt32(0,2**30*e,!1),[N[0],N[1],N[2],N[3]]),At=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},V=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},jt=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]},Mt=jt(0),Nt=e=>[B(e[0]),B(e[1]),kt(e[2]),B(e[3]),B(e[4]),kt(e[5]),B(e[6]),B(e[7]),kt(e[8])],H=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),U=(e,t,n,r,i)=>H(e,[F(t),Et(n),r??[]],i),Pt=e=>e.isQuickTime?H(`ftyp`,[V(`qt `),L(512),V(`qt `)]):e.fragmented?e.cmaf?H(`ftyp`,[V(`iso5`),L(512),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]):H(`ftyp`,[V(`iso5`),L(512),V(`iso5`),V(`iso6`),V(`mp41`)]):H(`ftyp`,[V(`isom`),L(512),V(`isom`),e.holdsAvc?V(`avc1`):[],V(`mp41`)]),Ft=()=>H(`styp`,[V(`iso5`),L(0),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]),It=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),U(`sidx`,1,0,[L(1),L(X),z(Z(e.minWrittenTimestamp,X)),z(0),I(0),I(1),L(t&2147483647),L(Z(n,X)),L(0)])},Lt=e=>({type:`mdat`,largeSize:e}),Rt=e=>({type:`free`,size:e}),W=e=>H(`moov`,void 0,[zt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Vt(t,e.creationTime)),e.isFragmented?On(e.trackDatas):null,Un(e)]),zt=(e,t)=>{let n=Math.max(0,...t.map(e=>Z(Bt(e),X)+Z(e.startTimestampOffset??0,X))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!w(e)||!w(n),a=i?z:L;return U(`mvhd`,+i,0,[a(e),a(e),L(X),a(n),B(1),Ot(1),Array(10).fill(0),Nt(Mt),Array(24).fill(0),L(r)])},Bt=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},Vt=(e,t)=>{let r=lr(e),i=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return H(`trak`,void 0,[Ht(e,t),i?Ut(e,e.startTimestampOffset):null,Wt(e,t),r.name===void 0?null:H(`udta`,void 0,[H(`name`,[...n.encode(r.name)])])])},Ht=(e,t)=>{let n=Z(Bt(e),X)+Z(e.startTimestampOffset??0,X),r=!w(t)||!w(n),i=r?z:L,a;if(e.type===`video`){let t=e.track.metadata.rotation;a=jt(t??0)}else a=Mt;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 U(`tkhd`,+r,o,[i(t),i(t),L(e.track.id),L(0),i(n),Array(8).fill(0),I(0),I(s),Ot(+(e.type===`audio`)),I(0),Nt(a),B(e.type===`video`?e.info.width:0),B(e.type===`video`?e.info.height:0)])},Ut=(e,t)=>{let n=Z(t,X),r=Z(Bt(e),X),i=!w(n)||!w(r),a=i?z:L,o=i?Dt:R;return H(`edts`,void 0,[U(`elst`,+!!i,0,[L(2),a(n),o(-1),B(1),a(r),o(0),B(1)])])},Wt=(e,t)=>H(`mdia`,void 0,[Gt(e,t),Jt(!0,Kt[e.type],qt[e.type]),Yt(e)]),Gt=(e,t)=>{let n=Z(Bt(e),e.timescale),r=!w(t)||!w(n),i=r?z:L;return U(`mdhd`,+r,0,[i(t),i(t),L(e.timescale),i(n),I(tr(e.track.metadata.languageCode??`und`)),I(0)])},Kt={video:`vide`,audio:`soun`,subtitle:`text`},qt={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Jt=(e,t,n,r=`\0\0\0\0`)=>U(`hdlr`,0,0,[e?V(`mhlr`):L(0),V(t),V(r),L(0),L(0),V(n,!0)]),Yt=e=>H(`minf`,void 0,[Xt[e.type](),Zt(),en(e)]),Xt={video:()=>U(`vmhd`,0,1,[I(0),I(0),I(0),I(0)]),audio:()=>U(`smhd`,0,0,[I(0),I(0)]),subtitle:()=>U(`nmhd`,0,0)},Zt=()=>H(`dinf`,void 0,[Qt()]),Qt=()=>U(`dref`,0,0,[L(1)],[$t()]),$t=()=>U(`url `,0,1),en=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return H(`stbl`,void 0,[tn(e),xn(e),t?En(e):null,t?Dn(e):null,Cn(e),wn(e),Tn(e),Sn(e)])},tn=e=>{let t;if(e.type===`video`)t=nn(Yn(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Zn(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);D(n),t=un(n,e)}else e.type===`subtitle`&&(t=yn($n[e.track.source._codec],e));return D(t),U(`stsd`,0,0,[L(1)],[t])},nn=(e,t)=>H(e,[[,,,,,,].fill(0),I(1),I(0),I(0),Array(12).fill(0),I(t.info.width),I(t.info.height),L(4718592),L(4718592),L(0),I(1),F(10),V(`Mediabunny`),Array(21).fill(0),I(t.info.hasAlphaChannel?32:24),Tt(65535)],[Xn[t.track.source._codec]?.(t)??null,rn(t),Ue(t.info.decoderConfig.colorSpace)?null:an(t)]),rn=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:H(`pasp`,[L(e.info.pixelAspectRatio.num),L(e.info.pixelAspectRatio.den)]),an=e=>{let t=e.info.decoderConfig.colorSpace;return H(`colr`,[V(e.muxer.isQuickTime?`nclc`:`nclx`),I(t?.primaries==null?2:je[t.primaries]),I(t?.transfer==null?2:xe[t.transfer]),I(t?.matrix==null?2:Je[t.matrix]),e.muxer.isQuickTime?[]:F(!!t?.fullRange<<7)])},on=e=>e.info.decoderConfig&&H(`avcC`,[...b(e.info.decoderConfig.description)]),sn=e=>e.info.decoderConfig&&H(`hvcC`,[...b(e.info.decoderConfig.description)]),cn=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?Je[t.colorSpace.matrix]:1;return U(`vpcC`,1,0,[F(r),F(i),F(c),F(l),F(u),F(d),I(0)])},ln=e=>H(`av1C`,ne(e.info.decoderConfig.codec)),un=(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}=y(e);a=8*r,a>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(a),I(0),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0)];else{let e=o?0:-2;r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(Math.min(a,16)),Tt(e),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0),o?[L(1),L(a/8),L(t.info.numberOfChannels*a/8)]:[L(0),L(0),L(0)],L(2)]}return H(e,r,[Qn(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},dn=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...F(t),...F(21),...Et(0),...L(0),...L(0)];if(e.info.decoderConfig.description){let t=b(e.info.decoderConfig.description);n=[...n,...F(5),...At(t.byteLength),...t]}return n=[...I(1),...F(0),...F(4),...At(n.length),...n,...F(6),...F(1),...F(2)],n=[...F(3),...At(n.length),...n],U(`esds`,0,0,n)},G=e=>H(`wave`,void 0,[fn(e),pn(e),H(`\0\0\0\0`)]),fn=e=>H(`frma`,[V(Zn(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),pn=e=>{let{littleEndian:t}=y(e.track.source._codec);return H(`enda`,[I(+t)])},mn=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){D(s.byteLength>=18);let e=b(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 H(`dOps`,[F(0),F(t),I(n),L(r),Tt(i),F(a),...o])},hn=e=>{let t=e.info.decoderConfig?.description;return D(t),U(`dfLa`,0,0,[...b(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=y(e.track.source._codec);return U(`pcmC`,0,0,[F(+t),F(8*n)])},gn=e=>{D(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 oe(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),H(`dac3`,[...n])},_n=e=>{D(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 oe(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return H(`dec3`,[...i])},vn=e=>{D(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 H(`ddts`,[...m(t)])},yn=(e,t)=>H(e,[[,,,,,,].fill(0),I(1)],[er[t.track.source._codec](t)]),bn=e=>H(`vttC`,[...n.encode(e.info.config.description)]),xn=e=>U(`stts`,0,0,[L(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[L(e.sampleCount),L(e.sampleDelta)])]),Sn=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return U(`stss`,0,0,[L(t.length),t.map(([e])=>L(e+1))])},Cn=e=>U(`stsc`,0,0,[L(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[L(e.firstChunk),L(e.samplesPerChunk),L(1)])]),wn=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=y(e.track.source._codec);return U(`stsz`,0,0,[L(t*e.info.numberOfChannels),L(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return U(`stsz`,0,0,[L(0),L(e.samples.length),e.samples.map(e=>L(e.size))])},Tn=e=>e.finalizedChunks.length>0&&x(e.finalizedChunks).offset>=2**32?U(`co64`,0,0,[L(e.finalizedChunks.length),e.finalizedChunks.map(e=>z(e.offset))]):U(`stco`,0,0,[L(e.finalizedChunks.length),e.finalizedChunks.map(e=>L(e.offset))]),En=e=>U(`ctts`,1,0,[L(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[L(e.sampleCount),R(e.sampleCompositionTimeOffset)])]),Dn=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;D(e.compositionTimeOffsetTable.length>0),D(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:U(`cslg`,0,0,[R(a),R(t),R(n),R(r),R(i)])},On=e=>H(`mvex`,void 0,e.map(kn)),kn=e=>U(`trex`,0,0,[L(e.track.id),L(1),L(0),L(0),L(0)]),An=(e,t)=>H(`moof`,void 0,[jn(e),...t.map(Nn)]),jn=e=>U(`mfhd`,0,0,[L(e)]),Mn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},Nn=e=>H(`traf`,void 0,[Pn(e),Fn(e),In(e)]),Pn=e=>{D(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Mn(n)};return U(`tfhd`,0,t,[L(e.track.id),L(r.duration),L(r.size),L(r.flags)])},Fn=e=>(D(e.currentChunk),U(`tfdt`,1,0,[z(Z(e.currentChunk.startTimestamp,e.timescale))])),In=e=>{D(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Mn),i=e.currentChunk.samples.map(t=>Z(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,U(`trun`,1,m,[L(e.currentChunk.samples.length),L(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?L(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?L(t[a]):[],d?L(n[a]):[],f?L(r[a]):[],p?R(i[a]):[]])])},Ln=e=>H(`mfra`,void 0,[...e.map(Rn),zn()]),Rn=e=>U(`tfra`,1,0,[L(e.track.id),L(63),L(e.finalizedChunks.length),e.finalizedChunks.map(t=>[z(Z(t.samples[0].timestamp,e.timescale)),z(t.moofOffset),L(t.trafIndex+1),L(1),L(1)])]),zn=()=>U(`mfro`,0,0,[L(0)]),Bn=()=>H(`vtte`),Vn=(e,t,r,i,a)=>H(`vttc`,void 0,[a===null?null:H(`vsid`,[R(a)]),r===null?null:H(`iden`,[...n.encode(r)]),t===null?null:H(`ctim`,[...n.encode(Ct(t))]),i===null?null:H(`sttg`,[...n.encode(i)]),H(`payl`,[...n.encode(e)])]),Hn=e=>H(`vtta`,[...n.encode(e)]),Un=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=qn(r);e&&t.push(e)}else if(n===`mdta`){let e=Jn(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&Wn(t,e.output._metadataTags);return t.length===0?null:H(`udta`,void 0,t)},Wn=(e,t)=>{for(let{key:n,value:r}of et(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`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(q(n,r)):r instanceof Uint8Array&&e.push(H(n,Array.from(r))))}},q=(e,t)=>{let r=n.encode(t);return H(e,[I(r.length),I(tr(`und`)),Array.from(r)])},Gn={"image/jpeg":13,"image/png":14,"image/bmp":27},Kn=(t,n)=>{let r=[];for(let{key:e,value:i}of et(t))switch(e){case`title`:r.push({key:n?`title`:`©nam`,value:J(i)});break;case`description`:r.push({key:n?`description`:`©des`,value:J(i)});break;case`artist`:r.push({key:n?`artist`:`©ART`,value:J(i)});break;case`album`:r.push({key:n?`album`:`©alb`,value:J(i)});break;case`albumArtist`:r.push({key:n?`album_artist`:`aART`,value:J(i)});break;case`comment`:r.push({key:n?`comment`:`©cmt`,value:J(i)});break;case`genre`:r.push({key:n?`genre`:`©gen`,value:J(i)});break;case`lyrics`:r.push({key:n?`lyrics`:`©lyr`,value:J(i)});break;case`date`:r.push({key:n?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&r.push({key:`covr`,value:H(`data`,[L(Gn[e.mimeType]??0),L(0),Array.from(e.data)])});break;case`trackNumber`:if(n){let e=t.tracksTotal===void 0?i.toString():`${i}/${t.tracksTotal}`;r.push({key:`track`,value:J(e)})}else r.push({key:`trkn`,value:H(`data`,[L(0),L(0),I(0),I(i),I(t.tracksTotal??0),I(0)])});break;case`discNumber`:n||r.push({key:`disc`,value:H(`data`,[L(0),L(0),I(0),I(i),I(t.discsTotal??0),I(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default: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:J(a)}):a instanceof Uint8Array?r.push({key:i,value:H(`data`,[L(0),L(0),Array.from(a)])}):a instanceof e&&r.push({key:i,value:H(`data`,[L(Gn[a.mimeType]??0),L(0),Array.from(a.data)])}))}return r},qn=e=>{let t=Kn(e,!1);return t.length===0?null:U(`meta`,0,0,void 0,[Jt(!1,`mdir`,``,`appl`),H(`ilst`,void 0,t.map(e=>H(e.key,void 0,[e.value])))])},Jn=e=>{let t=Kn(e,!0);return t.length===0?null:H(`meta`,void 0,[Jt(!1,`mdta`,``),U(`keys`,0,0,[L(t.length)],t.map(e=>H(`mdta`,[...n.encode(e.key)]))),H(`ilst`,void 0,t.map((e,t)=>H(String.fromCharCode(...L(t+1)),void 0,[e.value])))])},J=e=>H(`data`,[L(1),L(0),...n.encode(e)]),Yn=(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}},Xn={avc:on,hevc:sn,vp8:cn,vp9:cn,av1:ln,prores:null},Zn=(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`}},Qn=(e,t)=>{switch(e){case`aac`:return dn;case`mp3`:return dn;case`opus`:return mn;case`vorbis`:return dn;case`flac`:return hn;case`ac3`:return gn;case`eac3`:return _n;case`dts`:return vn}if(t)switch(e){case`pcm-s24`:return G;case`pcm-s24be`:return G;case`pcm-s32`:return G;case`pcm-s32be`:return G;case`pcm-f32`:return G;case`pcm-f32be`:return G;case`pcm-f64`:return G;case`pcm-f64be`:return G}else switch(e){case`pcm-s16`:return K;case`pcm-s16be`:return K;case`pcm-s24`:return K;case`pcm-s24be`:return K;case`pcm-s32`:return K;case`pcm-s32be`:return K;case`pcm-f32`:return K;case`pcm-f32be`:return K;case`pcm-f64`:return K;case`pcm-f64be`:return K}return null},$n={webvtt:`wvtt`},er={webvtt:bn},tr=e=>{D(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},nr=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){D(!this.started),this.target._start(),this.started=!0}write(e){D(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return D(this.started&&!this.finalized),this.target._flush()}async finalize(){D(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};ge();var Y=class extends Ve{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 or(this,e)}},rr=2**16,ir=2**32,ar=class extends Y{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);if(this._options=e,this._supportsResize=`resize`in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(rr,{maxByteLength:ir})}catch{this._buffer=new ArrayBuffer(rr),this._supportsResize=!1}else this._buffer=new ArrayBuffer(rr);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>ir)throw Error(`ArrayBuffer exceeded maximum size of ${ir} 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)}},or=class extends Y{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit(`finalized`)}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}},sr=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},X=57600,cr=2082844800,lr=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},ur=class extends xt{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new ar,this.auxWriter=new nr(this.auxTarget,!1),this.auxBoxWriter=new wt(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=le(),this.creationTime=Math.floor(Date.now()/1e3)+cr,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 Ar,this.isCmaf=t instanceof kr,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof kr?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 ar:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new wt(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof ar&&`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 nr(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new wt(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(D(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Pt({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(D(this.writer),D(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Lt(!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,n){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;u(n,e.source._codec),D(n),D(n.decoderConfig);let a={...n.decoderConfig};D(a.codedWidth!==void 0),D(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=nt(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=_(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=r(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=We(e),o=!0}let s=Le(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,d=c===void 0||l===void 0?{num:1,den:1}:Fe({num:c*a.codedHeight,den:l*a.codedWidth}),f=a.codec===`ap4h`||a.codec===`ap4x`,p={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:d,decoderConfig:a,requiresAnnexBTransformation:o,hasAlphaChannel:f},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(p),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ee(n,e.source._codec),D(n),D(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(Re.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;ie(t),D(t),D(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,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(Re.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=y(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=y(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;){let n=new Set([]);for(let r of e.cueQueue)D(r.timestamp<=t),D(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=Bn();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;St.lastIndex=0;let r=St.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=Hn(n.notes);this.auxBoxWriter.writeBox(e)}let c=Vn(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=x(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??=n[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){D(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(D(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=x(e.timeToSampleTable);if(D(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=x(e.compositionTimeOffsetTable);D(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,D(e.lastSample),D(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){D(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(D(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),D(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(D(!this.isFragmented),D(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||x(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)D(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(D(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(D(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;D(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){D(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new wt(this.writer);let e=this.boxWriter.measureBox(Ft()),t=this.boxWriter.measureBox(It(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}D(this.writer),D(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=An(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];n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e;for(let e of n.currentChunk.samples)o+=e.size;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=An(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}D(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=Lt(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){D(this.writer),D(this.boxWriter),this.ensureOneEnabledTrack();let e=W(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;D(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Lt(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){D(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;D(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){D(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)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(D(this.writer),D(this.boxWriter),this.fastStart===`in-memory`){this.mdat=Lt(!1);let e;for(let t=0;t<2;t++){let t=W(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)D(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=W(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)D(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(Ft()),this.boxWriter.writeBox(It(this,e))}else{let e=this.writer.getPos(),t=Ln(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{D(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);D(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=W(this);if(this.fastStart===`reserve`){D(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Rt(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()}},dr=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(){D(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>t[n*e+r]*+(r<2):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()),D(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor((i-1/this.sourceSampleRate)*this.targetSampleRate)+1,s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;D(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;D(this.startTime!==null);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new E({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()}},fr=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},pr=(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}),mr=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})()}},hr=class extends mr{constructor(e){if(super(),this._connectedTrack=null,!S.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${S.join(`, `)}.`);this._codec=e}},gr=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},_r=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`&&(D(this.outputWidth),D(this.outputHeight),D(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,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(j(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let i=[];try{for(let n of t)n instanceof O?i.push(n):typeof VideoFrame<`u`&&n instanceof VideoFrame?i.push(new O(n)):i.push(new O(n,{timestamp:e.timestamp,duration:e.duration}))}catch(n){for(let t of i)t!==e&&t.close();for(let n of t)(n instanceof O&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw n}r=i}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),D(this.encoderInitialized),this.closed)break;let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...this.defaultEncodeOptions,...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{D(this.encoder);let t=e.toVideoFrame(),n=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 yr;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n);try{this.encoder.encode(e,a)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;D(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r={stack:[],error:void 0,hasError:!1};try{let i=fr(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{pr(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=yt(this.encodingConfig.quality,this.encodingConfig.bitrate);D(t!==void 0);let n=st({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),r=null,i;for(let e of n){let t=e.config;if(this.encodingConfig.onEncoderConfig?.(t),i=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($e(`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=ht(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 C))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.`);gr(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=C.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=se(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})),gr(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();D(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(D(s!==void 0),i(s.chunk,a,s.meta),n++;t.length>0&&t[0]===n;){t.shift();let n=e.shift();D(n!==void 0),i(n.chunk,null,n.meta)}},error:e=>{e.stack=o,this.setError(e)}}),this.alphaEncoder.configure(a)}}D(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 te(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}},vr=null,yr=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!vr){let e=new Blob([`(${br.toString()})()`],{type:`application/javascript`});vr=URL.createObjectURL(e)}this.worker=new Worker(vr),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=le();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()}},br=()=>{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 ee=m,te=a?512:o?2048:128;s===1?y.fill(te,ee):new Uint16Array(y.buffer,ee,2*_).fill(te);let ne=a?`I420P10`:o?`I420P12`:`I420`,re=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),ie={format:ne,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,transfer:[y.buffer]};return{colorFrame:re,alphaFrame:new VideoFrame(y,ie)}}},xr=class extends hr{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.`);at(t),super(t.codec),this._encoder=new _r(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw TypeError(`timestamp must be a non-negative number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new O(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Sr=class extends mr{constructor(e){if(super(),this._connectedTrack=null,!A.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${A.join(`, `)}.`);this._codec=e}},Cr=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 dr({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(j(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof E))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 E&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),D(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new E({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{D(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){D(this.outputSampleSize),D(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.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 C(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=yt(this.encodingConfig.quality,this.encodingConfig.bitrate),a=ut({numberOfChannels:t,sampleRate:n,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(a);let o=qe.find(e=>e.supports(this.encodingConfig.codec,a));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof C))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($e(`AudioEncoder`));let e;try{e=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.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(b(t.decoderConfig.description)).objectType===0,e){let e=Number(x(a.codec.split(`.`)));t.decoderConfig.description=pe({objectType:e,outputNumberOfChannels:t.decoderConfig.numberOfChannels,outputSampleRate:t.decoderConfig.sampleRate})}}let n=C.fromEncodedChunk(e);n=n.clone({timestamp:l(n.timestamp,a.sampleRate),duration:e.duration==null?void 0:l(n.duration,a.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(a)}D(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=y(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,T((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,T(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,Be(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=T(Math.floor(n*32767),-32768,32767);e.setUint8(t,ve(r))}:D(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,T((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,T(Math.round(n*32767),-32768,32767),r):D(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>re(e,t,T((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>s(e,t,T(Math.round(n*8388607),-8388608,8388607),r):D(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,T((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,T(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):D(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):D(!1);break;default:Xe(n),D(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},wr=class extends Sr{constructor(e){ct(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Cr(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=E._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)}},Tr=class extends mr{constructor(e){if(super(),this._connectedTrack=null,!k.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${k.join(`, `)}.`);this._codec=e}},Er=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>S.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>A.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>k.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Dr=class extends Er{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&&(!Qe(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}_createMuxer(e){return new ur(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Or=class extends Dr{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ce,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...k]}_codecUnsupportedHint(e){return new Ar().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},kr=class extends Dr{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...S,...ce,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...k]}},Ar=class extends Dr{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...S,...A]}_codecUnsupportedHint(e){return new Or().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},jr=[`video`,`audio`,`subtitle`],Mr=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=Ne(this.metadata.group),r=Ne(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}},Nr=class extends Mr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Pr=class extends Mr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Fr=class extends Mr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Ir=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)}},Lr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!_e(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&&Ye(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 Ir)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Ir))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},Rr=class extends Ve{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(j(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Ir,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Ke,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 Er))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof sr))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Y&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Y)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Y&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){D(this._target instanceof sr);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return j(t)?t.then(n):n(t)}async _getTarget(e){D(this._target instanceof sr);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(D(this._initTarget!==null),this._initTarget instanceof Y)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Y)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return j(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new nr(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof hr))throw TypeError(`source must be a VideoSource.`);if(Lr(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 C))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 Nr(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Sr))throw TypeError(`source must be an AudioSource.`);if(Lr(t),t.decoderConfig!==void 0&&ee({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof C))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))}addSubtitleTrack(e,t={}){if(!(e instanceof Tr))throw TypeError(`source must be a SubtitleSource.`);Lr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Fr(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 jr)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 jr){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?(ze._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 ze._warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&ze._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?(ze._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()}})()}},zr=h,Br=[{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 Vr(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=Br.find(s),l=Br.find(e=>s(e)&&o*r<=e.maxMacroblocksPerSecond&&Math.max(i,a)<=Math.sqrt(e.maxMacroblocks*8))??Br[Br.length-1];if(c&&l!==c)return`avc1.6400${l.levelIdc.toString(16).padStart(2,`0`)}`}function Hr(){try{if(typeof DOMException<`u`)return new DOMException(`The operation was aborted.`,`AbortError`);throw Error(`DOMException is not available`)}catch{let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}}function Q(e){return!!e&&typeof e==`object`&&`name`in e&&e.name===`AbortError`}function $(e){if(e?.aborted)throw Hr()}function Ur(e){return Math.round(e/2)*2}function Wr(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function Gr(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 Kr(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:Ur(t),height:Ur(n)}}function qr(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 Jr(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 Yr(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 Xr(e,t){let n=d(),r=n.sceneCanvas._canvas;if(r.width=e.width*t,r.height=e.height*t,r.width<=0||r.height<=0)throw zr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}async function Zr(e,t){let n=new Rr({target:new ar,format:new Or}),{width:r,height:i}=e,a=null,o;for(let e of n.format.getSupportedVideoCodecs()){let n=Vr(e,r,i,t);if(await _t(e,{width:r,height:i,quality:gt,fullCodecString:n})){a=e,o=n;break}}if(!a)throw zr(`VIDEO_FAILED`,`Your browser doesn't support video encoding.`,{reason:`no-encoder`});let s=new xr(e,{codec:a,quality:gt,fullCodecString:o});return n.addVideoTrack(s,{frameRate:t}),{output:n,canvasSource:s}}async function Qr(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=qr(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 bt(s,{numberOfChannels:2,sampleRate:44100,quality:gt});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 wr({codec:c,quality:gt});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function $r(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 ei(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function ti(e,t,n,r,i,a,o,s,c){let l=1e3/a,u=Math.floor(i/1e3*a)||1,d=e.timingPreview;e.setTimingPreview(`playhead`);try{$(c),e.setElementsPixelRatio(o);let d=-1,f=0;for(let p=0;p<u;p++){$(c);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=$r(_,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),d=v),await ei(e,_,v,o,n),$(c),await t.add(h,g),s){let e=Date.now();if(p===u-1||e-f>=300){let t=e-m;s((p+1)/u*.95,t),f=e}}}}finally{e.pages.forEach(e=>{e.set({_rendering:!1})}),e.setCurrentTime(0),e.setTimingPreview(d)}}async function ni(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw zr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function ri(e,t){return e.decodeAudioData(t)}function ii(e){return e.startsWith(`data:`)}function ai(e){return e.startsWith(`file://`)}function oi(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function si(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 ci(e,t){try{if(oi(e))return new Ge({source:new Ee(e),formats:Ie});if(ii(e)){let t=si(e);return new Ge({source:new Oe(t),formats:Ie})}if(ai(e)){let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new Ge({source:new Oe(n),formats:Ie})}{let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new Ge({source:new Oe(n),formats:Ie})}}catch(n){return Q(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function li(e,t){try{$(t);let n=await ci(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(),Hr();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if(Q(n))throw n;if(t?.aborted)throw Hr();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function ui(e,t){let n=e.audios||[],r=qr(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:ni(e.src,t).catch(n=>(Q(n)||t?.aborted||console.error(`Failed to download audio ${e.src}:`,n),null))})),videoAudios:r.map(e=>({video:e,inputPromise:li(e.src,t).catch(e=>{if(Q(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function di(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 fi(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=ae(e.animations,e.pageDuration),s=(o-a)/1e3,c=Math.max(0,(e.pageStartTime+a)/1e3),l=Math.max(0,r),u=Math.min(i,t.duration-l);if(u<=0||s<=0||l>=t.duration)return;let d=n.offlineContext.createBufferSource();d.buffer=t,d.playbackRate.value=e.speed,d.loop=!0,d.loopStart=l,d.loopEnd=l+u;let f=n.offlineContext.createGain();f.gain.value=e.volume,d.connect(f),f.connect(n.offlineContext.destination),d.start(c,l),d.stop(c+s)}async function pi(e,t,n,r,i,a,o){$(o);let s=i||ui(e,o);if(s.storeAudios.length+s.videoAudios.length===0)return;let c=44100,l=typeof r==`string`?r:typeof r?.codec==`string`?r.codec:void 0,u=l?.includes(`opus`)?960:1024,d=l===`aac`?3:l?.includes(`opus`)?2:0,f=Math.floor(n/1e3*c),p=Math.floor(f/u)*u,m=d*u,h=Math.max(u,p-m),g=new OfflineAudioContext(2,h,c),_={offlineContext:g,sampleRate:c,totalDuration:n};a?.(.95);let[v,y]=await Promise.all([Promise.all(s.storeAudios.map(async({audio:e,bufferPromise:t})=>{try{$(o);let n=await t;return $(o),n?{audio:e,audioBuffer:await ri(g,n)}:null}catch(t){if(Q(t))throw t;return console.error(`Failed to process audio ${e.src}:`,t),null}})),Promise.all(s.videoAudios.map(async({video:e,inputPromise:t})=>{try{$(o);let{hasAudio:n,input:r}=await t;if($(o),!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),s.push(e.buffer);if(r.dispose(),$(o),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(Q(t))throw t;return console.error(`Failed to extract video audio ${e.src}:`,t),null}}))]);a?.(.97),$(o);for(let e of v)e&&di(e.audio,e.audioBuffer,_);for(let e of y)e&&fi(e.video,e.audioBuffer,_);$(o);let b=await g.startRendering();a?.(.99),$(o),await t.add(b)}async function mi({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){let o=Kr(e),s=Jr(e,o),c=null,l=null,u=null,d=null,f=!1;if(a){$(a);let e=()=>{try{l?.close()}catch{}try{u?.close()}catch{}c?.cancel().catch(()=>{})};a.addEventListener(`abort`,e,{once:!0}),d=()=>a.removeEventListener(`abort`,e)}try{$(a);let s=Wr(e);if(s===0)throw zr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let d=Gr(e),{canvas:p,canvases:m}=Xr(o,n),h=await Zr(p,t);c=h.output,l=h.canvasSource;let g=await Qr(c,e,i);u=g.audioBufferSource||null;let _=g.audioCodec;$(a),await c.start(),await ti(e,l,m,d,s,t,n,r,a),l.close();let v=u?ui(e,a):null;u&&v&&(await pi(e,u,s,_,v,r,a),u.close()),$(a),await c.finalize();let y=c.target,b=new Blob([y.buffer],{type:c.format.mimeType});return f=!0,b}catch(e){throw Q(e)?e:a?.aborted?Hr():e}finally{if(d?.(),!f&&c)try{await c.cancel()}catch{}Yr(e,s)}}export{mi 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),ce=w(String.prototype.replace),le=w(String.prototype.indexOf),ue=w(String.prototype.trim),de=w(Number.prototype.toString),fe=w(Boolean.prototype.toString),v=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=T(TypeError);function w(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return h(e,t,n)}}function T(e){return function(){return ee(e,[...arguments])}}function E(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 D(e){for(let t=0;t<e.length;t++)b(e,t)||(e[t]=null);return e}function O(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)?D(o):o&&typeof o==`object`&&o.constructor===Object?O(o):o)}return t}function pe(e){switch(typeof e){case`string`:return e;case`number`:return de(e);case`boolean`:return fe(e);case`bigint`:return v?v(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=k(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 k(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 me(e){try{return S(e,``),!0}catch{return!1}}var he=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(`.`)),ge=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(`.`)),_e=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`]),ve=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`]),ye=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(`.`)),be=d([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),xe=d([`#text`]),Se=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(`.`)),Ce=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(`.`)),we=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(`.`)),Te=d([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Ee=f(/{{[\w\W]*|^[\w\W]*}}/g),De=f(/<%[\w\W]*|^[\w\W]*%>/g),Oe=f(/\${[\w\W]*/g),ke=f(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ae=f(/^aria-[\-\w]+$/),je=f(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Me=f(/^(?:\w+script|data):/i),Ne=f(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Pe=f(/^html$/i),Fe=f(/^[a-z][.\w]*(-[.\w]+)+$/i),Ie=f(/<[/\w!]/g),Le=f(/<[/\w]/g),Re=f(/<\/no(script|embed|frames)/i),ze=f(/\/>/i),A={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},j=[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`],Be=d(E({},j)),Ve=function(){let e={};return g(j,t=>{e[t]=f(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),d(e)}(),He=function(){return typeof window>`u`?null:window},Ue=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}},We=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},M=function(e,t,n,r){return b(e,t)&&_(e[t])?E(r.base?O(r.base):{},e[t],r.transform):n},Ge=function(e,t,n){let r=b(e,t)?e[t]:void 0;return r&&typeof r==`object`?O(r):n()};function Ke(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:He(),t=e=>Ke(e);if(t.version=`3.4.14`,t.removed=[],!e||!e.document||e.document.nodeType!==A.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=k(h,`cloneNode`),de=k(h,`remove`),fe=k(h,`nextSibling`),v=k(h,`childNodes`),y=k(h,`parentNode`),x=k(h,`shadowRoot`),w=k(h,`attributes`),T=s&&s.prototype?k(s.prototype,`nodeType`):null,D=s&&s.prototype?k(s.prototype,`nodeName`):null,j=s&&s.prototype?k(s.prototype,`ownerDocument`):null,qe=function(e){return T?T(e):e.nodeType},Je=function(e){return D?D(e):e.nodeName};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let N,P=``,Ye,Xe=!1,Ze=0,Qe=function(){if(Ze>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.`)},F=function(e){Qe(),Ze++;try{return N.createHTML(e)}finally{Ze--}},$e=function(e){Qe(),Ze++;try{return N.createScriptURL(e)}finally{Ze--}},et=function(){return Xe||=(Ye=Ue(m,i),!0),Ye},tt=n,nt=tt.implementation,rt=tt.createNodeIterator,it=tt.createDocumentFragment,at=tt.getElementsByTagName,ot=r.importNode,I=We();t.isSupported=typeof o==`function`&&typeof y==`function`&&nt&&nt.createHTMLDocument!==void 0;let st=Ee,ct=De,lt=Oe,ut=ke,dt=Ae,ft=Me,pt=Ne,mt=Fe,ht=je,L=null,gt=E({},[...he,...ge,..._e,...ye,...xe]),R=null,_t=E({},[...Se,...Ce,...we,...Te]),z=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}})),vt=null,yt=null,B=Object.seal(p(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),bt=!0,xt=!0,St=!1,Ct=!0,V=!1,H=!0,U=!1,wt=!1,Tt=null,Et=null,Dt=!1,W=!1,Ot=!1,kt=!1,At=!0,jt=!1,Mt=`user-content-`,Nt=!0,Pt=!1,G={},K=null,Ft=E({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),It=null,Lt=E({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Rt=null,zt=E({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Bt=`http://www.w3.org/1998/Math/MathML`,Vt=`http://www.w3.org/2000/svg`,q=`http://www.w3.org/1999/xhtml`,J=q,Ht=!1,Ut=null,Wt=E({},[Bt,Vt,q],oe),Gt=d([`mi`,`mo`,`mn`,`ms`,`mtext`]),Kt=E({},Gt),qt=d([`annotation-xml`]),Jt=E({},qt),Yt=E({},[`title`,`style`,`font`,`a`,`script`]),Xt=null,Zt=[`application/xhtml+xml`,`text/html`],Y=null,X=null,Qt=n.createElement(`form`),$t=function(e){return e instanceof RegExp||e instanceof Function},en=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(X&&X===e)return;(!e||typeof e!=`object`)&&(e={}),e=O(e),Xt=Zt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Y=Xt===`application/xhtml+xml`?oe:ae,L=M(e,`ALLOWED_TAGS`,gt,{transform:Y}),R=M(e,`ALLOWED_ATTR`,_t,{transform:Y}),Ut=M(e,`ALLOWED_NAMESPACES`,Wt,{transform:oe}),Rt=M(e,`ADD_URI_SAFE_ATTR`,zt,{transform:Y,base:zt}),It=M(e,`ADD_DATA_URI_TAGS`,Lt,{transform:Y,base:Lt}),K=M(e,`FORBID_CONTENTS`,Ft,{transform:Y}),vt=M(e,`FORBID_TAGS`,O({}),{transform:Y}),yt=M(e,`FORBID_ATTR`,O({}),{transform:Y}),G=b(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?O(e.USE_PROFILES):e.USE_PROFILES:!1,bt=e.ALLOW_ARIA_ATTR!==!1,xt=e.ALLOW_DATA_ATTR!==!1,St=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ct=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,H=e.SAFE_FOR_XML!==!1,U=e.WHOLE_DOCUMENT||!1,W=e.RETURN_DOM||!1,Ot=e.RETURN_DOM_FRAGMENT||!1,kt=e.RETURN_TRUSTED_TYPE||!1,Dt=e.FORCE_BODY||!1,At=e.SANITIZE_DOM!==!1,jt=e.SANITIZE_NAMED_PROPS||!1,Nt=e.KEEP_CONTENT!==!1,Pt=e.IN_PLACE||!1,ht=me(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:je,J=typeof e.NAMESPACE==`string`?e.NAMESPACE:q,Kt=Ge(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>E({},Gt)),Jt=Ge(e,`HTML_INTEGRATION_POINTS`,()=>E({},qt));let t=Ge(e,`CUSTOM_ELEMENT_HANDLING`,()=>p(null));if(z=p(null),b(t,`tagNameCheck`)&&$t(t.tagNameCheck)&&(z.tagNameCheck=t.tagNameCheck),b(t,`attributeNameCheck`)&&$t(t.attributeNameCheck)&&(z.attributeNameCheck=t.attributeNameCheck),b(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(z.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),f(z),V&&(xt=!1),Ot&&(W=!0),G&&(L=E({},xe),R=p(null),G.html===!0&&(E(L,he),E(R,Se)),G.svg===!0&&(E(L,ge),E(R,Ce),E(R,Te)),G.svgFilters===!0&&(E(L,_e),E(R,Ce),E(R,Te)),G.mathMl===!0&&(E(L,ye),E(R,we),E(R,Te))),B.tagCheck=null,B.attributeCheck=null,b(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?B.tagCheck=e.ADD_TAGS:_(e.ADD_TAGS)&&(L===gt&&(L=O(L)),E(L,e.ADD_TAGS,Y))),b(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?B.attributeCheck=e.ADD_ATTR:_(e.ADD_ATTR)&&(R===_t&&(R=O(R)),E(R,e.ADD_ATTR,Y))),b(e,`ADD_FORBID_CONTENTS`)&&_(e.ADD_FORBID_CONTENTS)&&(K===Ft&&(K=O(K)),E(K,e.ADD_FORBID_CONTENTS,Y)),Nt&&(L[`#text`]=!0),U&&E(L,[`html`,`head`,`body`]),L.table&&(E(L,[`tbody`]),delete vt.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=N;N=e.TRUSTED_TYPES_POLICY;try{P=F(``)}catch(e){throw N=t,e}}else e.TRUSTED_TYPES_POLICY===null?(N=void 0,P=``):(N===void 0&&(N=et()),N&&typeof P==`string`&&(P=F(``)));d&&d(e),X=e},tn=E({},[...ge,..._e,...ve]),nn=E({},[...ye,...be]),rn=function(e,t,n){return t.namespaceURI===q?e===`svg`:t.namespaceURI===Bt?e===`svg`&&(n===`annotation-xml`||Kt[n]):!!tn[e]},an=function(e,t,n){return t.namespaceURI===q?e===`math`:t.namespaceURI===Vt?e===`math`&&Jt[n]:!!nn[e]},on=function(e,t,n){return t.namespaceURI===Vt&&!Jt[n]||t.namespaceURI===Bt&&!Kt[n]?!1:!nn[e]&&(Yt[e]||!tn[e])},sn=function(e){let t=y(e);(!t||!t.tagName)&&(t={namespaceURI:J,tagName:`template`});let n=ae(e.tagName),r=ae(t.tagName);return Ut[e.namespaceURI]?e.namespaceURI===Vt?rn(n,t,r):e.namespaceURI===Bt?an(n,t,r):e.namespaceURI===q?on(n,t,r):!!(Xt===`application/xhtml+xml`&&Ut[e.namespaceURI]):!1},Z=function(e){re(t.removed,{element:e});try{y(e).removeChild(e)}catch{if(de(e),!y(e))throw C(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},cn=function(e,t,n){try{e.removeAttributeNode(t)}catch{try{e.removeAttribute(n)}catch{}}},ln=function(e){dn(e);let t=v(e);if(t){let e=[];g(t,t=>{re(e,t)}),g(e,e=>{try{de(e)}catch{}})}let n=w(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&cn(e,r,i)}},Q=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}re(t.removed,{attribute:r||null,from:n});try{r?n.removeAttributeNode(r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(W||Ot)try{Z(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},un=function(e){let t=w(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||R[Y(i)]||cn(e,r,i)}},dn=function(e){let t=[e];for(;t.length>0;){let e=t.pop();qe(e)===A.element&&un(e);let n=v(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},fn=function(e,t){return H?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},pn=function(e){if(!H)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=qe(e);if(n===A.processingInstruction||n===A.comment&&S(Le,e.data)){try{de(e)}catch{}continue}if(n===A.element){let t=e,n=Y(Je(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&fn(`for`,n)&&t.removeAttribute(`for`)}catch{}}let r=v(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},mn=function(e){let t=null,r=null;if(Dt)e=`<remove></remove>`+e;else{let t=se(e,/^[\r\n\t ]+/);r=t&&t[0]}Xt===`application/xhtml+xml`&&J===q&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=N?F(e):e;if(J===q)try{t=new u().parseFromString(i,Xt)}catch{}if(!t||!t.documentElement){t=nt.createDocument(J,`template`,null);try{t.documentElement.innerHTML=Ht?P:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),J===q?at.call(t,U?`html`:`body`)[0]:U?t.documentElement:a},hn=function(e){let t=j?j(e):e.ownerDocument;return rt.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},gn=function(e){return e=ce(e,st,` `),e=ce(e,ct,` `),e=ce(e,lt,` `),e},_n=function(e){e.normalize();let t=j?j(e):e.ownerDocument,n=rt.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=gn(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&g(i,e=>{yn(e.content)&&_n(e.content)})},vn=function(e){let t=D?D(e):null;return typeof t!=`string`||Y(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==w(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==T(e)||e.childNodes!==v(e)},yn=function(e){if(!T||typeof e!=`object`||!e)return!1;try{return T(e)===A.documentFragment}catch{return!1}},bn=function(e){if(!T||typeof e!=`object`||!e)return!1;try{return typeof T(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&g(e,e=>{e.call(t,n,r,X)})}let xn=function(e,t){return!!(H&&e.hasChildNodes()&&!bn(e.firstElementChild)&&S(Ie,e.textContent)&&S(Ie,e.innerHTML)||H&&e.namespaceURI===q&&Be[t]&&(bn(e.firstElementChild)||typeof e.textContent==`string`&&S(Ve[t],e.textContent))||e.nodeType===A.processingInstruction||H&&e.nodeType===A.comment&&S(Le,e.data))},Sn=function(e,t){return e instanceof RegExp?S(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},Cn=function(e,t,n){if(!vt[t]&&kn(t)&&Sn(z.tagNameCheck,t))return!1;if(Nt&&!K[t]){let t=y(e),r=v(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,fe(e))}}}return Z(e),!0},wn=function(e,t,n,r){return e.length===0?t:t===n||t===r?O(t):t},Tn=function(e,t){return e===t||y(e)!==null?!1:(Pt&&dn(e),!0)},En=function(e,n){if($(I.beforeSanitizeElements,e,null),Tn(e,n))return!0;if(vn(e))return Z(e),!0;let r=Y(Je(e));if(L=wn(I.uponSanitizeElement,L,gt,Tt),$(I.uponSanitizeElement,e,{tagName:r,allowedTags:L}),Tn(e,n))return!0;if(xn(e,r))return Z(e),!0;if(vt[r]||!(B.tagCheck instanceof Function&&B.tagCheck(r))&&!L[r]){let t=Cn(e,r,n);return t===!1&&$(I.afterSanitizeElements,e,null),t}if(qe(e)===A.element&&!sn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&S(Re,e.innerHTML))return Z(e),!0;if(V&&e.nodeType===A.text){let n=gn(e.textContent);e.textContent!==n&&(re(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(I.afterSanitizeElements,e,null),!1},Dn=function(e,t,r){if(yt[t]||fn(t,e)||At&&(t===`id`||t===`name`)&&(r in n||r in Qt))return!1;let i=R[t]||B.attributeCheck instanceof Function&&B.attributeCheck(t,e);return xt&&S(ut,t)||bt&&S(dt,t)?!0:i?Rt[t]||S(ht,ce(r,pt,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&le(r,`data:`)===0&&It[e]||St&&!S(ft,ce(r,pt,``))?!0:!r:kn(e)&&Sn(z.tagNameCheck,e)&&Sn(z.attributeNameCheck,t,e)||t===`is`&&z.allowCustomizedBuiltInElements&&Sn(z.tagNameCheck,r)},On=E({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),kn=function(e){return!On[ae(e)]&&S(mt,e)},An=function(e,t,n,r){if(N&&typeof m==`object`&&typeof m.getAttributeType==`function`&&!n)switch(m.getAttributeType(e,t)){case`TrustedHTML`:return F(r);case`TrustedScriptURL`:return $e(r)}return r},jn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),vn(e)?Z(e):ne(t.removed)}catch{Q(n,e)}},Mn=function(e){$(I.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||vn(e))return;R=wn(I.uponSanitizeAttribute,R,_t,Et);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:R,forceKeepAttr:void 0},r=t.length,i=Y(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=Y(o),u=c,d=o===`value`?u:ue(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(I.uponSanitizeAttribute,e,n),d=n.attrValue,jt&&(l===`id`||l===`name`)&&le(d,Mt)!==0&&(Q(o,e,a),d=Mt+d),H&&S(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Q(o,e,a);continue}if(l===`attributename`&&se(d,`href`)){Q(o,e,a);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Q(o,e,a);continue}if(!Ct&&S(ze,d)){Q(o,e,a);continue}if(V&&(d=gn(d)),!Dn(i,l,d)){Q(o,e,a);continue}d=An(i,l,s,d),d!==u&&jn(e,o,s,d)}}$(I.afterSanitizeAttributes,e,null)},Nn=function(e){let t=null,n=hn(e);for($(I.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(I.uponSanitizeShadowNode,t,null),En(t,e),Mn(t),yn(t.content)&&Nn(t.content),qe(t)===A.element){let e=x(t);yn(e)&&(Pn(e),Nn(e))}$(I.afterSanitizeShadowDOM,e,null)},Pn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Nn(e.shadow);continue}let n=e.node,r=qe(n)===A.element,i=v(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=D?D(n):null;if(typeof e==`string`&&Y(e)===`template`){let e=n.content;yn(e)&&t.push({node:e,shadow:null})}}if(r){let e=x(n);yn(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(Ht=!e,Ht&&(e=`<!-->`),typeof e!=`string`&&!bn(e)&&(e=pe(e),typeof e!=`string`))throw C(`dirty is not a string, aborting`);if(!t.isSupported)return e;wt?(L=Tt,R=Et):en(n),(I.uponSanitizeElement.length>0||I.uponSanitizeAttribute.length>0)&&(L=O(L)),I.uponSanitizeAttribute.length>0&&(R=O(R)),t.removed=[];let c=Pt&&typeof e!=`string`&&bn(e);if(c){pn(e);let t=Je(e);if(typeof t==`string`){let n=Y(t);if(!L[n]||vt[n])throw ln(e),C(`root node is forbidden and cannot be sanitized in-place`)}if(vn(e))throw ln(e),C(`root node is clobbered and cannot be sanitized in-place`);try{Pn(e)}catch(t){throw ln(e),t}}else if(bn(e))i=mn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===A.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Pn(a);else{if(!W&&!V&&!U&&e.indexOf(`<`)===-1)return N&&kt?F(e):e;if(i=mn(e),!i)return W?null:kt?P:``}i&&Dt&&Z(i.firstChild);let l=c?e:i;try{let e=hn(l);for(;o=e.nextNode();)En(o,l),Mn(o),yn(o.content)&&Nn(o.content)}catch(n){throw c&&(ln(e),g(t.removed,e=>{e.element&&dn(e.element)})),n}if(c)return g(t.removed,e=>{e.element&&dn(e.element)}),V&&_n(e),e;if(W){if(V&&_n(i),Ot)for(s=it.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(R.shadowroot||R.shadowrootmode)&&(s=ot.call(r,s,!0)),s}let u=U?i.outerHTML:i.innerHTML;return U&&L[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&S(Pe,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
3
|
+
`+u),V&&(u=gn(u)),N&&kt?F(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};en(e),wt=!0,Tt=L,Et=R},t.clearConfig=function(){X=null,wt=!1,Tt=null,Et=null,N=Ye,P=``},t.isValidAttribute=function(e,t,n){X||en({});let r=Y(e),i=Y(t);return Dn(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&b(I,e)&&re(I[e],t)},t.removeHook=function(e,t){if(b(I,e)){if(t!==void 0){let n=te(I[e],t);return n===-1?void 0:ie(I[e],n,1)[0]}return ne(I[e])}},t.removeHooks=function(e){b(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=We()},t}var qe=Ke();export{qe as default};
|
package/dist/index.html
CHANGED
|
@@ -8,10 +8,8 @@
|
|
|
8
8
|
}
|
|
9
9
|
</style>
|
|
10
10
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
11
|
-
<script type="module" crossorigin src="./assets/index-
|
|
11
|
+
<script type="module" crossorigin src="./assets/index-Bc1WTi4k.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-hePW80VL.js">
|
|
13
|
-
<link rel="modulepreload" crossorigin href="./assets/id3-B1cFGCGS.js">
|
|
14
|
-
<link rel="modulepreload" crossorigin href="./assets/preload-helper-HclGiUj8.js">
|
|
15
13
|
</head>
|
|
16
14
|
<body>
|
|
17
15
|
<div id="root"></div>
|
package/lib/instance.js
CHANGED
|
@@ -11,6 +11,7 @@ import * as fontCache from './font-cache.js';
|
|
|
11
11
|
import * as localMedia from './local-media.js';
|
|
12
12
|
import { polotnoError, rehydrateError } from './errors.js';
|
|
13
13
|
import { assertUrlAllowed } from './ssrf-guard.js';
|
|
14
|
+
import { isRetryableStatus, withRetry } from '@polotno/core/retry';
|
|
14
15
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
15
16
|
// Compiled to lib/instance.js; the client bundle is published to ../dist.
|
|
16
17
|
const DEFAULT_CLIENT = `file:${path.join(__dirname, '..', 'dist', 'index.html')}`;
|
|
@@ -178,11 +179,11 @@ export const guessExtension = (contentType, kind) => {
|
|
|
178
179
|
// address. `redirect: 'manual'` hands us each 3xx so we can validate its
|
|
179
180
|
// Location before chasing it.
|
|
180
181
|
const MAX_REDIRECTS = 5;
|
|
181
|
-
const guardedFetch = async (startUrl, policy) => {
|
|
182
|
+
const guardedFetch = async (startUrl, policy, signal) => {
|
|
182
183
|
let url = startUrl;
|
|
183
184
|
for (let hop = 0;; hop++) {
|
|
184
185
|
await assertUrlAllowed(url, policy);
|
|
185
|
-
const res = await fetch(url, { redirect: 'manual' });
|
|
186
|
+
const res = await fetch(url, { redirect: 'manual', signal });
|
|
186
187
|
if (res.status >= 300 && res.status < 400) {
|
|
187
188
|
const location = res.headers.get('location');
|
|
188
189
|
if (!location)
|
|
@@ -198,61 +199,92 @@ const guardedFetch = async (startUrl, policy) => {
|
|
|
198
199
|
return res;
|
|
199
200
|
}
|
|
200
201
|
};
|
|
202
|
+
// A media download only gets a deadline up to the RESPONSE HEADERS. The body
|
|
203
|
+
// can legitimately be a hundred megabytes of video on a slow link, and there is
|
|
204
|
+
// no way to tell that from a stalled socket — capping the whole transfer would
|
|
205
|
+
// start failing exports that work today. A connect/TTFB that never arrives is
|
|
206
|
+
// unambiguous, so that is what this bounds.
|
|
207
|
+
const HEADERS_TIMEOUT_MS = 30000;
|
|
201
208
|
const downloadUrlToFile = async (urlString, destinationPath, policy = {}) => {
|
|
202
209
|
if (typeof fetch !== 'function') {
|
|
203
210
|
throw polotnoError('FETCH_FAILED', 'Global fetch API is not available in this Node.js runtime. Please use Node 18+.', { url: urlString });
|
|
204
211
|
}
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
212
|
+
let attempts = 0;
|
|
213
|
+
const attemptDownload = async (attempt) => {
|
|
214
|
+
attempts = attempt;
|
|
215
|
+
// Ensure no partial file exists from a previous attempt
|
|
216
|
+
await fs.promises.rm(destinationPath, { force: true });
|
|
217
|
+
const controller = new AbortController();
|
|
218
|
+
const timeoutId = setTimeout(() => controller.abort(), HEADERS_TIMEOUT_MS);
|
|
219
|
+
let res;
|
|
209
220
|
try {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
// ignore
|
|
221
|
+
res = await guardedFetch(urlString, policy, controller.signal);
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
// Cleared before the body streams — see HEADERS_TIMEOUT_MS.
|
|
225
|
+
clearTimeout(timeoutId);
|
|
226
|
+
}
|
|
227
|
+
if (!res.ok) {
|
|
228
|
+
// Best-effort read of error body (small) for debugging.
|
|
229
|
+
let bodyPreview = '';
|
|
230
|
+
try {
|
|
231
|
+
bodyPreview = await res.text();
|
|
232
|
+
if (bodyPreview.length > 500) {
|
|
233
|
+
bodyPreview = bodyPreview.slice(0, 500) + '...';
|
|
224
234
|
}
|
|
225
|
-
const details = [
|
|
226
|
-
`${res.status} ${res.statusText}`.trim(),
|
|
227
|
-
bodyPreview ? `body: ${JSON.stringify(bodyPreview)}` : null,
|
|
228
|
-
]
|
|
229
|
-
.filter(Boolean)
|
|
230
|
-
.join(', ');
|
|
231
|
-
throw polotnoError('FETCH_FAILED', `HTTP error while downloading: ${details}`, { url: urlString, status: res.status });
|
|
232
235
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
url: urlString,
|
|
236
|
-
});
|
|
236
|
+
catch (e) {
|
|
237
|
+
// ignore
|
|
237
238
|
}
|
|
238
|
-
|
|
239
|
-
|
|
239
|
+
const details = [
|
|
240
|
+
`${res.status} ${res.statusText}`.trim(),
|
|
241
|
+
bodyPreview ? `body: ${JSON.stringify(bodyPreview)}` : null,
|
|
242
|
+
]
|
|
243
|
+
.filter(Boolean)
|
|
244
|
+
.join(', ');
|
|
245
|
+
throw polotnoError('FETCH_FAILED', `HTTP error while downloading: ${details}`, { url: urlString, status: res.status });
|
|
240
246
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
247
|
+
if (!res.body) {
|
|
248
|
+
throw polotnoError('FETCH_FAILED', 'Empty response body', {
|
|
249
|
+
url: urlString,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(destinationPath));
|
|
253
|
+
return res.headers.get('content-type') || '';
|
|
254
|
+
};
|
|
255
|
+
try {
|
|
256
|
+
return await withRetry(attemptDownload, {
|
|
257
|
+
// The shared policy (@polotno/core/retry), with this path's own pacing:
|
|
258
|
+
// local media is staged before the render starts, so it can afford to be
|
|
259
|
+
// quicker off the mark than an in-render asset fetch.
|
|
260
|
+
baseDelayMs: 300,
|
|
261
|
+
// Stated as what is TERMINAL, not what is transient: a transport
|
|
262
|
+
// allow-list silently missed this loop's own timeout abort.
|
|
263
|
+
shouldRetry: (e) => {
|
|
264
|
+
// Blocked by policy (SSRF) — deterministic, and re-resolving the same
|
|
265
|
+
// bad host would only burn the budget.
|
|
266
|
+
if (e?.ssrfBlocked)
|
|
267
|
+
return false;
|
|
268
|
+
const status = e?.details
|
|
269
|
+
?.status;
|
|
270
|
+
// A 4xx means the media is not there. This loop used to retry it three
|
|
271
|
+
// times before saying so.
|
|
272
|
+
if (typeof status === 'number')
|
|
273
|
+
return isRetryableStatus(status);
|
|
274
|
+
return true;
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
catch (lastError) {
|
|
279
|
+
// A policy rejection is surfaced untouched, as it was before this loop
|
|
280
|
+
// delegated its retrying: `ssrfBlocked` is what callers branch on, and a
|
|
281
|
+
// second FETCH_FAILED wrap buries it on `cause`.
|
|
282
|
+
if (lastError?.ssrfBlocked) {
|
|
283
|
+
throw lastError;
|
|
252
284
|
}
|
|
285
|
+
const message = lastError?.message || String(lastError);
|
|
286
|
+
throw polotnoError('FETCH_FAILED', `Failed to download media after ${attempts} attempt${attempts === 1 ? '' : 's'}: ${urlString}\nLast error: ${message}`, { url: urlString, attempts }, lastError);
|
|
253
287
|
}
|
|
254
|
-
const message = lastError && lastError.message ? lastError.message : String(lastError);
|
|
255
|
-
throw polotnoError('FETCH_FAILED', `Failed to download media after ${MAX_ATTEMPTS} attempts: ${urlString}\nLast error: ${message}`, { url: urlString, attempts: MAX_ATTEMPTS }, lastError);
|
|
256
288
|
};
|
|
257
289
|
// Returns a human-readable reason string if the video file needs transcoding
|
|
258
290
|
// for Chromium headless compatibility, or null if it is already render-safe.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno-node",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.8.0",
|
|
4
4
|
"description": "Polotno workflow from NodeJS",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
@@ -35,25 +35,25 @@
|
|
|
35
35
|
"@polotno/video-export"
|
|
36
36
|
],
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@types/node": "^26.1
|
|
39
|
-
"axios": "^1.
|
|
38
|
+
"@types/node": "^26.4.1",
|
|
39
|
+
"axios": "^1.20.0",
|
|
40
40
|
"dotenv": "^17.4.2",
|
|
41
41
|
"fluent-ffmpeg": "^2.1.3",
|
|
42
42
|
"jspdf": "^4.2.1",
|
|
43
43
|
"konva": "^10.3.2",
|
|
44
|
-
"mediabunny": "^1.
|
|
44
|
+
"mediabunny": "^1.55.5",
|
|
45
45
|
"pixelmatch": "^7.2.0",
|
|
46
46
|
"pngjs": "^7.0.0",
|
|
47
47
|
"react": "^19.2.8",
|
|
48
48
|
"react-dom": "^19.2.8",
|
|
49
49
|
"tmp": "^0.2.7",
|
|
50
50
|
"typescript": "~6.0.3",
|
|
51
|
-
"vite": "^8.2.
|
|
52
|
-
"vitest": "^4.1.
|
|
53
|
-
"web-audio-api": "^1.5.
|
|
54
|
-
"
|
|
55
|
-
"@polotno/video-export": "0.2.
|
|
56
|
-
"polotno": "
|
|
51
|
+
"vite": "^8.2.2",
|
|
52
|
+
"vitest": "^4.1.11",
|
|
53
|
+
"web-audio-api": "^1.5.5",
|
|
54
|
+
"polotno": "4.12.0",
|
|
55
|
+
"@polotno/video-export": "0.2.5",
|
|
56
|
+
"@polotno/design-fixtures": "0.0.0"
|
|
57
57
|
},
|
|
58
58
|
"overrides": {
|
|
59
59
|
"@polotno/video-export": {
|
|
@@ -64,8 +64,9 @@
|
|
|
64
64
|
"author": "Anton Lavrenov",
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@sparticuz/chromium": "^149.0.0",
|
|
67
|
-
"puppeteer": "25.
|
|
68
|
-
"puppeteer-core": "25.
|
|
67
|
+
"puppeteer": "25.9.0",
|
|
68
|
+
"puppeteer-core": "25.9.0",
|
|
69
|
+
"@polotno/core": "0.10.0",
|
|
69
70
|
"@polotno/schema": "0.6.1"
|
|
70
71
|
},
|
|
71
72
|
"bugs": {
|
|
@@ -77,6 +78,7 @@
|
|
|
77
78
|
"build": "rm -rf ./lib ./dist && tsc -p tsconfig.json && vite build ./client/ --base=./ --outDir ../dist --emptyOutDir --logLevel error",
|
|
78
79
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
79
80
|
"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",
|
|
81
|
+
"test:update-goldens": "rm -f test/static/goldens/*.png test/static/goldens/matrix/*.png && pnpm run test",
|
|
80
82
|
"test:video": "pnpm exec turbo run build --filter=polotno-node && VITEST_MAX_CONCURRENCY=${VITEST_MAX_CONCURRENCY:-3} vitest run test/video/video.test.mjs",
|
|
81
83
|
"test:all": "pnpm exec turbo run build --filter=polotno-node && vitest run test/unit test/static test/video",
|
|
82
84
|
"dev": "vite ./client.html"
|