UNPKG

@diffusionstudio/core

Version:

2D motion graphics and video rendering engine

17 lines (14 loc) 357 kB
/*! * @diffusionstudio/core v3.8.3 * (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,nt){typeof exports=="object"&&typeof module<"u"?nt(exports):typeof define=="function"&&define.amd?define(["exports"],nt):(S=typeof globalThis<"u"?globalThis:S||self,nt(S.core={}))})(this,function(S){"use strict";let nt=class ba{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,i){if(!i?.format||i.format!=="s16")throw new Error("Only s16 format is supported for copyTo");for(let s=0;s<this.numberOfFrames;s++)for(let r=0;r<this.numberOfChannels;r++){const a=r*this.numberOfFrames+s,n=s*this.numberOfChannels+r,o=Math.max(-1,Math.min(1,this.data[a]));e[n]=Math.round(o*32767)}}clone(){return new ba({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:nt});const Sa=.2,ot=30,rs=1;class He extends Error{message;code;constructor({message:e="",code:i=""},...s){super(e,...s),console.error(e),this.code=i,this.message=e}}class ve extends He{}class J extends He{}class $e extends He{}class va extends He{}class ct extends He{}function as(t,e=ot){if(e<1)throw new J({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t*e)}function Ta(t,e=ot){if(e<1)throw new J({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t/e*1e3)/1e3}function Et(t,e=ot){if(e<1)throw new J({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(t/e*1e3)}function xa(t){return Math.floor(t*255).toString(16).padStart(2,"0").toUpperCase()}function Ca(t,e){return t.reduce((i,s)=>{const r=s[e];return i[r]||(i[r]=[]),i[r].push(s),i},{})}function lt(t,e){return[t.slice(0,e),t.slice(e)].filter(i=>i.length>0)}function dt(t,e){return e?Math.floor(Math.random()*(e-t+1)+t):t}async function _a(t){t<=0||await new Promise(e=>setTimeout(e,t))}function B(t,e){if(!t)throw new Error(e||`Assertion failed: ${String(t)}`)}function Ia(t,e=300){let i;return(...s)=>{clearTimeout(i),i=setTimeout(()=>{t.apply(t,s)},e)}}function ns(t,e,i){i<0&&(i=0);const s=t[e];t.splice(e,1),t.splice(i,0,s)}function Ea(){return typeof crypto<"u"?crypto.randomUUID().split("-").at(0):Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}function Pa(t){return t.charAt(0).toUpperCase()+t.slice(1)}function os(t,e,i){return Math.max(e,Math.min(i,t))}function Fa(t){throw new Error("This should not run!")}function cs(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 i=Math.max(...e.map(n=>n.length)),s=new Float32Array(i*t.numberOfChannels);let r=0,a=0;for(;a<i;)e.forEach(n=>{s[r++]=n[a]!==void 0?n[a]:0}),a++;return s}function Pt(t,e,i){for(let s=0;s<i.length;s++)t.setUint8(e+s,i.charCodeAt(s))}function ls(t,e,i){for(let s=0;s<e.length;s++,i+=2){const r=Math.max(-1,Math.min(1,e[s]));t.setInt16(i,r<0?r*32768:r*32767,!0)}return t}function Ra(t,e,i){const a=e*2,n=8,o=36,c=t.length*2,l=o+c,d=new ArrayBuffer(n+l),h=new DataView(d);return Pt(h,0,"RIFF"),h.setUint32(4,l,!0),Pt(h,8,"WAVE"),Pt(h,12,"fmt "),h.setUint32(16,16,!0),h.setUint16(20,1,!0),h.setUint16(22,e,!0),h.setUint32(24,i,!0),h.setUint32(28,i*a,!0),h.setUint16(32,a,!0),h.setUint16(34,16,!0),Pt(h,36,"data"),h.setUint32(40,c,!0),ls(h,t,n+o)}function Ba(t,e="audio/wav"){const i=cs(t),s=Ra(i,t.numberOfChannels,t.sampleRate);return new Blob([s],{type:e})}function Ma(t){const e=new Float32Array(t.length*t.numberOfChannels);let i=0;for(let s=0;s<t.numberOfChannels;s++){const r=t.getChannelData(s);e.set(r,i),i+=r.length}return e}function Oa(t){const e=t.numberOfChannels,i=t.length,s=new Int16Array(i*e);for(let r=0;r<i;r++)for(let a=0;a<e;a++){let n=t.getChannelData(a)[r]*32767;n>32767&&(n=32767),n<-32767&&(n=-32767),s[r*e+a]=n}return s}async function Aa(t,e=22050,i=Math.sqrt(2)){const s=await t.arrayBuffer(),r=new OfflineAudioContext({sampleRate:e,length:1}),a=await r.decodeAudioData(s),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 d=0;d<a.length;++d)l[d]=i*(o[d]+c[d])/2;return n}return a}function za(t,e=44100,i=2){if(t.sampleRate==e&&t.numberOfChannels==i)return t;const s=Math.floor(t.duration*e),a=new OfflineAudioContext(i,1,e).createBuffer(i,s,e);for(let n=0;n<t.numberOfChannels;n++){const o=t.getChannelData(n),c=a.getChannelData(n),l=t.sampleRate/e;for(let d=0;d<c.length;d++){const h=d*l,u=Math.floor(h),m=Math.ceil(h);if(m>=o.length)c[d]=o[u];else{const p=h-u;c[d]=o[u]*(1-p)+o[m]*p}}}return a}async function Zt(t,e){const i=document.createElement("a");if(document.head.appendChild(i),i.target="_blank",e?i.download=e:t instanceof File?i.download=t.name:t instanceof Blob?i.download="untitled":typeof t=="string"&&(i.download=t.split("/").pop()??"untitled"),typeof t=="string"&&t.startsWith("data:image/svg+xml;base64,")){const s=t.split(",")[1],r=atob(s),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"});i.href=URL.createObjectURL(o),i.download=e?.split(".")[0]+".svg"}else typeof t=="string"?i.href=t:t instanceof Blob?i.href=URL.createObjectURL(t):i.href=URL.createObjectURL(await t.getFile());i.click(),i.remove()}async function Ua(t,e=!0){return new Promise(i=>{const s=document.createElement("input");s.type="file",s.accept=t,s.multiple=e,s.onchange=r=>{const a=Array.from(r.target?.files??[]);i(a)},s.click()})}function O(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[i,s,r]=e.map(Number);if(isNaN(i)||isNaN(s)||isNaN(r))throw new Error(`Invalid time format: ${t}`);return new P(0,r,s,i)}if(e.length===2){const[i,s]=e.map(Number);if(isNaN(i)||isNaN(s))throw new Error(`Invalid time format: ${t}`);return new P(0,s,i)}if(typeof t=="string"){const i=parseFloat(t);if(isNaN(i))throw new Error(`Invalid time format: ${t}`);if(t.endsWith("ms"))return new P(i);if(t.endsWith("s"))return new P(0,i);if(t.endsWith("f"))return P.fromFrames(i);if(t.endsWith("min"))return new P(0,0,i);throw new Error(`Invalid time format: ${t}`)}throw new Error(`Invalid time format: ${t}`)}async function Da(t){const{fps:e,height:i,width:s,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 d of n)o.push({codec:l,hardwareAcceleration:d,width:s,height:i,bitrate:r,framerate:e});const c=[];if("VideoEncoder"in window){for(const l of o){const d=await VideoEncoder.isConfigSupported(l);d.supported&&c.push(d.config??l)}return c.sort(Va)[0].codec}}function Va(t,e){const i=t.hardwareAcceleration??"",s=e.hardwareAcceleration??"";return i<s?-1:i>s?1:0}const ht={fromJSON:t=>new Date(t)};class P{time;constructor(e=0,i=0,s=0,r=0){this.time=Math.round(e+i*1e3+s*6e4+r*36e5)}get millis(){return this.time}set millis(e){this.time=Math.round(e)}get frames(){return as(this.millis/1e3)}set frames(e){this.millis=Et(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 i=Et(e);return this.millis=this.millis+i,this}add(e){return new P(e.millis+this.millis)}subtract(e){return new P(this.millis-e.millis)}static fromFrames(e,i){const s=new P;return s.millis=Et(e,i),s}copy(){return new P(this.millis)}toJSON(){return this.millis}fromJSON(e){return B(typeof e=="number"),this.millis=e,this}static fromJSON(e){return B(typeof e=="number"),new P(e)}}function ds(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 Re{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 Ft=(t=>(t.en="en",t.de="de",t))(Ft||{});class ut{id=crypto.randomUUID();text;start;stop;confidence;constructor(e,i,s,r){this.text=e,this.start=new P(i),this.stop=new P(s),this.confidence=r}get duration(){return this.stop.subtract(this.start)}}class ie{id=crypto.randomUUID();language=Ft.en;groups=[];get text(){return this.groups.map(({text:e})=>e).join(" ")}get words(){return this.groups.flatMap(({words:e})=>e)}constructor(e=[],i=Ft.en){this.groups=e,this.language=i}*iter({count:e,duration:i,length:s}){for(const r of this.groups){let a;for(const[n,o]of r.words.entries())a&&(e&&a.words.length>=dt(...e)?(yield a,a=void 0):i&&a?.duration.seconds>=dt(...i)?(yield a,a=void 0):s&&a.text.length>=dt(...s)&&(yield a,a=void 0)),a?a.words.push(o):a=new Re([o]),n==r.words.length-1&&(yield a)}}optimize(){const e=this.groups.flatMap(i=>i.words);for(let i=0;i<e.length-1;i++){const s=e[i],r=e[i+1];r.start.millis-s.stop.millis<0?r.start.millis=s.stop.millis+1:s.stop.millis=r.start.millis-1}return this}toSRT(e={}){let i=1,s="";for(const r of this.iter(e)){const a=hs(r.start.seconds),n=hs(r.stop.seconds);s+=`${i} `+ds(a)+" --> "+ds(n)+` ${r.text} `,i+=1}return{text:s,blob:new Blob([s],{type:"text/plain;charset=utf8"})}}toJSON(){return this.groups.map(e=>e.words.map(i=>({token:i.text,start:i.start.millis,stop:i.stop.millis})))}slice(e,i=!0){let s=0;const r=[];for(const a of this.groups)for(const n of a.words)if(r.length==0&&i&&(s=n.start.millis),r.push(new ut(n.text,n.start.millis-s,n.stop.millis-s)),r.length==e)return new ie([new Re(r)]);return new ie([new Re(r)])}copy(){return ie.fromJSON(this.toJSON())}static fromJSON(e){const i=new ie;for(const s of e){const r=new Re;for(const a of s)r.words.push(new ut(a.token,a.start,a.stop));i.groups.push(r)}return i}static async from(e){if(Array.isArray(e))return ie.fromJSON(e);if(e instanceof FileSystemFileHandle){const s=await e.getFile();return ie.fromJSON(JSON.parse(await s.text()))}if(e instanceof Blob)return ie.fromJSON(JSON.parse(await e.text()));const i=await fetch(e);if(!i.ok)throw new ve({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return ie.fromJSON(await i.json())}fromJSON(e){B(typeof e=="object"),B(Array.isArray(e)),this.groups=[];for(const i of e){const s=new Re;for(const r of i)s.words.push(new ut(r.token,r.start,r.stop));this.groups.push(s)}return this}}class me{toJSON(e){const i={},s=this.constructor.__serializableProperties||[],r=a=>{if(a==null||a instanceof Blob||a instanceof FileSystemFileHandle)return a;if(Array.isArray(a))return a.map(n=>r(n)).filter(n=>n!==void 0);if(typeof a=="object"&&"toJSON"in a)return a.toJSON();if(typeof a=="object"){const n={};for(const o in a){const c=r(a[o]);c!==void 0&&(n[o]=c)}return n}return a};return s.forEach(({propertyKey:a,mapTo:n})=>{if(e?.includes(a))return;const o=this[a],c=n??a,l=r(o);l!==void 0&&(i[c]=l)}),i}fromJSON(e){return(this.constructor.__serializableProperties||[]).forEach(({propertyKey:s,deserializer:r,mapTo:a})=>{const n=a??s,o=r.fromJSON?.bind(r)??(c=>c);e.hasOwnProperty(n)&&(this[s]=o(e[n]))}),this}static fromJSON(e){return new this().fromJSON(e)}}function T(t={},e){return function(i,s){const r=i.constructor;r.__serializableProperties||(r.__serializableProperties=[]),r.__serializableProperties=[...r.__serializableProperties.filter(a=>a.propertyKey!==s),{propertyKey:s,deserializer:t,mapTo:e}]}}function je(t){return class extends t{_handlers={};on(i,s){if(typeof s!="function")throw new Error("The callback of an event listener needs to be a function.");const r=crypto.randomUUID();return this._handlers[i]?this._handlers[i][r]=s:this._handlers[i]={[r]:s},r}off(i,...s){if(i){if(i==="*"){this._handlers={};return}for(const r of Object.values(this._handlers))i in r&&delete r[i];for(const r of s)this.off(r)}}emit(i,s){const r=new CustomEvent(i,{detail:s});Object.defineProperty(r,"currentTarget",{writable:!1,value:this});for(const a in this._handlers[i]??{})this._handlers[i]?.[a](r);for(const a in this._handlers["*"]??{})this._handlers["*"]?.[a](r)}bubble(i){return this.on("*",s=>{i.emit(s.type,s.detail)})}resolve(i){return(s,r)=>{this.on("error",r),this.on(i,s)}}}}class Rt extends je(me){_key;_value;_store;loaded=!1;constructor(e,i,s){super(),this._store=e,this._key=i,this.initValue(s)}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 Na{storageEngine;namespace;constructor(e,i=localStorage){this.storageEngine=i,this.namespace=e}define(e,i,s){const r=this.get(e);return r===null?(this.set(e,i),new Rt(this,e,i)):s&&r!=null?new Rt(this,e,s(r)):new Rt(this,e,r)}set(e,i){this.storageEngine.setItem(this.getStorageId(e),JSON.stringify({value:i}))}get(e){const i=this.storageEngine.getItem(this.getStorageId(e));return i?JSON.parse(i).value:null}remove(e){this.storageEngine.removeItem(this.getStorageId(e))}getStorageId(e){return this.namespace?`${this.namespace}.${e}`:e}}function ei(){return class extends je(class{}){}}function La(t,e){return e=="lower"?t.toLocaleLowerCase():e=="upper"?t.toUpperCase():t}function Be(t="#000000",e=100){return`${t}${Math.round(e/100*255).toString(16)}`}function I(t,e){return typeof t=="number"?t:Number.parseFloat(t.replace("%",""))*e/100}function Wa(t){const e=t.startsWith("#")?t.slice(1):t,i=parseInt(e,16),s=i>>16&255,r=i>>8&255,a=i&255;return{r:s,g:r,b:a}}function Ha(t,e,i){return`#${((1<<24)+(Math.round(t)<<16)+(Math.round(e)<<8)+Math.round(i)).toString(16).slice(1)}`}function ti(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 i=t*2;return i*(2-i)/2}else{const i=(t-.5)*2;return i*i/2+.5}default:return t}}function ft(t,e,i){return t+(e-t)*i}function us(t){const e=Wa(t);return $a(e.r,e.g,e.b)}function $a(t,e,i){t/=255,e/=255,i/=255;const s=Math.max(t,e,i),r=Math.min(t,e,i);let a=0,n=0;const o=(s+r)/2;if(s!==r){const c=s-r;switch(n=o>.5?c/(2-s-r):c/(s+r),s){case t:a=(e-i)/c+(e<i?6:0);break;case e:a=(i-t)/c+2;break;case i: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 ja(t,e,i){e/=100,i/=100,t=(t+360)%360;function s(l,d,h){return h<0&&(h+=1),h>1&&(h-=1),h<1/6?l+(d-l)*6*h:h<1/2?d:h<2/3?l+(d-l)*(2/3-h)*6:l}const r=i<.5?i*(1+e):i+e-i*e,a=2*i-r,n=s(a,r,t/360+1/3),o=s(a,r,t/360),c=s(a,r,t/360-1/3);return Ha(Math.round(n*255),Math.round(o*255),Math.round(c*255))}function qa(t,e){const{frames:i,extrapolate:s="clamp",easing:r}=t;if(e.millis<=O(i[0].time).millis)return i[0].value;if(e.millis>=O(i[i.length-1].time).millis)return i[i.length-1].value;let a,n;for(let m=0;m<i.length-1;m++)if(e.millis>=O(i[m].time).millis&&e.millis<=O(i[m+1].time).millis){a=i[m],n=i[m+1];break}if(!a||!n)throw new Error("Unexpected error in keyframe interpolation");const o=(e.millis-O(a.time).millis)/(O(n.time).millis-O(a.time).millis),c=ti(o,a.easing??r),l=us(a.value),d=us(n.value);let h=l.h,u=d.h;return Math.abs(u-h)>180&&(h<u?h+=360:u+=360),ja(ft(h,u,c),ft(l.s,d.s,c),ft(l.l,d.l,c))}function fs(t,e){const{frames:i,extrapolate:s="clamp",easing:r}=t;if(e.millis<=O(i[0].time).millis)return i[0].value;if(e.millis>=O(i[i.length-1].time).millis)return i[i.length-1].value;let a,n;for(let l=0;l<i.length-1;l++)if(e.millis>=O(i[l].time).millis&&e.millis<=O(i[l+1].time).millis){a=i[l],n=i[l+1];break}if(!a||!n)throw new Error("Unexpected error in keyframe interpolation");const o=(e.millis-O(a.time).millis)/(O(n.time).millis-O(a.time).millis),c=ti(o,a.easing??r);return typeof a.value=="number"&&typeof n.value=="number"?ft(a.value,n.value,c):`${ft(ms(a.value),ms(n.value),c)}%`}function ms(t){return typeof t=="number"?t:Number(t.replace("%",""))}function Qa(t,e){const{frames:i,extrapolate:s="clamp"}=t;if(e.millis<=O(i[0].time).millis)return i[0].value;if(e.millis>=O(i[i.length-1].time).millis)return i[i.length-1].value;let r,a;for(let h=0;h<i.length-1;h++)if(e.millis>=O(i[h].time).millis&&e.millis<=O(i[h+1].time).millis){r=i[h],a=i[h+1];break}if(!r||!a)throw new Error("Unexpected error in keyframe interpolation");const n=(e.millis-O(r.time).millis)/(O(a.time).millis-O(r.time).millis),o=ti(n,r.easing),c=a.value,l=c.length,d=Math.floor(o*l);return c.slice(0,d)}var Ka=Object.defineProperty,mt=(t,e,i,s)=>{for(var r=void 0,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&Ka(e,i,r),r};class de extends me{id=crypto.randomUUID();type="base";width;height;fillRule;animations=[];clip;renderer;constructor({width:e=100,height:i=100}={}){super(),this.width=e,this.height=i}connect(e){return this.clip=e,this}draw(e){return this.renderer=e,new Path2D}animate(e){for(const i of this.animations){const s=i?.frames[0].value;(typeof s=="number"||typeof s=="string"&&s.match(/^[0-9]+(\.[0-9]+)?%$/))&&(this[i.key]=fs(i,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:I(this.width,this.renderer?.width??0),height:I(this.height,this.renderer?.height??0)}}get bounds(){const{width:e,height:i}=this.size;return[{x:0,y:0},{x:e,y:0},{x:e,y:i},{x:0,y:i}]}detach(){return this.clip&&(this.clip.mask=void 0,this.clip=void 0),this}}mt([T()],de.prototype,"type"),mt([T()],de.prototype,"width"),mt([T()],de.prototype,"height"),mt([T()],de.prototype,"fillRule"),mt([T()],de.prototype,"animations");var Xa=Object.defineProperty,Bt=(t,e,i,s)=>{for(var r=void 0,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&Xa(e,i,r),r};class qe extends de{type="rectangle";x;y;radius;constructor({x:e=0,y:i=0,radius:s=0,animations:r,...a}={}){super(a),this.x=e,this.y=i,this.radius=s,this.animations=r??[]}draw(e){const i=super.draw(e);if(this.radius){const s=I(this.width,e.width),r=I(this.height,e.height),a=I(this.radius,Math.min(s,r));i.roundRect(I(this.x,e.width)*e.resolution,I(this.y,e.height)*e.resolution,s*e.resolution,r*e.resolution,a*e.resolution)}else i.rect(I(this.x,e.width)*e.resolution,I(this.y,e.height)*e.resolution,I(this.width,e.width)*e.resolution,I(this.height,e.height)*e.resolution);return i}get bounds(){return super.bounds.map(e=>({x:e.x+I(this.x,this.renderer?.width??0),y:e.y+I(this.y,this.renderer?.height??0)}))}}Bt([T()],qe.prototype,"type"),Bt([T()],qe.prototype,"x"),Bt([T()],qe.prototype,"y"),Bt([T()],qe.prototype,"radius");class ps{static fromJSON(e){switch(B(typeof e=="object"),B(e!=null),B("type"in e),e.type){case"rectangle":return qe.fromJSON(e);case"circle":return pt.fromJSON(e);default:return de.fromJSON(e)}}}var Ga=Object.defineProperty,ii=(t,e,i,s)=>{for(var r=void 0,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&Ga(e,i,r),r};class pt extends de{type="circle";cx;cy;constructor({cx:e,cy:i,x:s=0,y:r=0,radius:a,animations:n,...o}={}){super(o),this.cx=e??s,this.cy=i??r,a&&(this.radius=a),this.animations=n??[]}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 i=super.draw(e);return i.ellipse(I(this.cx,e.width)*e.resolution,I(this.cy,e.height)*e.resolution,I(this.width,e.width)*e.resolution*.5,I(this.height,e.height)*e.resolution*.5,0,0,2*Math.PI),i}get bounds(){const{width:e,height:i}=this.size,{cx:s,cy:r}=this,a=I(s,this.renderer?.width??0)-e*.5,n=I(r,this.renderer?.height??0)-i*.5;return[{x:a,y:n},{x:a+e,y:n},{x:a+e,y:n+i},{x:a,y:n+i}]}}ii([T()],pt.prototype,"type"),ii([T()],pt.prototype,"cx"),ii([T()],pt.prototype,"cy");var Ya=Object.defineProperty,Ja=Object.getOwnPropertyDescriptor,Mt=(t,e,i,s)=>{for(var r=s>1?void 0:s?Ja(e,i):e,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=(s?n(e,i,r):n(r))||r);return s&&r&&Ya(e,i,r),r};class Me extends me{_background="#000000";canvas=document.createElement("canvas");context=this.canvas.getContext("2d");resolution=1;width=0;height=0;constructor({width:e=1920,height:i=1080,background:s="#000000",resolution:r=1}={}){super(),this.resolution=r,this.background=s,this.resize(e,i)}get background(){return this._background}set background(e){this.background!=e&&(this.canvas.style.background=e,this._background=e)}resize(e=this.width,i=this.height,s=this.resolution){const r=Math.round(e/2)*2,a=Math.round(i/2)*2;return(r!==this.width||a!==this.height||s!==this.resolution)&&(this.width=r,this.height=a,this.resolution=s,this.canvas.width=Math.round(r*this.resolution/2)*2,this.canvas.height=Math.round(a*this.resolution/2)*2,this.context.imageSmoothingEnabled=!1),this}clear(e){let i=0,s=0,r=this.width*this.resolution,a=this.height*this.resolution;return this.context.fillStyle=this._background,e&&(i=I(e.x??0,this.width)*this.resolution,s=I(e.y??0,this.height)*this.resolution,r=I(e.width,this.width)*this.resolution,a=I(e.height,this.height)*this.resolution),this.context.clearRect(i,s,r,a),this.context.fillRect(i,s,r,a),this}rect(e){if(this.context.beginPath(),e.radius){const i=I(e.width,this.width),s=I(e.height,this.height),r=Math.max(I(e.radius,Math.min(i,s)),0);this.context.roundRect(I(e.x??0,this.width)*this.resolution|0,I(e.y??0,this.height)*this.resolution|0,i*this.resolution|0,s*this.resolution|0,r*this.resolution|0)}else this.context.rect(I(e.x??0,this.width)*this.resolution|0,I(e.y??0,this.height)*this.resolution|0,I(e.width,this.width)*this.resolution|0,I(e.height,this.height)*this.resolution|0);return this.context.closePath(),this}circle(e){return this.context.beginPath(),"height"in e?this.context.ellipse(I(e.cx,this.width)*this.resolution|0,I(e.cy,this.height)*this.resolution|0,I(e.width,this.width)*this.resolution|0,I(e.height,this.height)*this.resolution|0,0,0,Math.PI*2):this.context.arc(I(e.cx,this.width)*this.resolution|0,I(e.cy,this.height)*this.resolution|0,I(e.radius,Math.min(this.width,this.height)*.5)*this.resolution|0,0,Math.PI*2),this.context.closePath(),this}image(e,i){const{x:s=0,y:r=0,width:a,height:n,rotation:o}=i,c=I(s,this.width)*this.resolution|0,l=I(r,this.height)*this.resolution|0,d=I(a,this.width)*this.resolution|0,h=I(n,this.height)*this.resolution|0;if(o!==void 0&&o!==0){this.context.save(),this.context.translate(c+d/2,l+h/2);const u=o*Math.PI/180;this.context.rotate(u);const m=Math.abs(o%180)===90;this.context.drawImage(e,(m?-h/2:-d/2)|0,(m?-d/2:-h/2)|0,(m?h:d)|0,(m?d:h)|0),this.context.restore()}else this.context.drawImage(e,c,l,d,h);return this}clip(e,i){return e instanceof de?this.context.clip(e.draw(this),e.fillRule):e&&this.context.clip(e,i),this}opacity(e){return this.context.globalAlpha*=e/100,this}transform(e){return e?(e.translate&&this.context.translate(I(e.translate.x,this.width)*this.resolution|0,I(e.translate.y,this.height)*this.resolution|0),e.rotate&&this.context.rotate(e.rotate*Math.PI/180),e.scale&&this.context.scale(I(e.scale.x,this.width),I(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,i=!1){if(!e)return this.context.fillStyle="transparent",this;if(typeof e.color=="string")this.context.fillStyle=Be(e.color,e.opacity);else if("type"in e.color){const s=this.createGradient(e.color);this.context.fillStyle=s}else if("image"in e.color){const s=this.context.createPattern(e.color.image,e.color.repetition);this.context.fillStyle=s??""}return i&&this.context.fill(),this}shadow(e){return e?(this.context.fillStyle=this.context.shadowColor=Be(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,i=!1){return e?(this.context.strokeStyle=Be(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),i&&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 i;return e.type==="linear"?i=this.context.createLinearGradient(0,0,this.canvas.width,0):i=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(s=>{i.addColorStop(s.offset,s.color)}),i}watermark(e){!e||!e.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,i){return this.context.strokeText(e,I(i.x,this.width)*this.resolution,I(i.y,this.height)*this.resolution),this}fillText(e,i){return this.context.fillText(e,I(i.x,this.width)*this.resolution,I(i.y,this.height)*this.resolution),this}measureText(e,i){return this.context.font=this.createFontString(i.style,i.weight,i.size,i.family),this.context.measureText(e)}createFontString(e,i,s,r){return`${e??"normal"} ${i??"400"} ${(s??16)*this.textScale}px ${r??"Arial"}`.trim()}}Mt([T()],Me.prototype,"resolution",2),Mt([T()],Me.prototype,"width",2),Mt([T()],Me.prototype,"height",2),Mt([T()],Me.prototype,"background",1);class si{context;hardwareOffset=0;playbackOffset=0;playbackFps=ot;inactiveFps=rs;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 s=1e3/(this.playing?this.playbackFps:this.inactiveFps);e-this.lastFrameTime>=s&&(this.lastFrameTime=e,await this.callback?.()),requestAnimationFrame(this.timer.bind(this))}async resumeAudioContext(){this.context.state==="suspended"&&await this.context.resume()}}const Za={fromJSON:t=>{B(typeof t=="object"),B(t!=null);const e={};for(const[i,s]of Object.entries(t))B(typeof s=="number"),e[i]=new P(s);return e}};function en(t){const e=new P;for(const i of t)i.disabled||i.stop.frames>e.frames&&(e.frames=i.stop.frames);return e}var tn=Object.defineProperty,Oe=(t,e,i,s)=>{for(var r=void 0,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&tn(e,i,r),r};class ne extends me{id=crypto.randomUUID();data={};type="base";mimeType;input;name;createdAt=new Date;constructor(e){super(),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.input instanceof FileSystemFileHandle?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():this.input instanceof Blob?await this.input.arrayBuffer():await(await this.input.getFile()).arrayBuffer()}async download(){Zt(this.input,this.name)}async thumbnail(){return document.createElement("div")}async createCheckpoint(){return this.toJSON()}}Oe([T()],ne.prototype,"id"),Oe([T()],ne.prototype,"data"),Oe([T()],ne.prototype,"type"),Oe([T()],ne.prototype,"mimeType"),Oe([T()],ne.prototype,"input"),Oe([T()],ne.prototype,"name"),Oe([T(ht)],ne.prototype,"createdAt");function Ot(t){class e extends t{height=1080;width=1920;get aspectRatio(){return this.width/this.height}}return e}async function gs(t){if(t instanceof FileSystemFileHandle)return(await t.getFile()).type;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 i=e.headers.get("Content-Type");if(!i)throw new ve({message:"No content type found",code:"no_content_type_found"});return i}function f(t){if(!t)throw new Error("Assertion failed.")}var ri=t=>{const e=(t%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${t}.`)},$=t=>t&&t[t.length-1],Qe=t=>t>=0&&t<2**32,Te=class ka{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),i=this.bytes[e]??0,s=7-(this.pos&7),r=(i&1<<s)>>s;return this.pos++,r}readBits(e){let i=0;for(let s=0;s<e;s++)i<<=1,i|=this.readBit();return i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,i=this.bytes[e]??0;return this.pos+=8,i}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new ka(this.bytes);return e.pos=this.pos,e}},E=t=>{let e=0;for(;t.readBit()===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},gt=t=>{const e=E(t);return e&1?e+1>>1:-(e>>1)},sn=(t,e,i,s)=>{for(let r=e;r<i;r++){const a=Math.floor(r/8);let n=t[a];const o=7-(r&7);n&=~(1<<o),n|=(s&1<<i-r-1)>>i-r-1<<o,t[a]=n}},se=t=>t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength),Ae=t=>t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength),pe=new TextEncoder,ai=t=>Object.fromEntries(Object.entries(t).map(([e,i])=>[i,e])),Ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ws=ai(Ke),Xe={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18},ys=ai(Xe),Ge={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},bs=ai(Ge),ks=t=>!!t&&!!t.primaries&&!!t.transfer&&!!t.matrix&&t.fullRange!==void 0,At=t=>t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView),wt=class{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let t;const e=new Promise(s=>{t=s}),i=this.currentPromise;return this.currentPromise=e,await i,t}},Ss=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join(""),vs=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),q=(t,e,i)=>{let s=0,r=t.length-1,a=-1;for(;s<=r;){const n=s+r>>1,o=i(t[n]);o===e?(a=n,r=n-1):o<e?s=n+1:r=n-1}return a},N=(t,e,i)=>{let s=-1,r=0,a=t.length-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(t[n])<=e?(s=n,r=n+1):a=n-1}return s},ee=()=>{let t,e;return{promise:new Promise((s,r)=>{t=s,e=r}),resolve:t,reject:e}},rn=(t,e)=>{const i=t.indexOf(e);i!==-1&&t.splice(i,1)},Ts=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i]))return t[i]},xs=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i]))return i;return-1},an=async function*(t){Symbol.iterator in t?yield*t[Symbol.iterator]():yield*t[Symbol.asyncIterator]()},nn=t=>{if(!(Symbol.iterator in t)&&!(Symbol.asyncIterator in t))throw new TypeError("Argument must be an iterable or async iterable.")},Cs=(t,e,i)=>{const s=t.getUint8(e),r=t.getUint8(e+1),a=t.getUint8(e+2);return i?s|r<<8|a<<16:s<<16|r<<8|a},on=(t,e,i)=>Cs(t,e,i)<<8>>8,_s=(t,e,i,s)=>{i=i>>>0,i=i&16777215,s?(t.setUint8(e,i&255),t.setUint8(e+1,i>>>8&255),t.setUint8(e+2,i>>>16&255)):(t.setUint8(e,i>>>16&255),t.setUint8(e+1,i>>>8&255),t.setUint8(e+2,i&255))},cn=(t,e,i,s)=>{i=te(i,-8388608,8388607),i<0&&(i=i+16777216&16777215),_s(t,e,i,s)},ln=(t,e,i,s)=>{t.setUint32(e+0,i,!0),t.setInt32(e+4,Math.floor(i/2**32),!0)},zt=(t,e)=>({async next(){const i=await t.next();return i.done?{value:void 0,done:!0}:{value:e(i.value),done:!1}},return(){return t.return()},throw(i){return t.throw(i)},[Symbol.asyncIterator](){return this}}),te=(t,e,i)=>Math.max(e,Math.min(i,t)),ge="und",ni=(t,e)=>{const i=10**e;return Math.round(t*i)/i},oi=(t,e)=>Math.round(t/e)*e,dn=t=>{let e=0;for(;t;)e++,t>>=1;return e},hn=/^[a-z]{3}$/,ci=t=>hn.test(t),xe=1e6*(1+Number.EPSILON),li=(t,e)=>{const i={...t};for(const s in e)typeof t[s]=="object"&&t[s]!==null&&typeof e[s]=="object"&&e[s]!==null?i[s]=li(t[s],e[s]):i[s]=e[s];return i},Is=async(t,e,i)=>{let s=0;for(;;)try{return await fetch(t,e)}catch(r){console.error("Retrying failed fetch. Error:",r),s++;const a=i(s);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))}},un=(t,e)=>{const i=t<0?-1:1;t=Math.abs(t);let s=0,r=1,a=1,n=0,o=t;for(;;){const c=Math.floor(o),l=c*a+s,d=c*n+r;if(d>e)return{numerator:i*a,denominator:n};if(s=a,r=n,a=l,n=d,o=1/(o-c),!isFinite(o))break}return{numerator:i*a,denominator:n}},Ut=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},fn=class{static supports(t,e){return!1}},Es=class{static supports(t,e){return!1}},Ps=[],Fs=[],Dt=[],Vt=[],mn=t=>{if(t.prototype instanceof fn)Dt.push(t);else if(t.prototype instanceof Es)Vt.push(t);else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")},ae=["avc","hevc","vp9","av1","vp8"],Q=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-u8","pcm-s8","ulaw","alaw"],di=["aac","opus","mp3","vorbis","flac"],oe=[...di,...Q],Ce=["webvtt"],Rs=[{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}],Bs=[{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}],_e=[{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}],Ms=[{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}],pn=".01.01.01.01.00",gn=".0.110.01.01.01.0",hi=(t,e,i,s)=>{if(t==="avc"){const a=Math.ceil(e/16)*Math.ceil(i/16),n=Rs.find(h=>a<=h.maxMacroblocks&&s<=h.maxBitrate)??$(Rs),o=n?n.level:0,c="64".padStart(2,"0"),l="00",d=o.toString(16).padStart(2,"0");return`avc1.${c}${l}${d}`}else if(t==="hevc"){const r="",n="6",o=e*i,c=Bs.find(d=>o<=d.maxPictureSize&&s<=d.maxBitrate)??$(Bs);return`hev1.${r}1.${n}.${c.tier}${c.level}.B0`}else{if(t==="vp8")return"vp8";if(t==="vp9"){const r="00",a=e*i,n=_e.find(c=>a<=c.maxPictureSize&&s<=c.maxBitrate)??$(_e);return`vp09.${r}.${n.level.toString().padStart(2,"0")}.08${pn}`}else if(t==="av1"){const a=e*i,n=Ms.find(l=>a<=l.maxPictureSize&&s<=l.maxBitrate)??$(Ms);return`av01.0.${n.level.toString().padStart(2,"0")}${n.tier}.08${gn}`}}throw new TypeError(`Unhandled codec '${t}'.`)},wn=t=>{const e=t.split("."),i=Number(e[1]),s=Number(e[2]),r=Number(e[3]),a=e[4]?Number(e[4]):1;return[1,1,i,2,1,s,3,1,r,4,1,a]},Os=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,h=Number(e[3])===8?0:1,u=0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,g=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,b=(l<<7)+(h<<6)+(u<<5)+(m<<4)+(p<<3)+(g<<2)+w;return[r,c,b,0]},As=t=>{const{codec:e,codecDescription:i,colorSpace:s,avcCodecInfo:r,hevcCodecInfo:a,vp9CodecInfo:n,av1CodecInfo:o}=t;if(e==="avc"){if(r){const c=new Uint8Array([r.avcProfileIndication,r.profileCompatibility,r.avcLevelIndication]);return`avc1.${Ss(c)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc1.${Ss(i.subarray(1,4))}`}else if(e==="hevc"){let c,l,d,h,u,m;if(a)c=a.generalProfileSpace,l=a.generalProfileIdc,d=vs(a.generalProfileCompatibilityFlags),h=a.generalTierFlag,u=a.generalLevelIdc,m=[...a.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const g=Ae(i),w=g.getUint8(1);c=w>>6&3,l=w&31,d=vs(g.getUint32(2)),h=w>>5&1,u=g.getUint8(12),m=[];for(let b=0;b<6;b++)m.push(g.getUint8(6+b))}let p="hev1.";for(p+=["","A","B","C"][c]+l,p+=".",p+=d.toString(16).toUpperCase(),p+=".",p+=h===0?"L":"H",p+=u;m.length>0&&m[m.length-1]===0;)m.pop();return m.length>0&&(p+=".",p+=m.map(g=>g.toString(16).toUpperCase()).join(".")),p}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!n){const C=t.width*t.height;let v=$(_e).level;for(const k of _e)if(C<=k.maxPictureSize){v=k.level;break}return`vp09.00.${v.toString().padStart(2,"0")}.08`}const c=n.profile.toString().padStart(2,"0"),l=n.level.toString().padStart(2,"0"),d=n.bitDepth.toString().padStart(2,"0"),h=n.chromaSubsampling.toString().padStart(2,"0"),u=n.colourPrimaries.toString().padStart(2,"0"),m=n.transferCharacteristics.toString().padStart(2,"0"),p=n.matrixCoefficients.toString().padStart(2,"0"),g=n.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${c}.${l}.${d}.${h}`;w+=`.${u}.${m}.${p}.${g}`;const b=".01.01.01.01.00";return w.endsWith(b)&&(w=w.slice(0,-b.length)),w}else if(e==="av1"){if(!o){const k=t.width*t.height;let y=$(_e).level;for(const x of _e)if(k<=x.maxPictureSize){y=x.level;break}return`av01.0.${y.toString().padStart(2,"0")}M.08`}const c=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",h=o.bitDepth.toString().padStart(2,"0"),u=o.monochrome?"1":"0",m=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),p=s?.primaries?Ke[s.primaries]:1,g=s?.transfer?Xe[s.transfer]:1,w=s?.matrix?Ge[s.matrix]:1,b=s?.fullRange?1:0;let C=`av01.${c}.${l}${d}.${h}`;C+=`.${u}.${m.toString().padStart(3,"0")}`,C+=`.${p.toString().padStart(2,"0")}`,C+=`.${g.toString().padStart(2,"0")}`,C+=`.${w.toString().padStart(2,"0")}`,C+=`.${b}`;const v=".0.110.01.01.01.0";return C.endsWith(v)&&(C=C.slice(0,-v.length)),C}}throw new TypeError(`Unhandled codec '${e}'.`)},ui=(t,e,i)=>{if(t==="aac")return e>=2&&i<=24e3?"mp4a.40.29":i<=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(Q.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},zs=t=>{const{codec:e,codecDescription:i,aacCodecInfo:s}=t;if(e==="aac"){if(!s)throw new TypeError("AAC codec info must be provided.");return s.isMpeg2?"mp4a.67":`mp4a.40.${Us(i).objectType}`}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e&&Q.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Us=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new Te(t);let i=e.readBits(5);i===31&&(i=32+e.readBits(6));const s=e.readBits(4);let r=null;if(s===15)r=e.readBits(24);else{const o=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s<o.length&&(r=o[s])}const a=e.readBits(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:i,frequencyIndex:s,sampleRate:r,channelConfiguration:a,numberOfChannels:n}},fi=48e3,Ds=/^pcm-([usf])(\d+)+(be)?$/,ze=t=>{if(f(Q.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=Ds.exec(t);f(e);let i;e[1]==="u"?i="unsigned":e[1]==="s"?i="signed":i="float";const s=Number(e[2])/8,r=e[3]!=="be",a=t==="pcm-u8"?2**7:0;return{dataType:i,sampleSize:s,littleEndian:r,silentValue:a}},Vs=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":Ds.test(t)?t:t==="webvtt"?"webvtt":null,mi=t=>t==="avc"?{avc:{format:"avc"}}:t==="hevc"?{hevc:{format:"hevc"}}:{},pi=t=>t==="aac"?{aac:{format:"aac"}}:t==="opus"?{opus:{format:"opus"}}:{},Nt=class{constructor(t){this._factor=t}_toVideoBitrate(t,e,i){const s=e*i,r={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},c=(l=>2e6*Math.pow(l/2073600,.75))(s)*r[t]*this._factor;return Math.ceil(c/1e3)*1e3}_toAudioBitrate(t){if(Q.includes(t)||t==="flac")return-1;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[t];if(!i)throw new Error(`Unhandled codec: ${t}`);let s=i*this._factor;return t==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,n)=>Math.abs(n-s)<Math.abs(a-s)?n:a):t==="opus"||t==="vorbis"?s=Math.max(6e3,s):t==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,n)=>Math.abs(n-s)<Math.abs(a-s)?n:a)),Math.round(s/1e3)*1e3}},yn=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],bn=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,kn=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Sn=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,vn=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ns=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(!yn.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&&!At(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 i=Object.keys(Ke);if(e.primaries!=null&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const s=Object.keys(Xe);if(e.transfer!=null&&!s.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${s.join(", ")}.`);const r=Object.keys(Ge);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(!bn.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.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!kn.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if(t.decoderConfig.codec!=="vp8")throw new TypeError(