polotno-node 3.12.1 → 3.13.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 +3 -0
- package/dist/assets/html2canvas-iod3n_YB.js +5 -0
- package/dist/assets/index-DODDd0dH.js +662 -0
- package/dist/assets/index.es-Dt5PfWmo.js +5 -0
- package/dist/assets/{jspdf.es.min-B6ep_ULC.js → jspdf.es.min-D3vqlR_0.js} +6 -6
- package/dist/assets/lib-SCSmTgPg.js +1 -0
- package/dist/assets/purify.es-BZxk_wWO.js +3 -0
- package/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/index.html +2 -2
- package/lib/instance.js +5 -2
- package/lib/types.d.ts +9 -0
- package/package.json +13 -13
- package/dist/assets/html2canvas-Dn6bw578.js +0 -5
- package/dist/assets/index-BIKy_ifH.js +0 -663
- package/dist/assets/index.es-D9O1JDWG.js +0 -5
- package/dist/assets/lib-RNLS4uJH.js +0 -1
- package/dist/assets/purify.es-Bvo9QlJ8.js +0 -3
- package/dist/assets/rolldown-runtime-hePW80VL.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./rolldown-runtime-XKyaHtl9.js";import{$ as e,A as t,At as n,B as r,Bt as i,C as a,Ct as o,D as s,Dt as c,E as l,Et as u,F as d,Ft as f,G as p,Gt as m,H as h,Ht as g,I as _,It as v,J as y,K as b,Kt as x,L as ee,Lt as te,M as ne,Mt as re,N as S,Nt as ie,O as ae,Ot as oe,P as se,Pt as ce,Q as le,R as ue,Rt as de,S as fe,St as pe,T as C,Tt as me,U as he,Ut as ge,V as _e,Vt as ve,W as ye,Wt as be,X as xe,Y as Se,Z as Ce,_ as we,_t as w,a as Te,at as Ee,b as T,bt as De,c as Oe,ct as ke,d as Ae,dt as je,et as Me,f as Ne,ft as Pe,g as Fe,gt as Ie,h as Le,ht as Re,i as ze,it as Be,j as Ve,jt as He,k as Ue,kt as E,l as D,lt as We,m as Ge,mt as Ke,n as qe,nt as Je,o as Ye,ot as Xe,p as Ze,pt as O,q as Qe,qt as $e,r as et,rt as tt,s as nt,st as rt,tt as it,u as k,ut as at,v as ot,vt as st,w as A,wt as ct,x as j,xt as lt,y as ut,yt as dt,z as ft,zt as pt}from"./index-DODDd0dH.js";var mt=`Mediabunny v1.61.4`,ht=new Map,gt=new Map,_t=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!C.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${C.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0)throw TypeError(`config.quality must be provided.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError(`config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.`);if(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.flip!==void 0&&typeof e.transform.flip!=`boolean`)throw TypeError(`config.transform.flip, when provided, must be a boolean.`);if(e.transform.crop!==void 0&&Ze(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.`);vt(e.codec,e)},vt=(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&&ne(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.`)},yt=e=>{let t=e.bitrateMode,n=e.quality._toVideoRateControl(e.codec,e.width,e.height,t),r=(t,n,r)=>({codec:e.fullCodecString??s(e.codec,e.width,e.height,r,e.alpha===`keep`),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:n,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...Ve(e.codec)}),i=[];return n.quantizer!==null&&i.push({config:r(void 0,`quantizer`,n.bitrate),quantizer:n.quantizer}),n.bitrateMode!==`quantizer`&&i.push({config:r(n.bitrate,n.bitrateMode,n.bitrate),quantizer:null}),O(i.length>0),i},bt=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!j.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${j.join(`, `)}.`);let t=e.bitrate;if(e.quality===void 0&&t===void 0&&!(a.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.quality must be provided for compressed audio codecs.`);if(e.quality!==void 0&&t!==void 0)throw TypeError(`config.quality and config.bitrate cannot both be provided.`);if(e.quality!==void 0&&!(e.quality instanceof M))throw TypeError(`config.quality, when provided, must be a Quality.`);if(t!==void 0&&!(t instanceof M)&&(!Number.isInteger(t)||t<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);if(e.onEncodedSample!==void 0&&typeof e.onEncodedSample!=`function`)throw TypeError(`config.onEncodedSample, when provided, must be a function.`);xt(e.codec,e)},xt=(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&&ne(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},St=e=>{let n=e.bitrateMode;return{codec:e.fullCodecString??l(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??n,...t(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 Ct):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`?Ct[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,r,i){let a=wt[e],o=null,s=this._bitrateMode??i??`variable`;if(this._quantizer!==void 0){if(!a){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<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${a.min} and ${a.max}.`)}else o=this._quantizer,this._bitrate===void 0&&(s=`quantizer`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(O(this._quality!==void 0),o=w(Math.round(n(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let n=this._quality;n===void 0&&(O(o!==null&&a),n=w((o-a.worst)/(a.best-a.worst),0,1)),c=Et(e,t,r,Tt(n))}return{quantizer:o,bitrate:c,bitrateMode:s}}_toVideoBitrate(e,t,n){return this._bitrate===void 0?(O(this._quality!==void 0),Et(e,t,n,Tt(this._quality))):this._bitrate}_toAudioBitrate(e){if(a.includes(e)||e===`flac`)return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw Error(`This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.`);let t=Tt(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}},Ct={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},wt={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}},Tt=e=>.3*Math.exp(2.5538*e),Et=(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},Dt=(e,t)=>{if(e===`avc`)return{avc:{quantizer:t}};if(e===`hevc`)return{hevc:{quantizer:t}};if(e===`vp9`)return{vp9:{quantizer:t}};if(e===`av1`)return{av1:{quantizer:t}};O(!1)},Ot=new M(`high`),kt=async(e,t={})=>{let{width:n=1280,height:r=720,quality:i,bitrate:a,frameRate:o,...s}=t;if(!C.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(i!==void 0&&!(i instanceof M))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&a!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(a!==void 0&&!(a instanceof M)&&(!Number.isInteger(a)||a<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);if(o!==void 0&&(!Number.isFinite(o)||o<=0))throw TypeError(`frameRate, when provided, must be a finite positive number.`);vt(e,s);let c=jt(i,a)??new M(`medium`),l;try{l=yt({codec:e,width:n,height:r,quality:c,framerate:o,...s,alpha:`discard`})}catch{return!1}let u=JSON.stringify(l),d=ht.get(u);if(d)return d;let f=(async()=>{for(let{config:t}of l)if(Oe.some(n=>n.supports(e,t)))return!0;if(typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`))return!1;for(let{config:t,quantizer:i}of l){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!pe()||await new Promise(async a=>{try{let o=new VideoEncoder({output:()=>{},error:()=>a(!1)});o.configure(t);let s=new Uint8Array(n*r*4),c=new VideoFrame(s,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});o.encode(c,i===null?void 0:Dt(e,i)),c.close(),await o.flush(),a(!0)}catch{a(!1)}}))return!0}return!1})();return ht.set(u,f),f},At=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,quality:i,bitrate:o,...s}=t;if(!j.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(i!==void 0&&!(i instanceof M))throw TypeError(`quality, when provided, must be a Quality.`);if(i!==void 0&&o!==void 0)throw TypeError(`quality and bitrate cannot both be provided.`);if(o!==void 0&&!(o instanceof M)&&(!Number.isInteger(o)||o<=0))throw TypeError(`bitrate must be a positive integer.`);xt(e,s);let c=St({codec:e,numberOfChannels:n,sampleRate:r,quality:jt(i,o)??new M(`medium`),...s}),l=JSON.stringify(c),u=gt.get(l);if(u)return u;let d=(async()=>{if(nt.some(t=>t.supports(e,c))||a.includes(e))return!0;if(typeof AudioEncoder>`u`)return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return gt.set(l,d),d},jt=(e,t)=>{if(e!==void 0)return e;if(t!==void 0)return t instanceof M?t:new M({bitrate:t})},Mt=async(e,t)=>{for(let n of e)if(await At(n,t))return n;return null},Nt=class{constructor(e){this.mutex=new Xe,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},Pt=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ft=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`)},It=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);O(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},N=new Uint8Array(8),P=new DataView(N.buffer),F=e=>[(e%256+256)%256],I=e=>(P.setUint16(0,e,!1),[N[0],N[1]]),Lt=e=>(P.setInt16(0,e,!1),[N[0],N[1]]),Rt=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]]),zt=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]]),Bt=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]]),Vt=e=>(P.setInt32(0,2**30*e,!1),[N[0],N[1],N[2],N[3]]),Ht=(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},Ut=e=>[B(e[0]),B(e[1]),Vt(e[2]),B(e[3]),B(e[4]),Vt(e[5]),B(e[6]),B(e[7]),Vt(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),Rt(n),r??[]],i),Wt=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`)]),Gt=()=>H(`styp`,[V(`iso5`),L(0),V(`iso5`),V(`iso6`),V(`mp41`),V(`cmfc`),V(`dash`)]),Kt=(e,t)=>{let n=Math.max(0,e.minWrittenTimestamp),r=Math.max(0,e.maxWrittenEndTimestamp-n);return Number.isFinite(r)||(r=0),U(`sidx`,1,0,[L(1),L(X),z(Z(n,X)),z(0),I(0),I(1),L(t&2147483647),L(Z(r,X)),L(0)])},qt=e=>({type:`mdat`,largeSize:e}),Jt=e=>({type:`free`,size:e}),W=e=>H(`moov`,void 0,[Yt(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Xt(t,e.creationTime)),e.isFragmented?Rn(e.trackDatas):null,$n(e)]),Yt=(e,t)=>{let n=Math.max(0,...t.map(e=>Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!c(e)||!c(n),a=i?z:L;return U(`mvhd`,+i,0,[a(e),a(e),L(X),a(n),B(1),Bt(1),Array(10).fill(0),Ut(at),Array(24).fill(0),L(r)])},Xt=(e,t)=>{let n=yr(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset!==0;return H(`trak`,void 0,[Zt(e,t),r?Qt(e):null,$t(e,t),n.name===void 0?null:H(`udta`,void 0,[H(`name`,[...i.encode(n.name)])])])},Zt=(e,t)=>{let n=Math.max(0,Z(Q(e),X)+Z(e.startTimestampOffset??0,X)),r=!c(t)||!c(n),i=r?z:L,a;if(e.type===`video`&&e.track.metadata.transformationMatrix)a=e.track.metadata.transformationMatrix;else if(e.type===`video`){let{rotation:t,flip:n}=e.track.metadata,r=re(ce(t??0),v(n?-1:1,1));a=Ie(r,e.info.width,e.info.height)}else a=at;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:Ke(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),Bt(+(e.type===`audio`)),I(0),Ut(a),B(e.type===`video`?e.info.width:0),B(e.type===`video`?e.info.height:0)])},Qt=e=>{let t=e.startTimestampOffset;if(O(t!==null),t>0){let n=Z(t,X),r=Z(Q(e),X),i=!c(n)||!c(r),a=i?z:L,o=i?zt:R;return H(`edts`,void 0,[U(`elst`,+!!i,0,[L(2),a(n),o(-1),B(1),a(r),o(0),B(1)])])}{let n=Z(-t,e.timescale),r=Math.max(0,Z(Q(e),X)+Z(t,X)),i=!o(n)||!c(r),a=i?z:L,s=i?zt:R;return H(`edts`,void 0,[U(`elst`,+!!i,0,[L(1),a(r),s(n),B(1)])])}},$t=(e,t)=>H(`mdia`,void 0,[en(e,t),rn(!0,tn[e.type],nn[e.type]),an(e)]),en=(e,t)=>{let n=Z(Q(e),e.timescale),r=!c(t)||!c(n),i=r?z:L;return U(`mdhd`,+r,0,[i(t),i(t),L(e.timescale),i(n),I(dr(e.track.metadata.languageCode??`und`)),I(0)])},tn={video:`vide`,audio:`soun`,subtitle:`text`},nn={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},rn=(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)]),an=e=>H(`minf`,void 0,[on[e.type](),sn(),un(e)]),on={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)},sn=()=>H(`dinf`,void 0,[cn()]),cn=()=>U(`dref`,0,0,[L(1)],[ln()]),ln=()=>U(`url `,0,1),un=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return H(`stbl`,void 0,[dn(e),jn(e),t?In(e):null,t?Ln(e):null,Nn(e),Pn(e),Fn(e),Mn(e)])},dn=e=>{let t;if(e.type===`video`)t=fn(ar(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=sr(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);O(n),t=bn(n,e)}else e.type===`subtitle`&&(t=kn(lr[e.track.source._codec],e));return O(t),U(`stsd`,0,0,[L(1)],[t])},fn=(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(mt.length),V(mt),Array(31-mt.length).fill(0),I(t.info.hasAlphaChannel?32:24),Lt(65535)],[or[t.track.source._codec]?.(t)??null,mn(t),st(t.info.decoderConfig.colorSpace)?null:hn(t),pn(t)]),pn=e=>e.avgBitrate===0&&e.maxBitrate===0?null:H(`btrt`,[L(0),L(e.maxBitrate),L(e.avgBitrate)]),mn=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:H(`pasp`,[L(e.info.pixelAspectRatio.num),L(e.info.pixelAspectRatio.den)]),hn=e=>{let t=e.info.decoderConfig.colorSpace;return H(`colr`,[V(e.muxer.isQuickTime?`nclc`:`nclx`),I(t?.primaries==null?2:rt[t.primaries]),I(t?.transfer==null?2:Pe[t.transfer]),I(t?.matrix==null?2:je[t.matrix]),e.muxer.isQuickTime?[]:F(!!t?.fullRange<<7)])},gn=e=>e.info.decoderConfig&&H(`avcC`,[...g(e.info.decoderConfig.description)]),_n=e=>e.info.decoderConfig&&H(`hvcC`,[...g(e.info.decoderConfig.description)]),vn=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?rt[t.colorSpace.primaries]:1,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Pe[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)])},yn=e=>H(`av1C`,Ue(e.info.decoderConfig.codec)),bn=(e,t)=>{let n=0,r,i=16,o=a.includes(t.track.source._codec);if(o){let e=t.track.source._codec,{sampleSize:r}=S(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(i),I(0),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0)];else{let e=o?0:-2;r=[[,,,,,,].fill(0),I(1),I(n),I(0),L(0),I(t.info.numberOfChannels),I(Math.min(i,16)),Lt(e),I(0),I(t.info.sampleRate<2**16?t.info.sampleRate:0),I(0),o?[L(1),L(i/8),L(t.info.numberOfChannels*i/8)]:[L(0),L(0),L(0)],L(2)]}return H(e,r,[cr(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,pn(t)])},xn=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),...Rt(0),...L(e.maxBitrate),...L(e.avgBitrate)];if(e.info.decoderConfig.description){let t=g(e.info.decoderConfig.description);n=[...n,...F(5),...Ht(t.byteLength),...t]}return n=[...I(1),...F(0),...F(4),...Ht(n.length),...n,...F(6),...F(1),...F(2)],n=[...F(3),...Ht(n.length),...n],U(`esds`,0,0,n)},G=e=>H(`wave`,void 0,[Sn(e),Cn(e),H(`\0\0\0\0`)]),Sn=e=>H(`frma`,[V(sr(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),Cn=e=>{let{littleEndian:t}=S(e.track.source._codec);return H(`enda`,[I(+t)])},wn=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){O(s.byteLength>=18);let e=g(s),c=y(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),Lt(i),F(a),...o])},Tn=e=>{let t=e.info.decoderConfig?.description;return O(t),U(`dfLa`,0,0,[...g(t).subarray(4)])},K=e=>{let{littleEndian:t,sampleSize:n}=S(e.track.source._codec);return U(`pcmC`,0,0,[F(+t),F(8*n)])},En=e=>{O(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 it(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])},Dn=e=>{O(e.info.primingPacket);let t=Qe(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 it(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])},On=e=>{O(e.info.primingPacket);let t=b(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`,[...ee(t)])},kn=(e,t)=>H(e,[[,,,,,,].fill(0),I(1)],[ur[t.track.source._codec](t),pn(t)]),An=e=>H(`vttC`,[...i.encode(e.info.config.description)]),jn=e=>U(`stts`,0,0,[L(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[L(e.sampleCount),L(e.sampleDelta)])]),Mn=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))])},Nn=e=>U(`stsc`,0,0,[L(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[L(e.firstChunk),L(e.samplesPerChunk),L(1)])]),Pn=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=S(e.track.source._codec);return U(`stsz`,0,0,[L(t*e.info.numberOfChannels),L(e.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0))])}return U(`stsz`,0,0,[L(0),L(e.samples.length),e.samples.map(e=>L(e.size))])},Fn=e=>e.finalizedChunks.length>0&&E(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))]),In=e=>U(`ctts`,1,0,[L(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[L(e.sampleCount),R(e.sampleCompositionTimeOffset)])]),Ln=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;O(e.compositionTimeOffsetTable.length>0),O(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Z(n.timestamp,e.timescale)),i=Math.max(i,Z(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:U(`cslg`,0,0,[R(a),R(t),R(n),R(r),R(i)])},Rn=e=>H(`mvex`,void 0,e.map(zn)),zn=e=>U(`trex`,0,0,[L(e.track.id),L(1),L(0),L(0),L(0)]),Bn=(e,t)=>H(`moof`,void 0,[Vn(e),...t.map(Un)]),Vn=e=>U(`mfhd`,0,0,[L(e)]),Hn=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16},Un=e=>H(`traf`,void 0,[Wn(e),Gn(e),Kn(e)]),Wn=e=>{O(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:Hn(n)};return U(`tfhd`,0,t,[L(e.track.id),L(r.duration),L(r.size),L(r.flags)])},Gn=e=>(O(e.currentChunk),U(`tfdt`,1,0,[z(Z(e.currentChunk.startTimestamp,e.timescale))])),Kn=e=>{O(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(Hn),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]):[]])])},qn=e=>H(`mfra`,void 0,[...e.map(Jn),Yn()]),Jn=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)])]),Yn=()=>U(`mfro`,0,0,[L(0)]),Xn=()=>H(`vtte`),Zn=(e,t,n,r,a)=>H(`vttc`,void 0,[a===null?null:H(`vsid`,[R(a)]),n===null?null:H(`iden`,[...i.encode(n)]),t===null?null:H(`ctim`,[...i.encode(Ft(t))]),r===null?null:H(`sttg`,[...i.encode(r)]),H(`payl`,[...i.encode(e)])]),Qn=e=>H(`vtta`,[...i.encode(e)]),$n=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=rr(r);e&&t.push(e)}else if(n===`mdta`){let e=ir(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&er(t,e.output._metadataTags);return t.length===0?null:H(`udta`,void 0,t)},er=(e,t)=>{for(let{key:n,value:r}of oe(t))switch(n){case`title`:e.push(q(`©nam`,r));break;case`description`:e.push(q(`©des`,r));break;case`artist`:e.push(q(`©ART`,r));break;case`album`:e.push(q(`©alb`,r));break;case`albumArtist`:e.push(q(`albr`,r));break;case`genre`:e.push(q(`©gen`,r));break;case`date`:e.push(q(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(q(`©cmt`,r));break;case`lyrics`:e.push(q(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`beatsPerMinute`:case`images`:break;default:Ke(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(q(n,r)):r instanceof Uint8Array&&e.push(H(n,Array.from(r))))}},q=(e,t)=>{let n=i.encode(t);return H(e,[I(n.length),I(dr(`und`)),Array.from(n)])},tr={"image/jpeg":13,"image/png":14,"image/bmp":27},nr=(e,t)=>{let n=[];for(let{key:r,value:i}of oe(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:J(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:J(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:J(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:J(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:J(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:J(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:J(i)});break;case`beatsPerMinute`:t||n.push({key:`tmpo`,value:H(`data`,[L(21),L(0),I(i)])});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:J(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:J(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:H(`data`,[L(tr[e.mimeType]??0),L(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:J(t)})}else n.push({key:`trkn`,value:H(`data`,[L(0),L(0),I(0),I(i),I(e.tracksTotal??0),I(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:H(`data`,[L(0),L(0),I(0),I(i),I(e.discsTotal??0),I(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Ke(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:J(i)}):i instanceof Uint8Array?n.push({key:r,value:H(`data`,[L(0),L(0),Array.from(i)])}):i instanceof Je&&n.push({key:r,value:H(`data`,[L(tr[i.mimeType]??0),L(0),Array.from(i.data)])}))}return n},rr=e=>{let t=nr(e,!1);return t.length===0?null:U(`meta`,0,0,void 0,[rn(!1,`mdir`,``,`appl`),H(`ilst`,void 0,t.map(e=>H(e.key,void 0,[e.value])))])},ir=e=>{let t=nr(e,!0);return t.length===0?null:H(`meta`,void 0,[rn(!1,`mdta`,``),U(`keys`,0,0,[L(t.length)],t.map(e=>H(`mdta`,[...i.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),...i.encode(e)]),ar=(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}},or={avc:gn,hevc:_n,vp8:vn,vp9:vn,av1:yn,prores:null},sr=(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`}},cr=(e,t)=>{switch(e){case`aac`:return xn;case`mp3`:return xn;case`opus`:return wn;case`vorbis`:return xn;case`flac`:return Tn;case`ac3`:return En;case`eac3`:return Dn;case`dts`:return On}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},lr={webvtt:`wvtt`},ur={webvtt:An},dr=e=>{O(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},fr=class{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){O(!this.started),this.target._start(),this.started=!0}write(e){O(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return O(this.started&&!this.finalized),this.target._flush()}async finalize(){O(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};we();var Y=class extends We{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 gr(this,e)}},pr=2**16,mr=2**32,hr=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(pr,{maxByteLength:mr})}catch{this._buffer=new ArrayBuffer(pr),this._supportsResize=!1}else this._buffer=new ArrayBuffer(pr);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>mr)throw Error(`ArrayBuffer exceeded maximum size of ${mr} 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)}},gr=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)}},_r=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,vr=2082844800,yr=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Z=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Q=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},br=class extends Nt{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new hr,this.auxWriter=new fr(this.auxTarget,!1),this.auxBoxWriter=new It(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ie(),this.creationTime=Math.floor(Date.now()/1e3)+vr,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 Br,this.isCmaf=t instanceof zr,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof zr?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 hr:this.formatOptions.fastStart===`fragmented`),this.boxWriter=new It(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof hr&&`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 fr(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new It(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(O(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(Wt({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`){if(this.fastStart===`reserve`){for(let e of this.output.tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(O(this.writer),O(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=qt(!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 ut({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;_(n,e.source._codec),O(n),O(n.decoderConfig);let i={...n.decoderConfig};O(i.codedWidth!==void 0),O(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){if(!t)throw Error(`No AVC description provided; you must therefore provide a priming packet.`);let e=_e(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Se(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){if(!t)throw Error(`No HEVC description provided; you must therefore provide a priming packet.`);let e=h(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=xe(e),a=!0}let o=dt(1/(e.metadata.frameRate??57600),1e6).den,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:pt({num:s*i.codedHeight,den:c*i.codedWidth}),u=i.codec===`ap4h`||i.codec===`ap4x`,d={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a,hasAlphaChannel:u},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,n,r){let i=this.trackDatas.find(e=>e.track===t);if(i)return i;se(r,t.source._codec),O(r),O(r.decoderConfig);let o={...r.decoderConfig},s=!1;if(t.source._codec===`aac`&&!o.description){if(!n)throw Error(`No AAC description provided; you must therefore provide a priming packet.`);let t=ot(qe.tempFromBytes(n.data));if(!t)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let r=le[t.samplingFrequencyIndex],i=Ce[t.channelConfiguration];if(r===void 0||i===void 0)throw Error(`Invalid ADTS frame header.`);o.description=e({objectType:t.objectType,outputSampleRate:r,outputNumberOfChannels:i}),s=!0}if(!n){if(t.source._codec===`ac3`||t.source._codec===`eac3`)throw Error(`AC-3/E-AC-3 require a priming packet.`);if(t.source._codec===`dts`)throw Error(`DTS requires a priming packet.`)}let c={muxer:this,track:t,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:o,requiresPcmTransformation:!this.isFragmented&&a.includes(t.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:s,primingPacket:n},timescale:o.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:t.source._nominalBitrate??t.metadata.averageBitrate??0,maxBitrate:t.source._nominalBitrate??t.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;d(t),O(t),O(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...ye(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=ue(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=ot(qe.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=S(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=Z(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=S(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let r of e.cueQueue)O(r.timestamp<=t),O(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=Xn();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;Pt.lastIndex=0;let r=Pt.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=Qn(n.notes);this.auxBoxWriter.writeBox(e)}let c=Zn(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Z(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){O(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Z(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=E(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t];let i=Z(r.timestamp-r.decodeTimestamp,e.timescale),a=Z(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){O(e.lastSample);let t=Z(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(O(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=E(e.timeToSampleTable);if(O(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=E(e.compositionTimeOffsetTable);O(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Z(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,O(e.lastSample),O(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){O(t.type===`key`);let n=Z(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(O(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),O(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(O(!this.isFragmented),O(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Z(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||E(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`)e.currentChunk.offset=0;else{e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)O(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}}async interleaveSamples(e=!1){if(O(this.isFragmented),e||this.allTracksAreKnown())outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(O(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;O(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=W(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,n)}if(this.isCmaf){O(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new It(this.writer);let e=this.boxWriter.measureBox(Gt()),t=this.boxWriter.measureBox(Kt(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}O(this.writer),O(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(t.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,r=Bn(n,t),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e=0;e<t.length;e++){let n=t[e];O(n.currentChunk),O(n.startTimestampOffset!==null),n.currentChunk.offset=o,n.currentChunk.moofOffset=i,n.currentChunk.trafIndex=e,n.currentChunk.startTimestamp-=n.startTimestampOffset;for(let e of n.currentChunk.samples)o+=e.size,e.timestamp-=n.startTimestampOffset,e.decodeTimestamp-=n.startTimestampOffset;s=Math.min(s,n.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=Bn(n,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,s)}O(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let d=qt(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of t)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){O(this.writer),O(this.boxWriter),this.ensureOneEnabledTrack();let e=W(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;O(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=qt(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){O(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;O(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of[`video`,`audio`,`subtitle`]){let t=this.trackDatas.filter(t=>t.type===e);if(t.length!==0&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){O(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart===`reserve`&&await this.createFastStartReserveMdat();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e);let t=Q(e);if(t>0){let n=0;for(let t of e.samples)n+=t.size;e.avgBitrate=Math.round(8*n/t)}else e.avgBitrate=0;let n=0,r=0,i=0;for(let t=0;t<e.samples.length;t++){let a=e.samples[t];for(r+=a.size;a.decodeTimestamp-e.samples[n].decodeTimestamp>=1;)r-=e.samples[n].size,n++;i=Math.max(i,r)}if(e.maxBitrate=8*i,e.startTimestampOffset!==null)for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(O(this.writer),O(this.boxWriter),this.fastStart===`in-memory`){this.mdat=qt(!1);let e;for(let t=0;t<2;t++){let t=W(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)O(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=W(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)O(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented){if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(Gt()),this.boxWriter.writeBox(Kt(this,e))}else{let e=this.writer.getPos(),t=qn(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}}else{O(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);O(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let n=W(this);if(this.fastStart===`reserve`){O(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Jt(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()}},xr=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){O(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>r<2?t[n*e+r]:0:e===4&&t===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;let t=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+t,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}O(this.startTime!==null);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=i+e.duration,o=Math.floor((i-1/this.sourceSampleRate)*this.targetSampleRate)+1,s=Math.ceil(a*this.targetSampleRate);for(let t=o;t<s;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;O(n<this.bufferCapacityInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=this.maxWrittenFrame===null?n:Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;O(this.startTime!==null);let e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=new D({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(n),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}},Sr=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},Cr=(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}),wr=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,e.output.state!==`finalizing`&&e.output.state!==`finalized`&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Tr=class extends wr{constructor(e){if(super(),!C.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${C.join(`, `)}.`);this._codec=e}},Er=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},Dr=class{setError(e){this.errorSet||=(this.error=e,!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new ke,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,n){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let i=this.encodingConfig,a=i.sizeChangeBehavior??`deny`,o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a===`deny`))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(i.transform?.width!==void 0||i.transform?.height!==void 0||i.transform?.rotate!==void 0||i.transform?.flip!==void 0||i.transform?.crop!==void 0||i.transform?.force===!0||o&&a!==`passThrough`){let n=i.transform?.width,r=i.transform?.height,s=i.transform?.fit??`fill`;o&&a!==`passThrough`&&(O(this.outputWidth),O(this.outputHeight),O(a!==`deny`),n=this.outputWidth,r=this.outputHeight,s=a);let c=await e.transform({width:n,height:r,roundDimensionsTo:2,crop:i.transform?.crop,rotate:i.transform?.rotate,flip:i.transform?.flip,fit:s,alpha:i.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let s=i.transform?.frameRate;if(s!==void 0){let i=e.timestamp+e.duration,a=De(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(u(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);let i=[];try{for(let n of t)n instanceof k?i.push(n):typeof VideoFrame<`u`&&n instanceof VideoFrame?i.push(new k(n)):i.push(new k(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 k&&n!==e||typeof VideoFrame<`u`&&n instanceof VideoFrame)&&n.close();throw n}r=i}else r=[e];try{for(let e of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),O(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let n=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/n),i={...this.defaultEncodeOptions,...e.encodeOptions,...t},a={...i,keyFrame:i.keyFrame===void 0?n===0||r!==this.lastMultipleOfKeyFrameInterval:i.keyFrame};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n}else{O(this.encoder);let t=e.toVideoFrame(),n=Re(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 kr;let{colorFrame:e,alphaFrame:n}=await this.splitter.split(t);this.alphaFrameQueue.push(n);try{this.encoder.encode(e,a)}finally{e.close()}}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of r)t!==e&&t.close()}}async padFrameRate(e,t){let n=this.encodingConfig.transform.frameRate;O(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*n);for(let e=1;e<r;e++){let r={stack:[],error:void 0,hasError:!1};try{let i=Sr(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{Cr(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=jt(this.encodingConfig.quality,this.encodingConfig.bitrate);O(t!==void 0);let n=yt({...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=Oe.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(He(`VideoEncoder`));let e=n[0].config,t=n.map(({config:e,quantizer:t})=>t===null?`${e.bitrate} bps`:`quantizer ${t}`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(` / `)}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??`no-preference`}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let a=r.config;r.quantizer===null?this.source._nominalBitrate=a.bitrate??null:this.defaultEncodeOptions=Dt(this.encodingConfig.codec,r.quantizer),i?(this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof T))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);Er(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init()):(this.encoderConfig=a,this.createWebCodecsEncoders()),O(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let e=this.encoderConfig;O(e);let t=[],n=[],r=0,i=0,a=(e,t)=>{lt(e)?this.encodersReclaimed=!0:(e.stack=t,this.setError(e))},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(e,a)=>{if(!this.alphaEncoder){this.addPacket(e,null,a);return}let o=this.alphaFrameQueue.shift();O(o!==void 0),o?(this.alphaEncoder.encode(o,{...this.defaultEncodeOptions,keyFrame:e.type===`key`}),i++,o.close(),t.push({chunk:e,meta:a})):i===0?this.addPacket(e,null,a):(n.push(r+i),t.push({chunk:e,meta:a}))},error:e=>a(e,o)}),this.encoder.configure(e),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(e,a)=>{i--;let o=t.shift();for(O(o!==void 0),this.addPacket(o.chunk,e,o.meta),r++;n.length>0&&n[0]===r;){n.shift();let e=t.shift();O(e!==void 0),this.addPacket(e.chunk,null,e.meta)}},error:e=>a(e,o)}),this.alphaEncoder.configure(e)}}addPacket(e,t,n){let i={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}let a=T.fromEncodedChunk(e,i),o=this.encoderConfig;O(o),n?.decoderConfig&&(n.decoderConfig.codec=ae({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:n.decoderConfig.description?g(n.decoderConfig.description):null,colorSpace:n.decoderConfig.colorSpace??null,avcType:o.codec.includes(`avc1.`)?1:o.codec.includes(`avc3.`)?3:null,avcCodecInfo:this.encodingConfig.codec===`avc`&&!n.decoderConfig.description?_e(a.data):null,hevcCodecInfo:this.encodingConfig.codec===`hevc`&&!n.decoderConfig.description?h(a.data):null,vp9CodecInfo:this.encodingConfig.codec===`vp9`?he(a.data):null,av1CodecInfo:this.encodingConfig.codec===`av1`?r(a.data):null,proresFormat:null}));let s=Re(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),c=s===-1?null:this.preciseTimings[s],l=null;this.emittedEncoderPackets===0&&a.type===`delta`&&n?.decoderConfig&&(l=ft(this.encodingConfig.codec,n.decoderConfig,a.data)),(c&&c.microsecondTimestamp===e.timestamp||l!==null)&&(a=a.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:l??void 0})),Er(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,n).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){O(this.encoder),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=De(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await ge(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}},Or=null,kr=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!Or){let e=new Blob([`(${Ar.toString()})()`],{type:`application/javascript`});Or=URL.createObjectURL(e)}this.worker=new Worker(Or),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=ie();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()}},Ar=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.allocationSize();if((!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=r*i,o=a+Math.ceil(r/2)*Math.ceil(i/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:t===`RGBA`?`RGBX`:`BGRX`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),l={format:`I420`,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n)=>{let r=n.visibleRect?.width??n.codedWidth,i=n.visibleRect?.height??n.codedHeight,a=t.includes(`P10`),o=t.includes(`P12`),s=a||o?2:1,c,l;t.startsWith(`I420`)?(c=Math.ceil(r/2),l=Math.ceil(i/2)):t.startsWith(`I422`)?(c=Math.ceil(r/2),l=i):(c=r,l=i);let u=r*i,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=t.replace(`A`,``),_=Math.ceil(r/2)*Math.ceil(i/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,ee=a?512:o?2048:128;s===1?y.fill(ee,x):new Uint16Array(y.buffer,x,2*_).fill(ee);let te=a?`I420P10`:o?`I420P12`:`I420`,ne=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0}),re={format:te,codedWidth:r,codedHeight:i,timestamp:n.timestamp,duration:n.duration??void 0,colorSpace:{fullRange:!0,matrix:`bt709`,primaries:`bt709`,transfer:`bt709`},transfer:[y.buffer]};return{colorFrame:ne,alphaFrame:new VideoFrame(y,re)}}},jr=class extends Tr{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.`);_t(t),super(t.codec),this._encoder=new Dr(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e))throw TypeError(`timestamp must be a finite number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new k(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Mr=class extends wr{constructor(e){if(super(),!j.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${j.join(`, `)}.`);this._codec=e}},Nr=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 ke,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 xr({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&&Ne(e.format)!==n.transform.sampleFormat){let r=Ae(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process)try{let t=n.transform.process(e);if(u(t)&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof D))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 D&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),O(this.encoderInitialized),this.closed)return;{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new D({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{O(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){O(this.outputSampleSize),O(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.format===`s32`||e.format===`s32-planar`,l=c?`s32-planar`:`f32-planar`,u=c?1/2147483648:1,d=e.allocationSize({planeIndex:0,format:l}),f=c?new Int32Array(d/4):new Float32Array(d/4);for(let t=0;t<n;t++){e.copyTo(f,{planeIndex:t,format:l});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,f[e*o+a]*u)}}t&&e.close();let p={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,c=e*o,l=new T(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,p),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,p)}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:n,sampleRate:r}=t,i=jt(this.encodingConfig.quality,this.encodingConfig.bitrate),o=St({numberOfChannels:n,sampleRate:r,...this.encodingConfig,quality:i});this.encodingConfig.onEncoderConfig?.(o),this.source._nominalBitrate=o.bitrate??null;let s=nt.find(e=>e.supports(this.encodingConfig.codec,o));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof T))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(a.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(He(`AudioEncoder`));let t;try{t=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{t=!1}if(!t)throw Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let n=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(t,n)=>{if(this.encodingConfig.codec===`aac`&&n?.decoderConfig){let t=!1;if(t=!n.decoderConfig.description||n.decoderConfig.description.byteLength<2||Me(g(n.decoderConfig.description)).objectType===0,t){let t=Number(E(o.codec.split(`.`)));n.decoderConfig.description=e({objectType:t,outputNumberOfChannels:n.decoderConfig.numberOfChannels,outputSampleRate:n.decoderConfig.sampleRate})}}let r=T.fromEncodedChunk(t);r=r.clone({timestamp:f(r.timestamp,o.sampleRate),duration:t.duration==null?void 0:f(r.duration,o.sampleRate)}),this.encodingConfig.onEncodedPacket?.(r,n),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,r,n).catch(e=>{this.setError(e)})},error:e=>{e.stack=n,this.setError(e)}}),this.encoder.configure(o)}O(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=S(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,w(Math.round(n*128)+128,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,w(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=w(Math.round(n*32768),-32768,32767);e.setUint8(t,Ye(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=w(Math.round(n*32768),-32768,32767);e.setUint8(t,Te(r))}:O(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,w(Math.round(n*32768)+32768,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,w(Math.round(n*32768),-32768,32767),r):O(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>de(e,t,w(Math.round(n*8388608)+8388608,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>te(e,t,w(Math.round(n*8388608),-8388608,8388607),r):O(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,w(Math.round(n*2147483648)+2147483648,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,w(Math.round(n*2147483648),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):O(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):O(!1);break;default:Ke(n),O(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Pr=class extends Mr{constructor(e,t={}){if(bt(e),typeof t!=`object`||!t)throw TypeError(`options must be an object.`);if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw TypeError(`options.startTimestamp, when provided, must be a finite number.`);super(e.codec),this._encoder=new Nr(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=D._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)}},Fr=class extends wr{constructor(e){if(super(),!A.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${A.join(`, `)}.`);this._codec=e}},Ir=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>C.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>j.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>A.includes(e))}_codecUnsupportedHint(e){return``}_isFragmentedIsobmff(){return!1}},Lr=class extends Ir{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&&(!me(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:0,max:e}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return`full`}_createMuxer(e){return new br(e,this)}_isFragmentedIsobmff(){return this._options.fastStart===`fragmented`}},Rr=class extends Lr{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...C,...fe,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...A]}_codecUnsupportedHint(e){return new Br().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},zr=class extends Lr{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...C,...fe,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...A]}},Br=class extends Lr{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...C,...j]}_codecUnsupportedHint(e){return new Rr().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},Vr=[`video`,`audio`,`subtitle`],Hr=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=ve(this.metadata.group),r=ve(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},Ur=class extends Hr{constructor(e,t,n,r){super(e,t,`video`,n,r)}},Wr=class extends Hr{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},Gr=class extends Hr{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},Kr=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},qr=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!ct(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&&Be(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.bitrate!==void 0&&(!Number.isFinite(e.bitrate)||e.bitrate<0))throw TypeError(`metadata.bitrate, when provided, must be a non-negative number.`);if(e.averageBitrate!==void 0&&(!Number.isFinite(e.averageBitrate)||e.averageBitrate<0))throw TypeError(`metadata.averageBitrate, when provided, must be a non-negative number.`);if(e.group!==void 0&&!(e.group instanceof Kr)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof Kr))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},Jr=class extends We{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(u(t))throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new Kr,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Xe,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 Ir))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Y||e.target instanceof _r))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Y&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Y)&&typeof e.initTarget!=`function`)throw Error(`options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw TypeError(`options.onFinalize, when provided, must be a function.`);this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Y&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){O(this._target instanceof _r);let t=this._target.getTarget(e),n=e=>{if(!(e instanceof Y))throw TypeError(`getTarget must return a Target.`);return e};return u(t)?t.then(n):n(t)}async _getTarget(e){O(this._target instanceof _r);let t=await this._getTargetValidated(e);return this._emit(`target`,{target:t,request:e,isRoot:e.isRoot}),this.state===`canceled`?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on(`finalized`,()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(O(this._initTarget!==null),this._initTarget instanceof Y)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Y)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return u(t)?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new fr(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof Tr))throw TypeError(`source must be a VideoSource.`);if(qr(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(t.flip!==void 0&&typeof t.flip!=`boolean`)throw TypeError(`metadata.flip, when provided, must be a boolean.`);if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(e=>Number.isFinite(e))))throw TypeError(`metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.hasOnlyKeyPackets!==void 0&&typeof t.hasOnlyKeyPackets!=`boolean`)throw TypeError(`metadata.hasOnlyKeyPackets, when provided, must be a boolean.`);if(t.canBeTransparent!==void 0&&typeof t.canBeTransparent!=`boolean`)throw TypeError(`metadata.canBeTransparent, when provided, must be a boolean.`);if(t.decoderConfig!==void 0&&_({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof T))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Ur(this.tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof Mr))throw TypeError(`source must be an AudioSource.`);if(qr(t),t.decoderConfig!==void 0&&se({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof T))throw TypeError(`metadata.primingPacket, when provided, must be an EncodedPacket.`);if(t.decoderConfig===void 0)throw TypeError(`metadata.primingPacket can only be provided alongside metadata.decoderConfig.`)}let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Wr(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Fr))throw TypeError(`source must be a SubtitleSource.`);qr(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new Gr(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(tt(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 Vr)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 Vr){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?(Ee._warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state===`canceled`)return this._cancelPromise??void 0;if(this.state===`finalizing`||this.state===`finalized`)this.state===`finalized`&&Ee._warn(`Output has already been finalized.`);else return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(Ee._warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}catch(e){throw this.state=`canceled`,e}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}},Yr=$e,Xr=[{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 Zr(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=Xr.find(s),l=Xr.find(e=>s(e)&&o*r<=e.maxMacroblocksPerSecond&&Math.max(i,a)<=Math.sqrt(e.maxMacroblocks*8))??Xr[Xr.length-1];if(c&&l!==c)return`avc1.6400${l.levelIdc.toString(16).padStart(2,`0`)}`}function Qr(e){return e instanceof Error&&/is not (supported|available) in this environment/.test(e.message)}async function $r({codecs:e,attempt:t,probe:n,...r}){let i,a=[];for(let[o,s]of e.entries())if(!(o>0&&!await n(s))){a.push(s);try{let e=await x(()=>t(s),{...r,shouldRetry:Qr});return i&&console.warn(`[polotno-video-export] Encoding with ${s}: ${i.message}`),e}catch(e){if(!Qr(e))throw e;i=e}}throw Yr(`VIDEO_FAILED`,`Your browser doesn't support video encoding. Tried ${a.join(`, `)}; last error: ${i?.message}`,{reason:`no-encoder`},i)}function ei(){return typeof DOMException<`u`?new DOMException(`The operation was aborted.`,`AbortError`):Object.assign(Error(`The operation was aborted.`),{name:`AbortError`})}function $(e){return!!e&&typeof e==`object`&&`name`in e&&e.name===`AbortError`}function ti(e){return Math.round(e/2)*2}function ni(e){return e.pages.reduce((e,t)=>e+(t.duration||5e3),0)}function ri(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 ii(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:ti(t),height:ti(n)}}function ai(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 oi(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 si(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 ci(e,t){let n=m(),r=n.sceneCanvas._canvas;if(r.width=e.width*t,r.height=e.height*t,r.width<=0||r.height<=0)throw Yr(`VIDEO_FAILED`,`Invalid canvas dimensions: ${r.width}x${r.height}`,{reason:`invalid-dimensions`});return{canvas:r,canvases:n}}var li=e=>e.cancel().catch(()=>{});function ui(e,t,n){let{width:r,height:i}=t;return kt(e,{width:r,height:i,quality:Ot,fullCodecString:Zr(e,r,i,n)})}async function di(e,t,n){if(!n)return{audioBufferSource:null};let r=t.audios&&t.audios.length>0,i=ai(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 Mt(s,{numberOfChannels:2,sampleRate:44100,quality:Ot});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 Pr({codec:c,quality:Ot});return e.addAudioTrack(l),{audioBufferSource:l,audioCodec:c}}function fi(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 pi(e,t,n,r,i){e.setCurrentTime(t),await e._toCanvas({pixelRatio:r,pageId:e.pages[n]?.id,_skipTimeout:!0,_exportCanvases:i})}async function mi(e,t,n,r,i,a,o,s,c){let l=1e3/a,u=Math.floor(i/1e3*a)||1;s?.(0,void 0,{stage:`frames`,completed:0,total:u});let d=e.timingPreview;e.setTimingPreview(`playhead`);try{c?.throwIfAborted(),e.setElementsPixelRatio(o);let d=-1,f=0;for(let p=0;p<u;p++){c?.throwIfAborted();let m=Date.now(),h=p/a,g=1/a,_=h*1e3;p===0&&(_=1),p===u-1&&(_=Math.min(i-1,(p+1)*l-1));let v=fi(_,r,d);if(v!==d&&v>=0&&(e.activePage.set({_rendering:!1}),e.selectPage(e.pages[v].id),e.activePage.set({_rendering:!0}),await e.waitLoading(),c?.throwIfAborted(),d=v),await pi(e,_,v,o,n),c?.throwIfAborted(),await t(h,g),s){let e=Date.now();if(p===u-1||e-f>=300){let t=e-m;s((p+1)/u*.95,t,{stage:`frames`,completed:p+1,total:u}),f=e,await new Promise(e=>setTimeout(e,0))}}}}finally{e.pages.forEach(e=>{e.set({_rendering:!1})}),e.setCurrentTime(0),e.setTimingPreview(d)}}async function hi(e,t){let n=await fetch(e,t?{signal:t}:void 0);if(!n.ok)throw Yr(`FETCH_FAILED`,`Failed to download audio from ${e}`,{url:e,status:n.status});return n.arrayBuffer()}async function gi(e,t){return e.decodeAudioData(t)}function _i(e){return e.startsWith(`data:`)}function vi(e){return e.startsWith(`file://`)}function yi(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function bi(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 xi(e,t){try{if(yi(e))return new et({source:new Fe(e),formats:Ge});if(_i(e)){let t=bi(e);return new et({source:new Le(t),formats:Ge})}if(vi(e)){let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new et({source:new Le(n),formats:Ge})}{let n=await(await fetch(e,t?{signal:t}:void 0)).arrayBuffer();return new et({source:new Le(n),formats:Ge})}}catch(n){return $(n)||t?.aborted||console.error(`Failed to create input from ${e.slice(0,50)}:`,n),null}}async function Si(e,t){try{t?.throwIfAborted();let n=await xi(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(),ei();return r.length===0?(n.dispose(),{hasAudio:!1,input:null}):{hasAudio:!0,input:n}}catch(n){if($(n))throw n;if(t?.aborted)throw ei();return console.error(`Failed to check audio for ${e.slice(0,50)}:`,n),{hasAudio:!1,input:null}}}function Ci(e,t){let n=e.audios||[],r=ai(e);return{storeAudios:n.map(e=>({audio:e,bufferPromise:hi(e.src,t).catch(n=>($(n)||t?.aborted||console.error(`Failed to download audio ${e.src}:`,n),null))})),videoAudios:r.map(e=>({video:e,inputPromise:Si(e.src,t).catch(e=>{if($(e)||t?.aborted)return{hasAudio:!1,input:null};throw e})}))}}function wi(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 Ti(e,t,n){let r=e.startTime*e.duration/1e3,i=e.duration*(e.endTime-e.startTime)/1e3,{start:a,end:o}=be(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 Ei(e,t,n,r,i,a,o){o?.throwIfAborted();let s=i||Ci(e,o),c=s.storeAudios.length+s.videoAudios.length;if(c===0)return;let l=44100,u=r?.includes(`opus`)?960:1024,d=r===`aac`?3:r?.includes(`opus`)?2:0,f=Math.floor(n/1e3*l),p=Math.floor(f/u)*u,m=d*u,h=Math.max(u,p-m),g=new OfflineAudioContext(2,h,l),_={offlineContext:g,sampleRate:l,totalDuration:n},v=0,y=()=>{v++,a?.(.95+v/c*.02,void 0,{stage:`audio-decode`,completed:v,total:c})};a?.(.95,void 0,{stage:`audio-decode`,completed:0,total:c});let[b,x]=await Promise.all([Promise.all(s.storeAudios.map(async({audio:e,bufferPromise:t})=>{try{o?.throwIfAborted();let n=await t;return o?.throwIfAborted(),n?{audio:e,audioBuffer:await gi(g,n)}:null}catch(t){if($(t))throw t;return console.error(`Failed to process audio ${e.src}:`,t),null}finally{y()}})),Promise.all(s.videoAudios.map(async({video:e,inputPromise:t})=>{try{o?.throwIfAborted();let{hasAudio:n,input:r}=await t;if(o?.throwIfAborted(),!n||!r)return console.log(`[polotno-video-export] Video ${e.id} has no audio track or input failed. hasAudio=${n}, input=${!!r}`),null;let i=await r.getPrimaryAudioTrack();if(!i)return console.log(`[polotno-video-export] Video ${e.id} getPrimaryAudioTrack returned null`),r.dispose(),null;let a=new ze(i),s=[];for await(let e of a.buffers())o?.throwIfAborted(),s.push(e.buffer);if(r.dispose(),o?.throwIfAborted(),s.length===0)return console.log(`[polotno-video-export] Video ${e.id} AudioBufferSink returned 0 buffers`),null;let c=s.reduce((e,t)=>e+t.length,0),l=g.createBuffer(s[0].numberOfChannels,c,s[0].sampleRate),u=0;for(let e of s){for(let t=0;t<e.numberOfChannels;t++)l.getChannelData(t).set(e.getChannelData(t),u);u+=e.length}return{video:e,audioBuffer:l}}catch(t){if($(t))throw t;return console.error(`Failed to extract video audio ${e.src}:`,t),null}finally{y()}}))]);o?.throwIfAborted();for(let e of b)e&&wi(e.audio,e.audioBuffer,_);for(let e of x)e&&Ti(e.video,e.audioBuffer,_);o?.throwIfAborted(),a?.(.97,void 0,{stage:`audio-render`});let ee=await g.startRendering();o?.throwIfAborted(),a?.(.99,void 0,{stage:`audio-encode`}),await t.add(ee)}async function Di({store:e,fps:t=30,pixelRatio:n=1,onProgress:r,includeAudio:i=!0,signal:a}){r?.(0,void 0,{stage:`setup`});let o=ii(e),s=oi(e,o),c=null,l=null,u=!1;if(a){let e=()=>{try{c?.canvasSource.close()}catch{}try{c?.audioBufferSource?.close()}catch{}c&&li(c.output)};a.addEventListener(`abort`,e,{once:!0}),l=()=>a.removeEventListener(`abort`,e)}try{a?.throwIfAborted();let s=ni(e);if(s===0)throw Yr(`VIDEO_FAILED`,`Video duration is 0`,{reason:`zero-duration`});let l=ri(e),{canvas:d,canvases:f}=ci(o,n),p=async(n,r,a)=>{let o=new Jr({target:new hr,format:new Rr});try{let s=new jr(d,{codec:n,quality:Ot,fullCodecString:Zr(n,d.width,d.height,t)});o.addVideoTrack(s,{frameRate:t});let c=await di(o,e,i);return await o.start(),await s.add(r,a),{output:o,canvasSource:s,...c}}catch(e){throw await li(o),e}},m=new Rr().getSupportedVideoCodecs();await mi(e,async(e,n)=>{c?await c.canvasSource.add(e,n):c=await $r({codecs:m,probe:e=>ui(e,d,t),attempt:t=>p(t,e,n),signal:a})},f,l,s,t,n,r,a);let{output:h,canvasSource:g,audioBufferSource:_,audioCodec:v}=c;g.close();let y=_?Ci(e,a):null;_&&y&&(await Ei(e,_,s,v,y,r,a),_.close()),a?.throwIfAborted(),r?.(.99,void 0,{stage:`finalize`}),await h.finalize();let b=h.target,x=new Blob([b.buffer],{type:h.format.mimeType});return u=!0,x}catch(e){throw $(e)?e:a?.aborted?ei():e}finally{l?.(),!u&&c&&await li(c.output),si(e,s)}}export{Di as storeToVideo};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
function e(e,t){this.v=e,this.k=t}function t(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function n(e){if(Array.isArray(e))return e}function r(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function i(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function a(e,t){return n(e)||r(e,t)||o(e,t)||i()}function o(e,n){if(e){if(typeof e==`string`)return t(e,n);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}function s(t){var n,r;function i(n,r){try{var o=t[n](r),s=o.value,c=s instanceof e;Promise.resolve(c?s.v:s).then(function(e){if(c){var r=n===`return`&&s.k?n:`next`;if(!s.k||e.done)return i(r,e);e=t[r](e).value}a(!!o.done,e)},function(e){i(`throw`,e)})}catch(e){a(2,e)}}function a(e,t){e===2?n.reject(t):n.resolve({value:t,done:e}),(n=n.next)?i(n.key,n.arg):r=null}this._invoke=function(e,t){return new Promise(function(a,o){var s={key:e,arg:t,resolve:a,reject:o,next:null};r?r=r.next=s:(n=r=s,i(e,t))})},typeof t.return!=`function`&&(this.return=void 0)}s.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},s.prototype.next=function(e){return this._invoke(`next`,e)},s.prototype.throw=function(e){return this._invoke(`throw`,e)},s.prototype.return=function(e){return this._invoke(`return`,e)};var c=Object.entries,l=Object.setPrototypeOf,u=Object.isFrozen,d=Object.getPrototypeOf,f=Object.getOwnPropertyDescriptor,p=Object.freeze,m=Object.seal,h=Object.create,ee=typeof Reflect<`u`&&Reflect,te=ee.apply,ne=ee.construct;p||=function(e){return e},m||=function(e){return e},te||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},ne||=function(e){return new e(...[...arguments].slice(1))};var g=T(Array.prototype.forEach);Array.prototype.indexOf;var re=T(Array.prototype.lastIndexOf),ie=T(Array.prototype.pop),ae=T(Array.prototype.push),oe=T(Array.prototype.slice),se=T(Array.prototype.splice),_=Array.isArray,ce=E(Set),le=T(Set.prototype.add),ue=T(Set.prototype.has),v=T(String.prototype.toLowerCase),de=T(String.prototype.toString),fe=T(String.prototype.match),pe=T(String.prototype.replace),me=T(String.prototype.indexOf),he=T(String.prototype.trim),ge=T(Number.prototype.toString),y=T(Boolean.prototype.toString),b=typeof BigInt>`u`?null:T(BigInt.prototype.toString),_e=typeof Symbol>`u`?null:T(Symbol.prototype.toString),x=T(Object.prototype.hasOwnProperty),S=T(Object.prototype.toString),C=T(RegExp.prototype.test),w=E(TypeError);function T(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return te(e,t,n)}}function E(e){return function(){return ne(e,[...arguments])}}function D(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v;if(l&&l(e,null),!_(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(u(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ve(e){for(let t=0;t<e.length;t++)x(e,t)||(e[t]=null);return e}function O(e){let t=h(null);for(let r of c(e)){var n=a(r,2);let i=n[0],o=n[1];x(e,i)&&(t[i]=_(o)?ve(o):o&&typeof o==`object`&&o.constructor===Object?O(o):o)}return t}function ye(e){switch(typeof e){case`string`:return e;case`number`:return ge(e);case`boolean`:return y(e);case`bigint`:return b?b(e):`0`;case`symbol`:return _e?_e(e):`Symbol()`;case`undefined`:return S(e);case`function`:case`object`:{if(e===null)return S(e);let t=e,n=k(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:S(e)}return S(e)}default:return S(e)}}function k(e,t){for(;e!==null;){let n=f(e,t);if(n){if(n.get)return T(n.get);if(typeof n.value==`function`)return T(n.value)}e=d(e)}function n(){return null}return n}function be(e,t){for(;e!==null;){let n=f(e,t);if(n)return n.get?T(n.get):null;e=d(e)}return null}function xe(e){try{return C(e,``),!0}catch{return!1}}var Se=p(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Ce=p(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),we=p([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Te=p([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Ee=p(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),De=p([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Oe=p([`#text`]),ke=p(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),Ae=p(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.pointer-events.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.vector-effect.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),je=p(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Me=p([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Ne=m(/{{[\w\W]*|^[\w\W]*}}/g),Pe=m(/<%[\w\W]*|^[\w\W]*%>/g),Fe=m(/\${[\w\W]*/g),Ie=m(/^data-[\-\w.\u00B7-\uFFFF]+$/),Le=m(/^aria-[\-\w]+$/),Re=m(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ze=m(/^(?:\w+script|data):/i),Be=m(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ve=m(/^html$/i),He=m(/^[a-z][.\w]*(-[.\w]+)+$/i),Ue=m(/<[/\w!]/g),We=m(/<[/\w]/g),Ge=m(/<\/no(script|embed|frames)/i),Ke=m(/\/>/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},qe=p(D({},[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`])),Je=function(){return typeof window>`u`?null:window},Ye=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}},Xe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},j=function(e,t,n,r){return x(e,t)&&_(e[t])?D(r.base?O(r.base):{},e[t],r.transform):n},Ze=function(e,t,n){let r=x(e,t)?e[t]:void 0;return r&&typeof r==`object`?O(r):n()};function Qe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Je(),t=e=>Qe(e);if(t.version=`3.4.17`,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,o=e.Node,s=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,d=e.trustedTypes,f=s.prototype,ee=k(f,`cloneNode`),te=k(f,`remove`),ne=k(f,`removeAttributeNode`),ge=k(f,`nextSibling`),y=k(f,`childNodes`),b=k(f,`parentNode`),_e=k(f,`shadowRoot`),S=k(f,`attributes`),T=o&&o.prototype?k(o.prototype,`nodeType`):null,E=o&&o.prototype?k(o.prototype,`nodeName`):null,ve=o&&o.prototype?k(o.prototype,`ownerDocument`):null,M=function(e){return T?T(e):e.nodeType},$e=function(e){return E?E(e):e.nodeName},et=be(f,`namespaceURI`),tt=function(e){return et?et(e):e.namespaceURI};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let N,P=``,nt,rt=!1,it=0,at=function(){if(it>0)throw w(`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){at(),it++;try{return N.createHTML(e)}finally{it--}},ot=function(e){at(),it++;try{return N.createScriptURL(e)}finally{it--}},st=function(){return rt||=(nt=Ye(d,i),!0),nt},ct=n,lt=ct.implementation,ut=ct.createNodeIterator,dt=ct.createDocumentFragment,ft=ct.getElementsByTagName,pt=r.importNode,I=Xe();t.isSupported=typeof c==`function`&&typeof b==`function`&<&<.createHTMLDocument!==void 0;let mt=Ne,ht=Pe,gt=Fe,_t=Ie,vt=Le,yt=ze,bt=Be,xt=He,St=Re,L=null,Ct=D({},[...Se,...Ce,...we,...Ee,...Oe]),R=null,wt=D({},[...ke,...Ae,...je,...Me]),z=Object.seal(h(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Tt=null,Et=null,B=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Dt=!0,Ot=!0,kt=!1,At=!0,V=!1,H=!0,U=!1,jt=!1,Mt=null,Nt=null,Pt=!1,W=!1,Ft=!1,It=!1,Lt=!0,Rt=!1,zt=`user-content-`,Bt=!0,Vt=!1,G=null,K={},q=null,Ht=D({},`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(`.`)),Ut=null,Wt=D({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Gt=null,Kt=D({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),qt=`http://www.w3.org/1998/Math/MathML`,Jt=`http://www.w3.org/2000/svg`,J=`http://www.w3.org/1999/xhtml`,Y=J,Yt=!1,Xt=null,Zt=D({},[qt,Jt,J],de),Qt=p([`mi`,`mo`,`mn`,`ms`,`mtext`]),$t=D({},Qt),en=p([`annotation-xml`]),tn=D({},en),nn=D({},[`title`,`style`,`font`,`a`,`script`]),rn=null,an=[`application/xhtml+xml`,`text/html`],X=null,on=null,sn=n.createElement(`form`),cn=function(e){return e instanceof RegExp||e instanceof Function},ln=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(on&&on===e)return;(!e||typeof e!=`object`)&&(e={}),e=O(e),rn=an.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=rn===`application/xhtml+xml`?de:v,L=j(e,`ALLOWED_TAGS`,Ct,{transform:X}),R=j(e,`ALLOWED_ATTR`,wt,{transform:X}),Xt=j(e,`ALLOWED_NAMESPACES`,Zt,{transform:de}),Gt=j(e,`ADD_URI_SAFE_ATTR`,Kt,{transform:X,base:Kt}),Ut=j(e,`ADD_DATA_URI_TAGS`,Wt,{transform:X,base:Wt}),q=j(e,`FORBID_CONTENTS`,Ht,{transform:X}),Tt=j(e,`FORBID_TAGS`,O({}),{transform:X}),Et=j(e,`FORBID_ATTR`,O({}),{transform:X}),K=x(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?O(e.USE_PROFILES):e.USE_PROFILES:!1,Dt=e.ALLOW_ARIA_ATTR!==!1,Ot=e.ALLOW_DATA_ATTR!==!1,kt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,At=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,Ft=e.RETURN_DOM_FRAGMENT||!1,It=e.RETURN_TRUSTED_TYPE||!1,Pt=e.FORCE_BODY||!1,Lt=e.SANITIZE_DOM!==!1,Rt=e.SANITIZE_NAMED_PROPS||!1,Bt=e.KEEP_CONTENT!==!1,Vt=e.IN_PLACE||!1,St=xe(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Re,Y=typeof e.NAMESPACE==`string`?e.NAMESPACE:J,$t=Ze(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>D({},Qt)),tn=Ze(e,`HTML_INTEGRATION_POINTS`,()=>D({},en));let t=Ze(e,`CUSTOM_ELEMENT_HANDLING`,()=>h(null));if(z=h(null),x(t,`tagNameCheck`)&&cn(t.tagNameCheck)&&(z.tagNameCheck=t.tagNameCheck),x(t,`attributeNameCheck`)&&cn(t.attributeNameCheck)&&(z.attributeNameCheck=t.attributeNameCheck),x(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(z.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),m(z),V&&(Ot=!1),Ft&&(W=!0),K&&(L=D({},Oe),R=h(null),K.html===!0&&(D(L,Se),D(R,ke)),K.svg===!0&&(D(L,Ce),D(R,Ae),D(R,Me)),K.svgFilters===!0&&(D(L,we),D(R,Ae),D(R,Me)),K.mathMl===!0&&(D(L,Ee),D(R,je),D(R,Me))),B.tagCheck=null,B.attributeCheck=null,x(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?B.tagCheck=e.ADD_TAGS:_(e.ADD_TAGS)&&(L===Ct&&(L=O(L)),D(L,e.ADD_TAGS,X))),x(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?B.attributeCheck=e.ADD_ATTR:_(e.ADD_ATTR)&&(R===wt&&(R=O(R)),D(R,e.ADD_ATTR,X))),x(e,`ADD_FORBID_CONTENTS`)&&_(e.ADD_FORBID_CONTENTS)&&(q===Ht&&(q=O(q)),D(q,e.ADD_FORBID_CONTENTS,X)),Bt&&(L[`#text`]=!0),U&&D(L,[`html`,`head`,`body`]),L.table&&(D(L,[`tbody`]),delete Tt.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw w(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw w(`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=st()),N&&typeof P==`string`&&(P=F(``)));p&&p(e),on=e},un=D({},[...Ce,...we,...Te]),dn=D({},[...Ee,...De]),fn=function(e,t,n){return t.namespaceURI===J?e===`svg`:t.namespaceURI===qt?e===`svg`&&(n===`annotation-xml`||$t[n]):!!un[e]},pn=function(e,t,n){return t.namespaceURI===J?e===`math`:t.namespaceURI===Jt?e===`math`&&tn[n]:!!dn[e]},mn=function(e,t,n){return t.namespaceURI===Jt&&!tn[n]||t.namespaceURI===qt&&!$t[n]?!1:!dn[e]&&(nn[e]||!un[e])},hn=function(e){let t=tt(e),n=v($e(e)),r=b(e),i,a;return r&&M(r)===A.element?(i={namespaceURI:tt(r)},a=v($e(r))):(i={namespaceURI:Y},a=`template`),Xt[t]?t===Jt?fn(n,i,a):t===qt?pn(n,i,a):t===J?mn(n,i,a):!!(rn===`application/xhtml+xml`&&Xt[t]):!1},Z=function(e){ae(t.removed,{element:e});try{b(e).removeChild(e)}catch{if(te(e),!b(e))throw w(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},gn=function(e,t,n){try{ne(e,t)}catch{try{e.removeAttribute(n)}catch{}}},_n=function(e){xn(e);let t=y(e);t&&g(oe(t),e=>{try{te(e)}catch{}});let n=M(e)===A.element?S(e):null;if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&gn(e,r,i)}},vn=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}ae(t.removed,{attribute:r||null,from:n});try{r?ne(n,r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(W||Ft)try{Z(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},yn=function(e){let t=S(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||R[X(i)]||gn(e,r,i)}},bn=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=[e];for(;r.length>0;){let e=r.pop();if(t(e)===!1)continue;if(n&&M(e)===A.element){let t=_e(e);Q(t)&&r.push(t)}let i=y(e);if(i)for(let e=i.length-1;e>=0;--e)r.push(i[e])}},xn=function(e){bn(e,e=>{M(e)===A.element&&yn(e)})},Sn=function(e){let t=[];return bn(e,e=>{t.push(e)},!0),t},Cn=function(e,t){let n=ce();g(Sn(e),e=>{M(e)===A.element&&le(n,e)}),g(t,e=>{M(e)===A.element&&!ue(n,e)&&yn(e)})},wn=function(e,n){let r=!1;return g(t.removed,t=>{t.element&&(r||=t.element===e,xn(t.element))}),Cn(e,n),r},Tn=function(e,t){let n=G,r=null,i=()=>(r||(r=ce(),g(t,e=>{le(r,e)})),r);for(let t=0;;t++){let r=Sn(e),a=[e],o=!1;if(g(r,e=>{M(e)===A.documentFragment?ae(a,e):!o&&!ue(n,e)&&(o=ue(i(),e))}),!o)return;if(t>=8)throw w(`the tree kept changing during in-place sanitization; refusing to return it`);g(a,(t,n)=>{En(t,n>0,e,i())})}},En=function(e,t,n,r){let i=jn(e),a;for(;a=i.nextNode();)ue(r,a)&&!ue(G,a)&&(t&&$(I.uponSanitizeShadowNode,a,null),Hn(a,n),Yn(a,n),Q(a.content)&&Xn(a.content))},Dn=function(e){G&&le(G,e)},On=function(e,t){return H?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},kn=function(e){H&&bn(e,e=>{let t=M(e);if(t===A.processingInstruction||t===A.comment&&C(We,e.data)){try{te(e)}catch{}return!1}if(t===A.element){let t=e,n=X($e(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&On(`for`,n)&&t.removeAttribute(`for`)}catch{}}return!0})},An=function(e){let t=null,r=null;if(Pt)e=`<remove></remove>`+e;else{let t=fe(e,/^[\r\n\t ]+/);r=t&&t[0]}rn===`application/xhtml+xml`&&Y===J&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=N?F(e):e;if(Y===J)try{t=new u().parseFromString(i,rn)}catch{}if(!t||!t.documentElement){t=lt.createDocument(Y,`template`,null);try{t.documentElement.innerHTML=Yt?P:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Y===J?ft.call(t,U?`html`:`body`)[0]:U?t.documentElement:a},jn=function(e){let t=ve?ve(e):e.ownerDocument;return ut.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Mn=function(e){return e=pe(e,mt,` `),e=pe(e,ht,` `),e=pe(e,gt,` `),e},Nn=function(e){Pn(e);let t=e.querySelectorAll?.call(e,`template`);t&&g(t,e=>{Q(e.content)&&Nn(e.content)})},Pn=function(e){e.normalize();let t=ve?ve(e):e.ownerDocument,n=ut.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=Mn(r.data),r=n.nextNode()},Fn=function(e){let t=E?E(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==S(e)||typeof e.removeAttribute!=`function`||typeof e.removeAttributeNode!=`function`||typeof e.getAttributeNode!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==T(e)||e.childNodes!==y(e)},Q=function(e){if(!T||typeof e!=`object`||!e)return!1;try{return T(e)===A.documentFragment}catch{return!1}},In=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,on)})}let Ln=function(e,t){return!!(H&&e.hasChildNodes()&&!In(e.firstElementChild)&&C(Ue,e.textContent)&&C(Ue,e.innerHTML)||H&&qe[t]&&M(e)===A.element&&tt(e)===J&&(In(e.firstElementChild)||typeof e.textContent==`string`&&C(Ue,e.textContent))||e.nodeType===A.processingInstruction||H&&e.nodeType===A.comment&&C(We,e.data))},Rn=function(e,t){return e instanceof RegExp?C(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},zn=function(e,t,n){if(!Tt[t]&&Gn(t)&&Rn(z.tagNameCheck,t))return!1;if(Bt&&!q[t]&&!q[v(t)]){let t=b(e),r=y(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,ge(e))}}}return Z(e),!0},Bn=function(e,t,n,r){return e.length===0?t:t===n||t===r?O(t):t},Vn=function(e,t){return e===t||b(e)!==null?!1:(Vt&&xn(e),!0)},Hn=function(e,n){if(Dn(e),$(I.beforeSanitizeElements,e,null),Vn(e,n))return!0;if(Fn(e))return Z(e),!0;let r=X($e(e));if(L=Bn(I.uponSanitizeElement,L,Ct,Mt),$(I.uponSanitizeElement,e,{tagName:r,allowedTags:L}),Vn(e,n))return!0;if(Ln(e,r))return Z(e),!0;if(Tt[r]||!(B.tagCheck instanceof Function&&B.tagCheck(r))&&!L[r]){let t=zn(e,r,n);return t===!1&&($(I.afterSanitizeElements,e,null),Vn(e,n))?!0:t}if(M(e)===A.element&&!hn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&C(Ge,e.innerHTML))return Z(e),!0;if(V&&e.nodeType===A.text){let n=Mn(e.textContent);e.textContent!==n&&(ae(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(I.afterSanitizeElements,e,null),Vn(e,n)},Un=function(e,t,r){if(Et[t]||On(t,e)||Lt&&(t===`id`||t===`name`)&&(r in n||r in sn))return!1;let i=R[t]||B.attributeCheck instanceof Function&&B.attributeCheck(t,e);return Ot&&C(_t,t)||Dt&&C(vt,t)?!0:i?Gt[t]||C(St,pe(r,bt,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&me(r,`data:`)===0&&Ut[e]||kt&&!C(yt,pe(r,bt,``))?!0:!r:Gn(e)&&Rn(z.tagNameCheck,e)&&Rn(z.attributeNameCheck,t,e)||t===`is`&&z.allowCustomizedBuiltInElements&&Rn(z.tagNameCheck,r)},Wn=D({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),Gn=function(e){return!Wn[v(e)]&&C(xt,e)},Kn=function(e,t,n,r){if(N&&typeof d==`object`&&typeof d.getAttributeType==`function`&&!n)switch(d.getAttributeType(e,t)){case`TrustedHTML`:return F(r);case`TrustedScriptURL`:return ot(r)}return r},qn=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!Fn(e)||(Z(e),!1)}catch{return vn(t,e),!1}},Jn=function(e,t){return H&&C(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t)?!0:v(e)===`attributename`&&fe(t,`href`)!==null},Yn=function(e,n){if($(I.beforeSanitizeAttributes,e,null),Vn(e,n))return;let r=e.attributes;if(!r||Fn(e))return;R=Bn(I.uponSanitizeAttribute,R,wt,Nt);let i={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:R,forceKeepAttr:void 0},a=r.length,o=X(e.nodeName);for(;a--;){let n=r[a],s=n.name,c=n.namespaceURI,l=n.value,u=X(s),d=l,f=s===`value`?d:he(d),p=!1;i.attrName=u,i.attrValue=f,i.keepAttr=!0,i.forceKeepAttr=void 0,$(I.uponSanitizeAttribute,e,i),f=i.attrValue,Rt&&(u===`id`||u===`name`)&&me(f,zt)!==0&&(vn(s,e,n),f=zt+f,p=!0),Jn(s,f)?vn(s,e,n):i.forceKeepAttr||(i.keepAttr?!At&&C(Ke,f)?vn(s,e,n):(V&&(f=Mn(f)),Un(o,u,f)?(f=Kn(o,u,c,f),f!==d&&qn(e,s,c,f)&&p&&ie(t.removed)):vn(s,e,n)):vn(s,e,n))}$(I.afterSanitizeAttributes,e,null),Vn(e,n)},Xn=function(e){let t=null,n=jn(e);for($(I.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(I.uponSanitizeShadowNode,t,null),Hn(t,e),Yn(t,e),Q(t.content)&&Xn(t.content),M(t)===A.element){let e=_e(t);Q(e)&&(Zn(e),Xn(e))}V&&Pn(e),$(I.afterSanitizeShadowDOM,e,null)},Zn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Xn(e.shadow);continue}let n=e.node,r=M(n)===A.element,i=y(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=E?E(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;Q(e)&&t.push({node:e,shadow:null})}}if(r){let e=_e(n);Q(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Yt=!e,Yt&&(e=`<!-->`),typeof e!=`string`&&!In(e)&&(e=ye(e),typeof e!=`string`))throw w(`dirty is not a string, aborting`);if(!t.isSupported)return e;jt?(L=Mt,R=Nt):ln(n),(I.uponSanitizeElement.length>0||I.uponSanitizeAttribute.length>0)&&(L=O(L)),I.uponSanitizeAttribute.length>0&&(R=O(R)),t.removed=[];let c=Vt&&typeof e!=`string`&&In(e),l=[],u=G;if(c){kn(e);let t=$e(e);if(typeof t==`string`){let n=X(t);if(!L[n]||Tt[n])throw _n(e),w(`root node is forbidden and cannot be sanitized in-place`)}if(Fn(e))throw _n(e),w(`root node is clobbered and cannot be sanitized in-place`);l=Sn(e),G=ce()}else if(In(e))i=An(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===A.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Zn(i);else{if(!W&&!V&&!U&&e.indexOf(`<`)===-1)return N&&It?F(e):e;if(i=An(e),!i)return W?null:It?P:``}i&&Pt&&Z(i.firstChild);let d=c?e:i;try{c&&Zn(e);let t=jn(d);for(;o=t.nextNode();)Hn(o,d),Yn(o,d),Q(o.content)&&Xn(o.content);c&&Tn(e,l)}catch(t){throw c&&(_n(e),wn(e,l)),t}finally{G=u}if(c){if(wn(e,l))throw w(`a node selected for removal could not be safely returned; refusing to sanitize in place`);return V&&Nn(e),e}if(W){if(V&&Nn(i),Ft)for(s=dt.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(R.shadowroot||R.shadowrootmode)&&(s=pt.call(r,s,!0)),s}let f=U?i.outerHTML:i.innerHTML;return U&&L[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&C(Ve,i.ownerDocument.doctype.name)&&(f=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
3
|
+
`+f),V&&(f=Mn(f)),N&&It?F(f):f},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ln(e),jt=!0,Mt=L,Nt=R},t.clearConfig=function(){on=null,jt=!1,Mt=null,Nt=null,N=nt,P=``},t.isValidAttribute=function(e,t,n){on||ln({});let r=X(e),i=X(t);return typeof n==`string`&&(Jn(t,n)||!At&&C(Ke,n))?!1:Un(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&x(I,e)&&ae(I[e],t)},t.removeHook=function(e,t){if(x(I,e)){if(t!==void 0){let n=re(I[e],t);return n===-1?void 0:se(I[e],n,1)[0]}return ie(I[e])}},t.removeHooks=function(e){x(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=Xe()},t}var M=Qe();export{M as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));export{s as n,l as r,o as t};
|
package/dist/index.html
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
<title>Canvas editor</title>
|
|
4
4
|
<style>body{margin:0;padding:0}</style>
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
-
<script type="module" crossorigin src="./assets/index-
|
|
7
|
-
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-
|
|
6
|
+
<script type="module" crossorigin src="./assets/index-DODDd0dH.js"></script>
|
|
7
|
+
<link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
|
|
8
8
|
</head>
|
|
9
9
|
<body>
|
|
10
10
|
<div id="root"></div>
|
package/lib/instance.js
CHANGED
|
@@ -940,8 +940,11 @@ export const createInstance = async ({ key, url, useParallelPages = true, browse
|
|
|
940
940
|
await store.waitLoading();
|
|
941
941
|
window.__polotnoThrowAssetErrorIfAny(attrs);
|
|
942
942
|
}
|
|
943
|
-
//
|
|
944
|
-
//
|
|
943
|
+
// Video export forces the GLOBAL flag to 'resize' so text fits
|
|
944
|
+
// properly in animations; the textOverflow option is ignored for
|
|
945
|
+
// now. An element's own textOverflow ('fit', maxLines, size
|
|
946
|
+
// bounds) still applies: the canvas sizes it once from the base
|
|
947
|
+
// attributes and plays the animation on top (D26).
|
|
945
948
|
window.config.setTextOverflow('resize');
|
|
946
949
|
if (!window.__polotnoLoadVideoExport) {
|
|
947
950
|
throw new Error('Video export module loader is not defined in the client. Expected window.__polotnoLoadVideoExport().');
|
package/lib/types.d.ts
CHANGED
|
@@ -11,7 +11,16 @@ export interface RenderOptions {
|
|
|
11
11
|
legacyRichTextEnabled?: boolean;
|
|
12
12
|
/** Vertical text resize + align. On by default; set `false` to disable. */
|
|
13
13
|
textVerticalResizeEnabled?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* The editor's `textSplitAllowed` flag: may text break a word mid-word
|
|
16
|
+
* instead of shrinking, under `'fit'` and the global `'change-font-size'`?
|
|
17
|
+
*/
|
|
14
18
|
textSplitAllowed?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* The global text-overflow flag: 'change-font-size' (the default here),
|
|
21
|
+
* 'resize', 'ellipsis' or 'fit'. A text element's own `textOverflow`,
|
|
22
|
+
* `maxLines`, `minFontSize` and `maxFontSize` apply either way.
|
|
23
|
+
*/
|
|
15
24
|
textOverflow?: string;
|
|
16
25
|
skipFontError?: boolean;
|
|
17
26
|
skipImageError?: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno-node",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.0",
|
|
4
4
|
"description": "Polotno workflow from NodeJS",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
@@ -35,24 +35,24 @@
|
|
|
35
35
|
"@polotno/video-export"
|
|
36
36
|
],
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@polotno/core": "0.
|
|
38
|
+
"@polotno/core": "0.16.0",
|
|
39
39
|
"@polotno/design-fixtures": "0.0.0",
|
|
40
40
|
"@polotno/video-export": "0.4.0",
|
|
41
|
-
"@types/node": "^26.6.
|
|
42
|
-
"dotenv": "^18.0.
|
|
41
|
+
"@types/node": "^26.6.5",
|
|
42
|
+
"dotenv": "^18.0.8",
|
|
43
43
|
"jspdf": "^4.2.1",
|
|
44
|
-
"konva": "^10.
|
|
45
|
-
"mediabunny": "^1.61.
|
|
44
|
+
"konva": "^10.8.0",
|
|
45
|
+
"mediabunny": "^1.61.4",
|
|
46
46
|
"pixelmatch": "^7.2.0",
|
|
47
47
|
"pngjs": "^7.0.0",
|
|
48
|
-
"polotno": "4.
|
|
48
|
+
"polotno": "4.16.0",
|
|
49
49
|
"react": "^19.3.0",
|
|
50
50
|
"react-dom": "^19.3.0",
|
|
51
51
|
"tmp": "^0.2.7",
|
|
52
52
|
"typescript": "~6.0.3",
|
|
53
|
-
"vite": "^8.3.
|
|
54
|
-
"vitest": "^5.0.
|
|
55
|
-
"web-audio-api": "^1.
|
|
53
|
+
"vite": "^8.3.4",
|
|
54
|
+
"vitest": "^5.0.4",
|
|
55
|
+
"web-audio-api": "^1.6.0"
|
|
56
56
|
},
|
|
57
57
|
"overrides": {
|
|
58
58
|
"@polotno/video-export": {
|
|
@@ -62,10 +62,10 @@
|
|
|
62
62
|
},
|
|
63
63
|
"author": "Anton Lavrenov",
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@polotno/schema": "0.
|
|
65
|
+
"@polotno/schema": "0.9.0",
|
|
66
66
|
"@sparticuz/chromium": "^153.0.0",
|
|
67
|
-
"puppeteer": "25.
|
|
68
|
-
"puppeteer-core": "25.
|
|
67
|
+
"puppeteer": "25.14.0",
|
|
68
|
+
"puppeteer-core": "25.14.0"
|
|
69
69
|
},
|
|
70
70
|
"bugs": {
|
|
71
71
|
"url": "https://github.com/polotno-project/polotno-node/issues"
|