@diffusionstudio/core
Version:
2D motion graphics and video rendering engine
17 lines (14 loc) • 332 kB
JavaScript
/*!
* @diffusionstudio/core v3.5.1
* (c) 2025 Diffusion Studio Inc.
*
* Licensed under the Diffusion Studio Non-Commercial License.
* You may NOT use this software for any commercial purposes.
*
* For commercial licensing, visit:
* https://diffusion.studio
*/
(function(S,je){typeof exports=="object"&&typeof module<"u"?je(exports):typeof define=="function"&&define.amd?define(["exports"],je):(S=typeof globalThis<"u"?globalThis:S||self,je(S.core={}))})(this,function(S){"use strict";let je=class Vr{data;format;numberOfChannels;numberOfFrames;sampleRate;timestamp;duration;constructor(e){this.data=e.data,this.format=e.format,this.numberOfChannels=e.numberOfChannels,this.numberOfFrames=e.numberOfFrames,this.sampleRate=e.sampleRate,this.timestamp=e.timestamp||0,this.duration=this.numberOfFrames/this.sampleRate*1e6}copyTo(e,s){if(!s?.format||s.format!=="s16")throw new Error("Only s16 format is supported for copyTo");for(let i=0;i<this.numberOfFrames;i++)for(let r=0;r<this.numberOfChannels;r++){const a=r*this.numberOfFrames+i,n=i*this.numberOfChannels+r,o=Math.max(-1,Math.min(1,this.data[a]));e[n]=Math.round(o*32767)}}clone(){return new Vr({data:new Float32Array(this.data),format:this.format,numberOfChannels:this.numberOfChannels,numberOfFrames:this.numberOfFrames,sampleRate:this.sampleRate,timestamp:this.timestamp})}close(){this.data=new Float32Array(0)}};"AudioData"in window||Object.assign(window,{AudioData:je});const $r=.2,qe=30,Us=1;class _e extends Error{message;code;constructor({message:e="",code:s=""},...i){super(e,...i),console.error(e),this.code=s,this.message=e}}class me extends _e{}class Q extends _e{}class Re extends _e{}class jr extends _e{}class Qe extends _e{}function Ds(t,e=qe){if(e<1)throw new Q({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t*e)}function qr(t,e=qe){if(e<1)throw new Q({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t/e*1e3)/1e3}function mt(t,e=qe){if(e<1)throw new Q({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t/e*1e3)}class P{time;constructor(e=0,s=0,i=0,r=0){this.time=Math.round(e+s*1e3+i*6e4+r*36e5)}get millis(){return this.time}set millis(e){this.time=Math.round(e)}get frames(){return Ds(this.millis/1e3)}set frames(e){this.millis=mt(e)}get seconds(){return this.millis/1e3}set seconds(e){this.millis=e*1e3}addMillis(e){return this.millis=this.millis+e,this}addFrames(e){const s=mt(e);return this.millis=this.millis+s,this}add(e){return new P(e.millis+this.millis)}subtract(e){return new P(this.millis-e.millis)}static fromFrames(e,s){const i=new P;return i.millis=mt(e,s),i}copy(){return new P(this.millis)}toJSON(){return this.millis}static fromJSON(e){return new P(e)}}function Qr(t){return Math.floor(t*255).toString(16).padStart(2,"0").toUpperCase()}function Xr(t,e){return t.reduce((s,i)=>{const r=i[e];return s[r]||(s[r]=[]),s[r].push(i),s},{})}function Xe(t,e){return[t.slice(0,e),t.slice(e)].filter(s=>s.length>0)}function Ke(t,e){return e?Math.floor(Math.random()*(e-t+1)+t):t}async function Kr(t){t<=0||await new Promise(e=>setTimeout(e,t))}function Gr(t){if(!t)throw"Assertion failed!"}function Yr(t,e=300){let s;return(...i)=>{clearTimeout(s),s=setTimeout(()=>{t.apply(t,i)},e)}}function Vs(t,e,s){s<0&&(s=0);const i=t[e];t.splice(e,1),t.splice(s,0,i)}function Jr(){return typeof crypto<"u"?crypto.randomUUID().split("-").at(0):Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}function Zr(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Ns(t){if(t.numberOfChannels===1)return t.getChannelData(0);const e=[];for(let n=0;n<t.numberOfChannels;n++)e.push(t.getChannelData(n));const s=Math.max(...e.map(n=>n.length)),i=new Float32Array(s*t.numberOfChannels);let r=0,a=0;for(;a<s;)e.forEach(n=>{i[r++]=n[a]!==void 0?n[a]:0}),a++;return i}function ft(t,e,s){for(let i=0;i<s.length;i++)t.setUint8(e+i,s.charCodeAt(i))}function Ls(t,e,s){for(let i=0;i<e.length;i++,s+=2){const r=Math.max(-1,Math.min(1,e[i]));t.setInt16(s,r<0?r*32768:r*32767,!0)}return t}function ea(t,e,s){const a=e*2,n=8,o=36,c=t.length*2,l=o+c,h=new ArrayBuffer(n+l),d=new DataView(h);return ft(d,0,"RIFF"),d.setUint32(4,l,!0),ft(d,8,"WAVE"),ft(d,12,"fmt "),d.setUint32(16,16,!0),d.setUint16(20,1,!0),d.setUint16(22,e,!0),d.setUint32(24,s,!0),d.setUint32(28,s*a,!0),d.setUint16(32,a,!0),d.setUint16(34,16,!0),ft(d,36,"data"),d.setUint32(40,c,!0),Ls(d,t,n+o)}function ta(t,e="audio/wav"){const s=Ns(t),i=ea(s,t.numberOfChannels,t.sampleRate);return new Blob([i],{type:e})}function sa(t){const e=new Float32Array(t.length*t.numberOfChannels);let s=0;for(let i=0;i<t.numberOfChannels;i++){const r=t.getChannelData(i);e.set(r,s),s+=r.length}return e}function ia(t){const e=t.numberOfChannels,s=t.length,i=new Int16Array(s*e);for(let r=0;r<s;r++)for(let a=0;a<e;a++){let n=t.getChannelData(a)[r]*32767;n>32767&&(n=32767),n<-32767&&(n=-32767),i[r*e+a]=n}return i}async function ra(t,e=22050,s=Math.sqrt(2)){const i=await t.arrayBuffer(),r=new OfflineAudioContext({sampleRate:e,length:1}),a=await r.decodeAudioData(i),n=r.createBuffer(1,a.length,e);if(a.numberOfChannels>=2){const o=a.getChannelData(0),c=a.getChannelData(1),l=n.getChannelData(0);for(let h=0;h<a.length;++h)l[h]=s*(o[h]+c[h])/2;return n}return a}function aa(t,e=44100,s=2){if(t.sampleRate==e&&t.numberOfChannels==s)return t;const i=Math.floor(t.duration*e),a=new OfflineAudioContext(s,1,e).createBuffer(s,i,e);for(let n=0;n<t.numberOfChannels;n++){const o=t.getChannelData(n),c=a.getChannelData(n),l=t.sampleRate/e;for(let h=0;h<c.length;h++){const d=h*l,u=Math.floor(d),f=Math.ceil(d);if(f>=o.length)c[h]=o[u];else{const p=d-u;c[h]=o[u]*(1-p)+o[f]*p}}}return a}async function Vt(t,e){const s=document.createElement("a");if(document.head.appendChild(s),s.target="_blank",e?s.download=e:t instanceof File?s.download=t.name:t instanceof Blob?s.download="untitled":typeof t=="string"&&(s.download=t.split("/").pop()??"untitled"),typeof t=="string"&&t.startsWith("data:image/svg+xml;base64,")){const i=t.split(",")[1],r=atob(i),a=new Array(r.length);for(let c=0;c<r.length;c++)a[c]=r.charCodeAt(c);const n=new Uint8Array(a),o=new Blob([n],{type:"image/svg+xml"});s.href=URL.createObjectURL(o),s.download=e?.split(".")[0]+".svg"}else typeof t=="string"?s.href=t:s.href=URL.createObjectURL(t);s.click(),s.remove()}async function na(t,e=!0){return new Promise(s=>{const i=document.createElement("input");i.type="file",i.accept=t,i.multiple=e,i.onchange=r=>{const a=Array.from(r.target?.files??[]);s(a)},i.click()})}function F(t){if(!t)return new P(0);if(typeof t=="number")return P.fromFrames(t);if(t instanceof P)return t;const e=t.split(":");if(e.length===3){const[s,i,r]=e.map(Number);if(isNaN(s)||isNaN(i)||isNaN(r))throw new Error(`Invalid time format: ${t}`);return new P(0,r,i,s)}if(e.length===2){const[s,i]=e.map(Number);if(isNaN(s)||isNaN(i))throw new Error(`Invalid time format: ${t}`);return new P(0,i,s)}if(typeof t=="string"){const s=parseFloat(t);if(isNaN(s))throw new Error(`Invalid time format: ${t}`);if(t.endsWith("ms"))return new P(s);if(t.endsWith("s"))return new P(0,s);if(t.endsWith("f"))return P.fromFrames(s);if(t.endsWith("min"))return new P(0,0,s);throw new Error(`Invalid time format: ${t}`)}throw new Error(`Invalid time format: ${t}`)}async function oa(t){const{fps:e,height:s,width:i,bitrate:r}=t,a=["avc1.640033","avc1.4d4033","avc1.424033","avc1.640029","avc1.4d4029","avc1.424029"],n=["prefer-hardware","prefer-software"],o=[];for(const l of a)for(const h of n)o.push({codec:l,hardwareAcceleration:h,width:i,height:s,bitrate:r,framerate:e});const c=[];if("VideoEncoder"in window){for(const l of o){const h=await VideoEncoder.isConfigSupported(l);h.supported&&c.push(h.config??l)}return c.sort(ca)[0].codec}}function ca(t,e){const s=t.hardwareAcceleration??"",i=e.hardwareAcceleration??"";return s<i?-1:s>i?1:0}function Ws(t){return`${t.hours.toString().padStart(2,"0")}:${t.minutes.toString().padStart(2,"0")}:${t.seconds.toString().padStart(2,"0")},`+t.milliseconds.toString().padStart(3,"0")}function Hs(t){const e=new Date(1970,0,1);return e.setSeconds(t),e.setMilliseconds(Math.round(t%1*1e3)),{hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds(),milliseconds:e.getMilliseconds()}}class Fe{words=[];constructor(e){e&&(this.words=e)}get duration(){return this.stop.subtract(this.start)}get text(){return this.words.map(({text:e})=>e).join(" ")}get start(){return this.words.at(0)?.start??new P}get stop(){return this.words.at(-1)?.stop??new P}}var pt=(t=>(t.en="en",t.de="de",t))(pt||{});class gt{id=crypto.randomUUID();text;start;stop;confidence;constructor(e,s,i,r){this.text=e,this.start=new P(s),this.stop=new P(i),this.confidence=r}get duration(){return this.stop.subtract(this.start)}}class ie{id=crypto.randomUUID();language=pt.en;groups=[];get text(){return this.groups.map(({text:e})=>e).join(" ")}get words(){return this.groups.flatMap(({words:e})=>e)}constructor(e=[],s=pt.en){this.groups=e,this.language=s}*iter({count:e,duration:s,length:i}){for(const r of this.groups){let a;for(const[n,o]of r.words.entries())a&&(e&&a.words.length>=Ke(...e)?(yield a,a=void 0):s&&a?.duration.seconds>=Ke(...s)?(yield a,a=void 0):i&&a.text.length>=Ke(...i)&&(yield a,a=void 0)),a?a.words.push(o):a=new Fe([o]),n==r.words.length-1&&(yield a)}}optimize(){const e=this.groups.flatMap(s=>s.words);for(let s=0;s<e.length-1;s++){const i=e[s],r=e[s+1];r.start.millis-i.stop.millis<0?r.start.millis=i.stop.millis+1:i.stop.millis=r.start.millis-1}return this}toSRT(e={}){let s=1,i="";for(const r of this.iter(e)){const a=Hs(r.start.seconds),n=Hs(r.stop.seconds);i+=`${s}
`+Ws(a)+" --> "+Ws(n)+`
${r.text}
`,s+=1}return{text:i,blob:new Blob([i],{type:"text/plain;charset=utf8"})}}toJSON(){return this.groups.map(e=>e.words.map(s=>({token:s.text,start:s.start.millis,stop:s.stop.millis})))}slice(e,s=!0){let i=0;const r=[];for(const a of this.groups)for(const n of a.words)if(r.length==0&&s&&(i=n.start.millis),r.push(new gt(n.text,n.start.millis-i,n.stop.millis-i)),r.length==e)return new ie([new Fe(r)]);return new ie([new Fe(r)])}copy(){return ie.fromJSON(this.toJSON())}static fromJSON(e){const s=new ie;for(const i of e){const r=new Fe;for(const a of i)r.words.push(new gt(a.token,a.start,a.stop));s.groups.push(r)}return s}static async from(e){if(Array.isArray(e))return ie.fromJSON(e);if(e instanceof Blob)return ie.fromJSON(JSON.parse(await e.text()));const s=await fetch(e);if(!s.ok)throw new me({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return ie.fromJSON(await s.json())}}class Te{id=crypto.randomUUID();toJSON(){const e={};return(this.constructor.__serializableProperties||[]).forEach(({propertyKey:i,serializer:r})=>{const a=this[i];r&&a instanceof r?e[i]=a.toJSON():e[i]=a}),e}static fromJSON(e){const s=new this;return(this.__serializableProperties||[]).forEach(({propertyKey:r,serializer:a})=>{if(e.hasOwnProperty(r))if(a){const n=a.fromJSON(e[r]);s[r]=n}else s[r]=e[r]}),s}}function E(t){return function(e,s){e.constructor.__serializableProperties||(e.constructor.__serializableProperties=[]),e.constructor.__serializableProperties.push({propertyKey:s,serializer:t})}}function Oe(t){return class extends t{_handlers={};on(s,i){if(typeof i!="function")throw new Error("The callback of an event listener needs to be a function.");const r=crypto.randomUUID();return this._handlers[s]?this._handlers[s][r]=i:this._handlers[s]={[r]:i},r}off(s,...i){if(s){if(s==="*"){this._handlers={};return}for(const r of Object.values(this._handlers))s in r&&delete r[s];for(const r of i)this.off(r)}}emit(s,i){const r=new CustomEvent(s,{detail:i});Object.defineProperty(r,"currentTarget",{writable:!1,value:this});for(const a in this._handlers[s]??{})this._handlers[s]?.[a](r);for(const a in this._handlers["*"]??{})this._handlers["*"]?.[a](r)}bubble(s){return this.on("*",i=>{s.emit(i.type,i.detail)})}resolve(s){return(i,r)=>{this.on("error",r),this.on(s,i)}}}}class wt extends Oe(Te){_key;_value;_store;loaded=!1;constructor(e,s,i){super(),this._store=e,this._key=s,this.initValue(i)}get key(){return this._key}get value(){return this._value}set value(e){this._value=e,this._store.set(this._key,e),this.emit("update",void 0)}async initValue(e){e instanceof Promise?this._value=await e:this._value=e,this.loaded=!0,this.emit("update",void 0)}}class la{storageEngine;namespace;constructor(e,s=localStorage){this.storageEngine=s,this.namespace=e}define(e,s,i){const r=this.get(e);return r===null?(this.set(e,s),new wt(this,e,s)):i&&r!=null?new wt(this,e,i(r)):new wt(this,e,r)}set(e,s){this.storageEngine.setItem(this.getStorageId(e),JSON.stringify({value:s}))}get(e){const s=this.storageEngine.getItem(this.getStorageId(e));return s?JSON.parse(s).value:null}remove(e){this.storageEngine.removeItem(this.getStorageId(e))}getStorageId(e){return this.namespace?`${this.namespace}.${e}`:e}}function Nt(){return class extends Oe(class{}){}}function da(t,e){return e=="lower"?t.toLocaleLowerCase():e=="upper"?t.toUpperCase():t}function ve(t="#000000",e=100){return`${t}${Math.round(e/100*255).toString(16)}`}function C(t,e){return typeof t=="number"?t:Number.parseFloat(t.replace("%",""))*e/100}function ha(t){const e=t.startsWith("#")?t.slice(1):t,s=parseInt(e,16),i=s>>16&255,r=s>>8&255,a=s&255;return{r:i,g:r,b:a}}function ua(t,e,s){return`#${((1<<24)+(Math.round(t)<<16)+(Math.round(e)<<8)+Math.round(s)).toString(16).slice(1)}`}function Lt(t,e){switch(e){case"ease-in":return t*t;case"ease-out":return t*(2-t);case"ease-in-out":return t<.5?2*t*t:-1+(4-2*t)*t;case"ease-out-in":if(t<.5){const s=t*2;return s*(2-s)/2}else{const s=(t-.5)*2;return s*s/2+.5}default:return t}}function Ge(t,e,s){return t+(e-t)*s}function $s(t){const e=ha(t);return ma(e.r,e.g,e.b)}function ma(t,e,s){t/=255,e/=255,s/=255;const i=Math.max(t,e,s),r=Math.min(t,e,s);let a=0,n=0;const o=(i+r)/2;if(i!==r){const c=i-r;switch(n=o>.5?c/(2-i-r):c/(i+r),i){case t:a=(e-s)/c+(e<s?6:0);break;case e:a=(s-t)/c+2;break;case s:a=(t-e)/c+4;break}a/=6}return{h:Math.round(a*360),s:Math.round(n*100),l:Math.round(o*100)}}function fa(t,e,s){e/=100,s/=100,t=(t+360)%360;function i(l,h,d){return d<0&&(d+=1),d>1&&(d-=1),d<1/6?l+(h-l)*6*d:d<1/2?h:d<2/3?l+(h-l)*(2/3-d)*6:l}const r=s<.5?s*(1+e):s+e-s*e,a=2*s-r,n=i(a,r,t/360+1/3),o=i(a,r,t/360),c=i(a,r,t/360-1/3);return ua(Math.round(n*255),Math.round(o*255),Math.round(c*255))}function pa(t,e){const{frames:s,extrapolate:i="clamp",easing:r}=t;if(e.millis<=F(s[0].time).millis)return s[0].value;if(e.millis>=F(s[s.length-1].time).millis)return s[s.length-1].value;let a,n;for(let f=0;f<s.length-1;f++)if(e.millis>=F(s[f].time).millis&&e.millis<=F(s[f+1].time).millis){a=s[f],n=s[f+1];break}if(!a||!n)throw new Error("Unexpected error in keyframe interpolation");const o=(e.millis-F(a.time).millis)/(F(n.time).millis-F(a.time).millis),c=Lt(o,a.easing??r),l=$s(a.value),h=$s(n.value);let d=l.h,u=h.h;return Math.abs(u-d)>180&&(d<u?d+=360:u+=360),fa(Ge(d,u,c),Ge(l.s,h.s,c),Ge(l.l,h.l,c))}function js(t,e){const{frames:s,extrapolate:i="clamp",easing:r}=t;if(e.millis<=F(s[0].time).millis)return s[0].value;if(e.millis>=F(s[s.length-1].time).millis)return s[s.length-1].value;let a,n;for(let l=0;l<s.length-1;l++)if(e.millis>=F(s[l].time).millis&&e.millis<=F(s[l+1].time).millis){a=s[l],n=s[l+1];break}if(!a||!n)throw new Error("Unexpected error in keyframe interpolation");const o=(e.millis-F(a.time).millis)/(F(n.time).millis-F(a.time).millis),c=Lt(o,a.easing??r);return typeof a.value=="number"&&typeof n.value=="number"?Ge(a.value,n.value,c):`${Ge(qs(a.value),qs(n.value),c)}%`}function qs(t){return typeof t=="number"?t:Number(t.replace("%",""))}function ga(t,e){const{frames:s,extrapolate:i="clamp"}=t;if(e.millis<=F(s[0].time).millis)return s[0].value;if(e.millis>=F(s[s.length-1].time).millis)return s[s.length-1].value;let r,a;for(let d=0;d<s.length-1;d++)if(e.millis>=F(s[d].time).millis&&e.millis<=F(s[d+1].time).millis){r=s[d],a=s[d+1];break}if(!r||!a)throw new Error("Unexpected error in keyframe interpolation");const n=(e.millis-F(r.time).millis)/(F(a.time).millis-F(r.time).millis),o=Lt(n,r.easing),c=a.value,l=c.length,h=Math.floor(o*l);return c.slice(0,h)}class yt extends Te{width;height;fillRule;animations=[];clip;renderer;constructor({width:e=100,height:s=100}={}){super(),this.width=e,this.height=s}connect(e){return this.clip=e,this}draw(e){return this.renderer=e,new Path2D}animate(e){for(const s of this.animations){const i=s?.frames[0].value;(typeof i=="number"||typeof i=="string"&&i.match(/^[0-9]+(\.[0-9]+)?%$/))&&(this[s.key]=js(s,e.subtract(this.start)))}return this}get start(){return this.clip?.start??new P}get stop(){return this.clip?.stop??new P}get size(){return{width:C(this.width,this.renderer?.width??0),height:C(this.height,this.renderer?.height??0)}}get bounds(){const{width:e,height:s}=this.size;return[{x:0,y:0},{x:e,y:0},{x:e,y:s},{x:0,y:s}]}detach(){return this.clip&&(this.clip.mask=void 0,this.clip=void 0),this}}class wa extends yt{cx;cy;constructor({cx:e=0,cy:s=0,radius:i,animations:r,...a}={}){super(a),this.cx=e,this.cy=s,i&&(this.radius=i),this.animations=r??[]}set x(e){this.cx=e}set y(e){this.cy=e}get x(){return this.cx}get y(){return this.cy}get radius(){const e=this.size;return Math.min(e.width,e.height)*.5}set radius(e){typeof e=="number"?(this.height=e*2,this.width=e*2):(this.height=`${Number(e.replace("%",""))*2}%`,this.width=`${Number(e.replace("%",""))*2}%`)}draw(e){const s=super.draw(e);return s.ellipse(C(this.cx,e.width)*e.resolution,C(this.cy,e.height)*e.resolution,C(this.width,e.width)*e.resolution*.5,C(this.height,e.height)*e.resolution*.5,0,0,2*Math.PI),s}get bounds(){const{width:e,height:s}=this.size,{cx:i,cy:r}=this,a=C(i,this.renderer?.width??0)-e*.5,n=C(r,this.renderer?.height??0)-s*.5;return[{x:a,y:n},{x:a+e,y:n},{x:a+e,y:n+s},{x:a,y:n+s}]}}class ya extends yt{x;y;radius;constructor({x:e=0,y:s=0,radius:i=0,animations:r,...a}={}){super(a),this.x=e,this.y=s,this.radius=i,this.animations=r??[]}draw(e){const s=super.draw(e);if(this.radius){const i=C(this.width,e.width),r=C(this.height,e.height),a=C(this.radius,Math.min(i,r));s.roundRect(C(this.x,e.width)*e.resolution,C(this.y,e.height)*e.resolution,i*e.resolution,r*e.resolution,a*e.resolution)}else s.rect(C(this.x,e.width)*e.resolution,C(this.y,e.height)*e.resolution,C(this.width,e.width)*e.resolution,C(this.height,e.height)*e.resolution);return s}get bounds(){return super.bounds.map(e=>({x:e.x+C(this.x,this.renderer?.width??0),y:e.y+C(this.y,this.renderer?.height??0)}))}}class Wt{canvas=document.createElement("canvas");context=this.canvas.getContext("2d");resolution=1;width=1920;height=1080;background="#000000";constructor({width:e=1920,height:s=1080,background:i="#000000",resolution:r=1}={}){this.canvas.style.background=i,this.resolution=r,this.background=i,this.resize(e,s)}resize(e,s){return this.width=Math.round(e),this.height=Math.round(s),this.canvas.width=Math.round(this.width*this.resolution),this.canvas.height=Math.round(this.height*this.resolution),this.context.imageSmoothingEnabled=!1,this}clear(e){let s=0,i=0,r=this.width*this.resolution,a=this.height*this.resolution;return this.context.fillStyle=this.background,e&&(s=C(e.x??0,this.width)*this.resolution,i=C(e.y??0,this.height)*this.resolution,r=C(e.width,this.width)*this.resolution,a=C(e.height,this.height)*this.resolution),this.context.clearRect(s,i,r,a),this.context.fillRect(s,i,r,a),this}rect(e){if(this.context.beginPath(),e.radius){const s=C(e.width,this.width),i=C(e.height,this.height),r=Math.max(C(e.radius,Math.min(s,i)),0);this.context.roundRect(C(e.x??0,this.width)*this.resolution|0,C(e.y??0,this.height)*this.resolution|0,s*this.resolution|0,i*this.resolution|0,r*this.resolution|0)}else this.context.rect(C(e.x??0,this.width)*this.resolution|0,C(e.y??0,this.height)*this.resolution|0,C(e.width,this.width)*this.resolution|0,C(e.height,this.height)*this.resolution|0);return this.context.closePath(),this}circle(e){return this.context.beginPath(),"height"in e?this.context.ellipse(C(e.cx,this.width)*this.resolution|0,C(e.cy,this.height)*this.resolution|0,C(e.width,this.width)*this.resolution|0,C(e.height,this.height)*this.resolution|0,0,0,Math.PI*2):this.context.arc(C(e.cx,this.width)*this.resolution|0,C(e.cy,this.height)*this.resolution|0,C(e.radius,Math.min(this.width,this.height)*.5)*this.resolution|0,0,Math.PI*2),this.context.closePath(),this}image(e,s){const{x:i=0,y:r=0,width:a,height:n,rotation:o}=s,c=C(i,this.width)*this.resolution|0,l=C(r,this.height)*this.resolution|0,h=C(a,this.width)*this.resolution|0,d=C(n,this.height)*this.resolution|0;if(o!==void 0&&o!==0){this.context.save(),this.context.translate(c+h/2,l+d/2);const u=o*Math.PI/180;this.context.rotate(u);const f=Math.abs(o%180)===90;this.context.drawImage(e,(f?-d/2:-h/2)|0,(f?-h/2:-d/2)|0,(f?d:h)|0,(f?h:d)|0),this.context.restore()}else this.context.drawImage(e,c,l,h,d);return this}clip(e,s){return e instanceof yt?this.context.clip(e.draw(this),e.fillRule):e&&this.context.clip(e,s),this}opacity(e){return this.context.globalAlpha=e/100,this}transform(e){return e?(e.translate&&this.context.translate(C(e.translate.x,this.width)*this.resolution|0,C(e.translate.y,this.height)*this.resolution|0),e.rotate&&this.context.rotate(e.rotate*Math.PI/180),e.scale&&this.context.scale(C(e.scale.x,this.width),C(e.scale.y,this.height)),this):(this.context.setTransform(1,0,0,1,0,0),this)}blendMode(e){return e&&(this.context.globalCompositeOperation=e),this}save(){return this.context.save(),this}restore(){return this.context.restore(),this}filter(e){return e?(this.context.filter=e,this):this}fill(e,s=!1){if(!e)return this.context.fillStyle="transparent",this;if(typeof e.color=="string")this.context.fillStyle=ve(e.color,e.opacity);else if("type"in e.color){const i=this.createGradient(e.color);this.context.fillStyle=i}else if("image"in e.color){const i=this.context.createPattern(e.color.image,e.color.repetition);this.context.fillStyle=i??""}return s&&this.context.fill(),this}shadow(e){return e?(this.context.fillStyle=this.context.shadowColor=ve(e.color,e.opacity),this.context.shadowOffsetX=(e.offsetX??0)*this.resolution*this.textScale,this.context.shadowOffsetY=(e.offsetY??0)*this.resolution*this.textScale,this.context.shadowBlur=(e.blur??24)*this.resolution*this.textScale,this):(this.context.shadowColor="transparent",this.context.shadowBlur=0,this.context.shadowOffsetX=0,this.context.shadowOffsetY=0,this)}stroke(e,s=!1){return e?(this.context.strokeStyle=ve(e.color,e.opacity),this.context.lineWidth=(e.width??1)*this.resolution*this.textScale,e.lineCap&&(this.context.lineCap=e.lineCap),e.lineJoin&&(this.context.lineJoin=e.lineJoin),e.miterLimit&&(this.context.miterLimit=e.miterLimit),s&&this.context.stroke(),this):(this.context.strokeStyle="transparent",this.context.lineWidth=0,this.context.lineCap="butt",this.context.lineJoin="miter",this.context.miterLimit=10,this)}mount(e){e.appendChild(this.canvas)}unmount(){this.canvas.parentElement?.removeChild(this.canvas)}createGradient(e){let s;return e.type==="linear"?s=this.context.createLinearGradient(0,0,this.canvas.width,0):s=this.context.createRadialGradient(this.canvas.width/2,this.canvas.height/2,0,this.canvas.width/2,this.canvas.height/2,this.canvas.width/2),e.stops.forEach(i=>{s.addColorStop(i.offset,i.color)}),s}watermark(e){!e||!this.watermark.length||(this.context.save(),this.context.font=`${46*this.resolution}px Verdana`,this.context.fillStyle="#ffffff",this.context.textAlign="center",this.context.textBaseline="middle",this.context.strokeStyle="#000000",this.context.lineWidth=8*this.resolution,this.context.strokeText(e,this.width*this.resolution*.5,this.height*this.resolution*.9),this.context.fillText(e,this.width*this.resolution*.5,this.height*this.resolution*.9),this.context.restore())}textScale=4;text(e){return e.font&&(this.context.font=this.createFontString(e.font.style,e.font.weight,e.font.size*this.resolution,e.font.family)),e.color&&(this.context.fillStyle=e.color),e.alignment&&(this.context.textAlign=e.alignment),e.baseline&&(this.context.textBaseline=e.baseline),this}strokeText(e,s){return this.context.strokeText(e,C(s.x,this.width)*this.resolution,C(s.y,this.height)*this.resolution),this}fillText(e,s){return this.context.fillText(e,C(s.x,this.width)*this.resolution,C(s.y,this.height)*this.resolution),this}measureText(e,s){return this.context.font=this.createFontString(s.style,s.weight,s.size,s.family),this.context.measureText(e)}createFontString(e,s,i,r){return`${e??"normal"} ${s??"400"} ${(i??16)*this.textScale}px ${r??"Arial"}`.trim()}}class Ht{context;hardwareOffset=0;playbackOffset=0;playbackFps=qe;inactiveFps=Us;playing=!1;stopped=!0;duration;lastFrameTime=0;constructor(e={}){this.callback=e.callback,this.context=e.context??new AudioContext,this.playbackFps=e.fps??30}get hardwareTime(){return this.context.currentTime}get playbackTime(){return this.playing?this.hardwareTime-this.hardwareOffset+this.playbackOffset:this.playbackOffset}get playbackTimestamp(){return new P(0,this.playbackTime)}get playbackFrame(){return Math.floor(this.playbackTime*this.playbackFps)}start(){this.stopped&&(this.stopped=!1,this.timer())}stop(){this.stopped=!0}async play(){this.playing||this.stopped||(this.resumeAudioContext(),this.hardwareOffset=this.hardwareTime,this.playing=!0)}async pause(){this.playing&&(this.playbackOffset=this.playbackTime,this.playing=!1)}async timer(e=0){if(this.stopped)return;const i=1e3/(this.playing?this.playbackFps:this.inactiveFps);e-this.lastFrameTime>=i&&(this.lastFrameTime=e,await this.callback?.()),requestAnimationFrame(this.timer.bind(this))}async resumeAudioContext(){this.context.state==="suspended"&&await this.context.resume()}}function ba(t){const e=new P;for(const s of t)s.disabled||s.stop.frames>e.frames&&(e.frames=s.stop.frames);return e}var ka=Object.defineProperty,Me=(t,e,s,i)=>{for(var r=void 0,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=n(e,s,r)||r);return r&&ka(e,s,r),r};const xe=class Nr extends Oe(Te){_name;_delay=new P;_duration=new P(0,16);data={};initialized=!1;type="base";source;rendered=!1;createdAt=new Date;disabled=!1;animations=[];layer;input;get name(){return this._name??this.source?.name}set name(e){this._name=e}get start(){return this._delay}get stop(){return this._delay.add(this._duration)}get delay(){return this._delay}get duration(){return this._duration}constructor(e={}){super(),Object.assign(this,e)}animate(e){return this}async connect(e){this.layer=e,this.emit("attach",void 0)}set delay(e){this._delay=F(e),this.emit("frame",this._delay.frames)}set duration(e){this._duration=F(e),this._duration.millis<=0&&(this._duration.frames=1),this.emit("frame",this._duration.frames)}offset(e){return e=F(e),this.delay.addMillis(e.millis),this.emit("offset",e),this.emit("frame",void 0),this}async init(e){}async enter(e){}async update(e){}render(e){}async exit(e){}async seek(e){}async play(e){}async pause(e){}detach(){return this.layer?.remove(this),this}cleanup(){this.off("*")}trim(e=this.start,s=this.stop){return e=F(e),s=F(s),this.delay=e,this.duration=s.subtract(e),this}async split(e){if(e=F(e??this.layer?.composition?.audio.playbackFrame),!e||e.millis<=this.start.millis||e.millis>=this.stop.millis)throw new Q({code:"split_out_of_range",message:"Cannot split clip at the specified time"});if(!this.layer)throw new Q({code:"layer_not_attached",message:"Layer must be attached to a layer"});const s=this.animate(e).copy();this.duration=e.subtract(this.delay),s.trim(e.addMillis(1),s.stop),s.animations=[];const i=this.layer.clips.findIndex(r=>r.id==this.id);return await this.layer.add(s,i+1),s}copy(){return Nr.fromJSON(JSON.parse(JSON.stringify(this)))}};Me([E()],xe.prototype,"_name"),Me([E(P)],xe.prototype,"_delay"),Me([E(P)],xe.prototype,"_duration"),Me([E()],xe.prototype,"data"),Me([E()],xe.prototype,"disabled"),Me([E()],xe.prototype,"animations");let fe=xe;class bt{data={};id=crypto.randomUUID();type="base";mimeType;input;name;constructor(e){this.input=e.input,this.mimeType=e.mimeType,e.name?this.name=e.name:typeof this.input=="string"?this.name=this.input.split("/").at(-1)??"":this.input instanceof File?this.name=this.input.name:this.name="UNTITLED_BLOB"}async init(e={}){}async arrayBuffer(){return typeof this.input=="string"?await(await fetch(this.input)).arrayBuffer():await this.input.arrayBuffer()}async download(){Vt(this.input,this.name)}async thumbnail(){return document.createElement("div")}}function kt(t){class e extends t{height=1080;width=1920;get aspectRatio(){return this.width/this.height}}return e}async function Qs(t){if(t instanceof Blob)return t.type;if(t.startsWith("<html>"))return"text/html";let e;try{e=await fetch(t,{method:"HEAD"})}catch{console.info("Using AbortController fallback");const r=new AbortController;e=await fetch(t,{signal:r.signal}),r.abort()}if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);const s=e.headers.get("Content-Type");if(!s)throw new me({message:"No content type found",code:"no_content_type_found"});return s}function m(t){if(!t)throw new Error("Assertion failed.")}var $t=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},N=t=>t&&t[t.length-1],Ae=t=>t>=0&&t<2**32,_=(t,e,s)=>{let i=0;for(let r=e;r<s;r++){const a=Math.floor(r/8),n=t[a],o=7-(r&7),c=(n&1<<o)>>o;i<<=1,i|=c}return i},Sa=(t,e,s,i)=>{for(let r=e;r<s;r++){const a=Math.floor(r/8);let n=t[a];const o=7-(r&7);n&=~(1<<o),n|=(i&1<<s-r-1)>>s-r-1<<o,t[a]=n}},J=t=>t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength),Ce=t=>t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength),le=new TextEncoder,jt=t=>Object.fromEntries(Object.entries(t).map(([e,s])=>[s,e])),ze={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Xs=jt(ze),Be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},Ks=jt(Be),Ue={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Gs=jt(Ue),Ys=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,St=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView),Tt=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let t;const e=new Promise(i=>{t=i}),s=this.currentPromise;return this.currentPromise=e,await s,t}},Ta=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),va=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0),W=(t,e,s)=>{let i=0,r=t.length-1,a=-1;for(;i<=r;){const n=i+r>>1,o=s(t[n]);o===e?(a=n,r=n-1):o<e?i=n+1:r=n-1}return a},B=(t,e,s)=>{let i=-1,r=0,a=t.length-1;for(;r<=a;){const n=r+(a-r+1)/2|0;s(t[n])<=e?(i=n,r=n+1):a=n-1}return i},K=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},xa=(t,e)=>{const s=t.indexOf(e);s!==-1&&t.splice(s,1)},Js=(t,e)=>{for(let s=t.length-1;s>=0;s--)if(e(t[s]))return t[s]},Zs=(t,e)=>{for(let s=t.length-1;s>=0;s--)if(e(t[s]))return s;return-1},Ca=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},Ia=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},ei=(t,e,s)=>{const i=t.getUint8(e),r=t.getUint8(e+1),a=t.getUint8(e+2);return s?i|r<<8|a<<16:i<<16|r<<8|a},Ea=(t,e,s)=>ei(t,e,s)<<8>>8,ti=(t,e,s,i)=>{s=s>>>0,s=s&16777215,i?(t.setUint8(e,s&255),t.setUint8(e+1,s>>>8&255),t.setUint8(e+2,s>>>16&255)):(t.setUint8(e,s>>>16&255),t.setUint8(e+1,s>>>8&255),t.setUint8(e+2,s&255))},Pa=(t,e,s,i)=>{s=G(s,-8388608,8388607),s<0&&(s=s+16777216&16777215),ti(t,e,s,i)},_a=(t,e,s,i)=>{t.setUint32(e+0,s,!0),t.setInt32(e+4,Math.floor(s/2**32),!0)},si=(t,e)=>({async next(){const s=await t.next();return s.done?{value:void 0,done:!0}:{value:e(s.value),done:!1}},return(){return t.return()},throw(s){return t.throw(s)},[Symbol.asyncIterator](){return this}}),G=(t,e,s)=>Math.max(e,Math.min(s,t)),de="und",qt=(t,e)=>{const s=10**e;return Math.round(t*s)/s},Ra=(t,e)=>Math.round(t/e)*e,Fa=t=>{let e=0;for(;t;)e++,t>>=1;return e},Oa=/^[a-z]{3}$/,Qt=t=>Oa.test(t),pe=1e6*(1+Number.EPSILON),Xt=(t,e)=>{const s={...t};for(const i in e)typeof t[i]=="object"&&t[i]!==null&&typeof e[i]=="object"&&e[i]!==null?s[i]=Xt(t[i],e[i]):s[i]=e[i];return s},ii=async(t,e,s)=>{let i=0;for(;;)try{return await fetch(t,e)}catch(r){console.error("Retrying failed fetch. Error:",r),i++;const a=s(i);if(a===null)throw r;if(!Number.isFinite(a)||a<0)throw new TypeError("Retry delay must be a non-negative finite number.");a>0&&await new Promise(n=>setTimeout(n,1e3*a))}},Ma=class{static supports(t,e){return!1}},ri=class{static supports(t,e){return!1}},ai=[],ni=[],vt=[],xt=[],Aa=t=>{if(t.prototype instanceof Ma)vt.push(t);else if(t.prototype instanceof ri)xt.push(t);else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")},te=["avc","hevc","vp9","av1","vp8"],H=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-u8","pcm-s8","ulaw","alaw"],Kt=["aac","opus","mp3","vorbis","flac"],re=[...Kt,...H],ge=["webvtt"],oi=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],ci=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],we=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],li=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],za=".01.01.01.01.00",Ba=".0.110.01.01.01.0",Gt=(t,e,s,i)=>{if(t==="avc"){const a=Math.ceil(e/16)*Math.ceil(s/16),n=oi.find(d=>a<=d.maxMacroblocks&&i<=d.maxBitrate)??N(oi),o=n?n.level:0,c="64".padStart(2,"0"),l="00",h=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${h}`}else if(t==="hevc"){const r="",n="6",o=e*s,c=ci.find(h=>o<=h.maxPictureSize&&i<=h.maxBitrate)??N(ci);return`hev1.${r}1.${n}.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const r="00",a=e*s,n=we.find(c=>a<=c.maxPictureSize&&i<=c.maxBitrate)??N(we);return`vp09.${r}.${n.level.toString().padStart(2,"0")}.08${za}`}else if(t==="av1"){const a=e*s,n=li.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??N(li);return`av01.0.${n.level.toString().padStart(2,"0")}${n.tier}.08${Ba}`}}throw new TypeError(`Unhandled codec '${t}'.`)},Ua=t=>{const e=t.split("."),s=Number(e[1]),i=Number(e[2]),r=Number(e[3]),a=e[4]?Number(e[4]):1;return[1,1,s,2,1,i,3,1,r,4,1,a]},di=t=>{const e=t.split("."),r=(1<<7)+1,a=Number(e[1]),n=e[2],o=Number(n.slice(0,-1)),c=(a<<5)+o,l=n.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,u=0,f=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,k=(l<<7)+(d<<6)+(u<<5)+(f<<4)+(p<<3)+(g<<2)+b;return[r,c,k,0]},hi=t=>{const{codec:e,codecDescription:s,colorSpace:i,vp9CodecInfo:r,av1CodecInfo:a}=t;if(e==="avc"){if(!s||s.byteLength<4)throw new TypeError("AVC description must be at least 4 bytes long.");return`avc1.${Ta(s.subarray(1,4))}`}else if(e==="hevc"){if(!s)throw new TypeError("HEVC description must be provided.");const n=Ce(s);let o="hev1.";const c=s[1]>>6&3,l=s[1]&31;o+=["","A","B","C"][c]+l,o+=".";const h=va(n.getUint32(2));o+=h.toString(16),o+=".";const d=s[1]>>5&1,u=s[12];o+=d===0?"L":"H",o+=u,o+=".";const f=[];for(let p=0;p<6;p++){const g=s[p+13];f.push(g)}for(;f[f.length-1]===0;)f.pop();return o+=f.map(p=>p.toString(16)).join("."),o}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!r){const b=t.width*t.height;let k=N(we).level;for(const y of we)if(b<=y.maxPictureSize){k=y.level;break}return`vp09.00.${k.toString().padStart(2,"0")}.08`}const n=r.profile.toString().padStart(2,"0"),o=r.level.toString().padStart(2,"0"),c=r.bitDepth.toString().padStart(2,"0"),l=r.chromaSubsampling.toString().padStart(2,"0"),h=r.colourPrimaries.toString().padStart(2,"0"),d=r.transferCharacteristics.toString().padStart(2,"0"),u=r.matrixCoefficients.toString().padStart(2,"0"),f=r.videoFullRangeFlag.toString().padStart(2,"0");let p=`vp09.${n}.${o}.${c}.${l}`;p+=`.${h}.${d}.${u}.${f}`;const g=".01.01.01.01.00";return p.endsWith(g)&&(p=p.slice(0,-g.length)),p}else if(e==="av1"){if(!a){const y=t.width*t.height;let v=N(we).level;for(const w of we)if(y<=w.maxPictureSize){v=w.level;break}return`av01.0.${v.toString().padStart(2,"0")}M.08`}const n=a.profile,o=a.level.toString().padStart(2,"0"),c=a.tier?"H":"M",l=a.bitDepth.toString().padStart(2,"0"),h=a.monochrome?"1":"0",d=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0),u=i?.primaries?ze[i.primaries]:1,f=i?.transfer?Be[i.transfer]:1,p=i?.matrix?Ue[i.matrix]:1,g=i?.fullRange?1:0;let b=`av01.${n}.${o}${c}.${l}`;b+=`.${h}.${d.toString().padStart(3,"0")}`,b+=`.${u.toString().padStart(2,"0")}`,b+=`.${f.toString().padStart(2,"0")}`,b+=`.${p.toString().padStart(2,"0")}`,b+=`.${g}`;const k=".0.110.01.01.01.0";return b.endsWith(k)&&(b=b.slice(0,-k.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},ui=t=>{const e=t[t.length-1];if(e&&(e&224)===192){const I=((e&24)>>3)+1,D=2+((e&7)+1)*I;if(t[t.length-D]!==e)return null;let L=0;const ee=t.length-D+1;for(let q=0;q<I;q++){if(!t[ee+q])return null;L|=t[ee+q]<<8*q}t=t.subarray(0,L)}let s=0;if(_(t,s,s+2)!==2)return null;s+=2;const r=_(t,s,s+1);s+=1;const a=_(t,s,s+1);s+=1;const n=(a<<1)+r;n===3&&(s+=1);const o=_(t,s,s+1);if(s+=1,o===1)return null;const c=_(t,s,s+1);if(s+=1,c!==0||(s+=2,_(t,s,s+24)!==4817730))return null;s+=24;let h=8;if(n>=2){const I=_(t,s,s+1);s+=1,h=I?12:10}const d=_(t,s,s+3);s+=3;let u=0,f=0;if(d!==7){const I=_(t,s,s+1);if(s+=1,f=I,n===1||n===3){const M=_(t,s,s+1);s+=1;const D=_(t,s,s+1);s+=1,u=!M&&!D?3:M&&!D?2:1,s+=1}else u=1}else u=3,f=1;const p=_(t,s,s+16);s+=16;const g=_(t,s,s+16);s+=16;const b=p+1,k=g+1,y=b*k;let v=N(we).level;for(const I of we)if(y<=I.maxPictureSize){v=I.level;break}return{profile:n,level:v,bitDepth:h,chromaSubsampling:u,videoFullRangeFlag:f,colourPrimaries:d===2?1:d===1?6:2,transferCharacteristics:d===2?1:d===1?6:2,matrixCoefficients:d===7?0:d===2?1:d===1?6:2}},mi=t=>{let e=0;const s=()=>{let i=0;for(let r=0;r<8;r++){const a=t[e++];if(a===void 0)return 0;if(i|=(a&127)<<r*7,!(a&128))break;if(r===7&&a&128)return null}return i>=2**32-1?null:i};for(;e<t.length;){const i=_(t,e*8,e*8+8);e+=1;const r=i>>3&15,a=i>>2&1,n=i>>1&1;a&&(e+=1);let o;if(n){const c=s();if(c===null)return null;o=c}else o=t.length-e;if(r===1){const c=e*8;let l=0;const h=_(t,c+l,c+l+3);l+=3,_(t,c+l,c+l+1),l+=1;const d=_(t,c+l,c+l+1);l+=1;let u=0,f=0,p=0;if(d)u=_(t,c+l,c+l+5),l+=5;else{const T=_(t,c+l,c+l+1);if(l+=1,T){l+=32,l+=32;const M=_(t,c+l,c+l+1);if(l+=1,M)return null}const O=_(t,c+l,c+l+1);l+=1,O&&(p=_(t,c+l,c+l+5),l+=5,l+=32,l+=5,l+=5);const I=_(t,c+l,c+l+5);l+=5;for(let M=0;M<=I;M++){l+=12;const D=_(t,c+l,c+l+5);if(l+=5,M===0&&(u=D),D>7){const ee=_(t,c+l,c+l+1);l+=1,M===0&&(f=ee)}if(O){const ee=_(t,c+l,c+l+1);if(l+=1,ee){const q=p+1;l+=q,l+=q,l+=1}}const L=_(t,c+l,c+l+1);l+=1,L&&(l+=4)}}const g=_(t,c+l,c+l+1);l+=1;let b=8;if(h===2&&g){const T=_(t,c+l,c+l+1);l+=1,b=T?12:10}else h<=2&&(b=g?10:8);let k=0;h!==1&&(k=_(t,c+l,c+l+1),l+=1);let y=1,v=1,w=0;return k||(h===0?(y=1,v=1):h===1?(y=0,v=0):b===12&&(y=_(t,c+l,c+l+1),l+=1,y&&(v=_(t,c+l,c+l+1),l+=1)),y&&v&&(w=_(t,c+l,c+l+2),l+=2)),{profile:h,level:u,tier:f,bitDepth:b,monochrome:k,chromaSubsamplingX:y,chromaSubsamplingY:v,chromaSamplePosition:w}}e+=o}return null},Yt=(t,e,s)=>{if(t==="aac")return e>=2&&s<=24e3?"mp4a.40.29":s<=24e3?"mp4a.40.5":"mp4a.40.2";if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(H.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},fi=t=>{const{codec:e,codecDescription:s,aacCodecInfo:i}=t;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":`mp4a.40.${pi(s).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&H.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},pi=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=0,s=_(t,e,e+5);e+=5,s===31&&(s=32+_(t,e,e+6),e+=6);const i=_(t,e,e+4);e+=4;let r=null;if(i===15)r=_(t,e,e+24),e+=24;else{const o=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i<o.length&&(r=o[i])}const a=_(t,e,e+4);e+=4;let n=null;return a>=1&&a<=7&&(n={1:1,2:2,3:3,4:4,5:5,6:6,7:8}[a]),{objectType:s,frequencyIndex:i,sampleRate:r,channelConfiguration:a,numberOfChannels:n}},Ct=t=>{const e=Ce(t),s=e.getUint8(9),i=e.getUint16(10,!0),r=e.getUint32(12,!0),a=e.getInt16(16,!0),n=e.getUint8(18);let o=null;return n&&(o=t.subarray(19,21+s)),{outputChannelCount:s,preSkip:i,inputSampleRate:r,outputGain:a,channelMappingFamily:n,channelMappingTable:o}},Jt=48e3,Da=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Va=t=>{const e=t[0]>>3;return{durationInSamples:Da[e]}},gi=/^pcm-([usf])(\d+)+(be)?$/,Ie=t=>{if(m(H.includes(t)),t==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(t==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=gi.exec(t);m(e);let s;e[1]==="u"?s="unsigned":e[1]==="s"?s="signed":s="float";const i=Number(e[2])/8,r=e[3]!=="be",a=t==="pcm-u8"?2**7:0;return{dataType:s,sampleSize:i,littleEndian:r,silentValue:a}},wi=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":t==="vp8"?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":t.startsWith("mp4a.40")||t==="mp4a.67"?"aac":t==="mp3"||t==="mp4a.69"||t==="mp4a.6B"||t==="mp4a.6b"?"mp3":t==="opus"?"opus":t==="vorbis"?"vorbis":t==="flac"?"flac":t==="ulaw"?"ulaw":t==="alaw"?"alaw":gi.test(t)?t:t==="webvtt"?"webvtt":null,Zt=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},es=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},It=class{constructor(t){this._factor=t}_toVideoBitrate(t,e,s){const i=e*s,r={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},c=(l=>2e6*Math.pow(l/2073600,.75))(i)*r[t]*this._factor;return Math.ceil(c/1e3)*1e3}_toAudioBitrate(t){if(H.includes(t)||t==="flac")return-1;const s={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[t];if(!s)throw new Error(`Unhandled codec: ${t}`);let i=s*this._factor;return t==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,n)=>Math.abs(n-i)<Math.abs(a-i)?n:a):t==="opus"||t==="vorbis"?i=Math.max(6e3,i):t==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,n)=>Math.abs(n-i)<Math.abs(a-i)?n:a)),Math.round(i/1e3)*1e3}},Na=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],La=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Wa=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ha=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,$a=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,yi=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if(typeof t!="object")throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof t.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof t.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Na.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(t.decoderConfig.description!==void 0&&!St(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=t.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const s=Object.keys(ze);if(e.primaries!=null&&!s.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${s.join(", ")}.`);const i=Object.keys(Be);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(Ue);if(e.matrix!=null&&!r.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${r.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!La.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.");if(!t.decoderConfig.description)throw new TypeError("Video chunk metadata decoder configuration for AVC must include a description, which is expected to be an AVCDecoderConfigurationRecord as specified in ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!Wa.test(t.decoderConfig.codec))throw ne