textmode.export.js 1.8.0-beta.2 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=class{$downloadFile(t,e){try{const i=this.t(e),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=i,n.style.display="none",n.rel="noopener",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}catch(i){console.error("[textmode-export] Failed to download file:",i)}}t(t){if(!t)return this.i();const e=t.trim();return e&&e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)||this.i()}i(){return`textmode-export-${/* @__PURE__ */(new Date).toISOString().slice(0,19).replace(/:/g,"-")}`}},n=/* @__PURE__ */new WeakMap;function o(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function s(t,e){let i=n.get(t);if(!i){i=/* @__PURE__ */new Map;for(const e of t.characters)i.set(o(e.color),e);n.set(t,i)}return i.get(e)}function a(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function h(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:a(t,e),layer:e}))}function c(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:a(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}function l(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var d=class extends i{o(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=l(t.primaryColorPixels,s),c=l(t.secondaryColorPixels,s);const d=this.$extractCellTransform(t.characterPixels,s);if(d.isInverted){const t=h;h=c,c=t}const u=this.o(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:d,position:u}),r++}return i}},u=class{h(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.l(e,i,r,o)}}l(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.h(h,a,l,d,s).toSVG()||null}},f=class{u;constructor(){this.u=new u}$generateSVGHeader(t){const{width:e,height:i}=t;return`<?xml version="1.0" encoding="UTF-8"?><svg width="${e}" height="${i}" viewBox="0 0 ${e} ${i}" xmlns="http://www.w3.org/2000/svg"><title>textmode.js sketch</title>`}$generateSVGFooter(){return"</g></svg>"}p(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}m(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}v(t,e,i,r){const n=s(i,t.encodedGlyphSlot);if(!n)return"";const o=this.u.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:a,g:h,b:c,a:l}=t.primaryColor,d=`rgba(${a},${h},${c},${l/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.m(t,e,r);o&&n.push(o);const s=this.v(t,e,i,r);if(s){const i=this.p(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},p=class{k(t){return{includeBackgroundRectangles:t.includeBackgroundRectangles??!0,drawMode:t.drawMode??"fill",strokeWidth:t.strokeWidth??1,filename:t.filename,layer:t.layer}}$generateSVG(t,e={}){const i=new d,r=new f,n=this.k(e),o=c(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new r).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}},m={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},w=class{k(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}T(t){if(!(t.format in m))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(/* @__PURE__ */new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},m[e.format])})}async $saveImage(t,e={}){const i=this.k(e);this.T(i);const n=await this.$toImageBlob(t,e);(new r).$downloadFile(n,i.filename)}async $toImageBlob(t,e={}){const i=this.k(e);return this.T(i),this.$generateImageBlob(t,i)}async $copyImageToClipboard(t,e={}){if("undefined"==typeof navigator||!navigator.clipboard||"function"!=typeof navigator.clipboard.write)throw new Error("Clipboard API is not available in this environment");const i=this.k(e);this.T(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[m[i.format]]:r});await navigator.clipboard.write([n])}},b=class{k(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}M(t,e){const r=new i,n=c(t,e.layer),o=r.$extractFramebufferData(n.drawFramebuffer),a=[];let h=0;for(let i=0;i<n.grid.rows;i++){let t="";for(let i=0;i<n.grid.cols;i++){const i=4*h,a=r.$getEncodedCharacterValue(o.characterPixels,i);t+=s(n.font,a)?.character||e.emptyCharacter,h++}e.preserveTrailingSpaces||(t=t.trimEnd()),a.push(t)}return a.join("\n")}$generateTXT(t,e={}){return this.M(t,this.k(e))}$saveTXT(t,e={}){const i=this.k(e),n=this.M(t,i),o=new Blob([n],{type:"text/plain;charset=utf-8"});(new r).$downloadFile(o,i.filename)}},y=/* @__PURE__ */e(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>_,applyPalette:()=>y,default:()=>P,nearestColor:()=>M,nearestColorIndex:()=>k,nearestColorIndexWithDistance:()=>T,prequantize:()=>b,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,b=m,y=(1<<b)-1;const v=1<<p-1,g=v+1;let x=v+2,E=0,k=i[0],T=0;for(let r=l;r<65536;r*=2)++T;T=8-T,s.writeByte(d),_(v);const M=i.length;for(let r=1;r<M;r++)t:{const t=i[r],e=(t<<12)+k;let n=t<<T^k;if(h[n]===e){k=c[n];break t}const o=0===n?1:l-n;for(;h[n]>=0;)if(n-=o,n<0&&(n+=l),h[n]===e){k=c[n];break t}_(k),k=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=v+2,w=!0,_(v))}return _(k),_(g),s.writeByte(0),s.bytesView();function _(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=b;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>y||w)&&(w?(b=m,y=(1<<b)-1,w=!1):(++b,y=12===b?1<<b:(1<<b)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let b=!1!==i.useSqrt;const y="rgba4444"===r,v=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=v.length,x=g-1,E=new Uint32Array(g+1);for(var k=0,T=0;T<g;++T){const t=v[T];if(null!=t){var M=1/t.cnt;y&&(t.ac*=M),t.rc*=M,t.gc*=M,t.bc*=M,v[k++]=t}}var _,C,A;for(l(e)/k<.022&&(b=!1),T=0;T<k-1;++T)v[T].fw=T+1,v[T+1].bk=T,b&&(v[T].cnt=Math.sqrt(v[T].cnt));for(b&&(v[T].cnt=Math.sqrt(v[T].cnt)),T=0;T<k;++T){d(v,T,!1);var S=v[T].err;for(C=++E[0];C>1&&!(v[_=E[A=C>>1]].err<=S);C=A)E[C]=_;E[C]=T}var B=k-e;for(T=0;T<B;){for(var P;;){var I=E[1];if((P=v[I]).tm>=P.mtm&&v[P.nn].mtm<=P.tm)break;for(P.mtm==x?I=E[1]=E[E[0]--]:(d(v,I,!1),P.tm=T),S=v[I].err,C=1;(A=C+C)<=E[0]&&(A<E[0]&&v[E[A]].err>v[E[A+1]].err&&A++,!(S<=v[_=E[A]].err));C=A)E[C]=_;E[C]=I}var $=v[P.nn],F=P.cnt,V=$.cnt;M=1/(F+V),y&&(P.ac=M*(F*P.ac+V*$.ac)),P.rc=M*(F*P.rc+V*$.rc),P.gc=M*(F*P.gc+V*$.gc),P.bc=M*(F*P.bc+V*$.bc),P.cnt+=$.cnt,P.mtm=++T,v[$.bk].fw=$.fw,v[$.fw].bk=$.bk,$.mtm=x}let O=[];var D=0;for(T=0;;++D){let t=c(Math.round(v[T].rc),0,255),e=c(Math.round(v[T].gc),0,255),i=c(Math.round(v[T].bc),0,255),r=255;y&&(r=c(Math.round(v[T].ac),0,255),m&&(r=r<=("number"==typeof m?m:127)?0:255),n&&r<=f&&(t=e=i=o,r=0));const s=y?[t,e,i,r]:[t,e,i];if(p(O,s)||O.push(s),0==(T=v[T].fw))break}return O}function p(t,e){for(let i=0;i<t.length;i++){const r=t[i];let n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],o=!(r.length>=4&&e.length>=4)||r[3]===e[3];if(n&&o)return!0}return!1}function m(t,e){var i,r=0;for(i=0;i<t.length;i++){const n=t[i]-e[i];r+=n*n}return r}function w(t,e){return e>1?Math.round(t/e)*e:t}function b(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function y(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=v(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function v(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=T(r,i.slice(0,3),m),h=a[0],c=a[1];c>0&&c<=n&&(t[h]=i)}}function E(t){return t*t}function k(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return n}function T(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return[n,r]}function M(t,e,i=m){return t[k(t,e,i)]}function _(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:b=8,dispose:y=-1}=r;let v=!1;if(n?l||(v=!0,d(),l=!0):v=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),v){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|B(r.length)-1;A(t,e),A(t,i),t.writeBytes([o,0,0])}(s,e,i,m,b),C(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),S(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),A(t,e),t.writeByte(0)}(s,w)}const g=Math.round(p/10);!function(t,e,i,r,n){var o,s;t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1),r?(o=1,s=2):(o=0,s=0),e>=0&&(s=7&e),s<<=2,t.writeByte(0|s|o),A(t,i),t.writeByte(n||0),t.writeByte(0)}(s,y,g,u,f);const x=Boolean(m)&&!v;!function(t,e,i,r){if(t.writeByte(44),A(t,0),A(t,0),A(t,e),A(t,i),r){const e=B(r.length)-1;t.writeByte(128|e)}else t.writeByte(0)}(s,e,i,x?m:null),x&&C(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,b,a,h,c)}};function d(){S(s,"GIF89a")}}function C(t,e){const i=1<<B(e.length);for(let r=0;r<i;r++){let i=[0,0,0];r<e.length&&(i=e[r]),t.writeByte(i[0]),t.writeByte(i[1]),t.writeByte(i[2])}}function A(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function S(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function B(t){return Math.max(Math.ceil(Math.log2(t)),1)}var P=_}),v=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function g(){return new v("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function x(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(g());let s=!1;const a=setTimeout(()=>h(()=>o(function(t){return new v("VIDEO_EXPORT_TIMEOUT",t,void 0)}(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(g()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var E=class{canvas;_;C;A;S;B=null;P=0;I=0;constructor(t,e,i,r){this._=t,this.C=e,this.S=t.canvas,this.canvas=this.$(i,r);const n=this.canvas.getContext("2d");if(!n)throw new Error("Video export requires a 2D canvas context for staging frames.");n.imageSmoothingEnabled=!1,this.A=n}async $render(t){const e=this._,i=Math.max(1,Math.round(t.frameCount)),r=Math.max(1,Math.round(t.frameRate)),n=1e3/r,o=e.isLooping(),s=e.frameCount,a=e.millis,h="secs"in e,c=e.secs,l=this.F(),d=this.V(),u=this.C(()=>{this.O()});try{e.noLoop(),this.P=s,this.I=a,this.D(h),this.U(r,n),this.R();for(let e=0;e<i;e++)this.N(t.signal),this.P=s+e+1,this.I=1e3*e/r,await(t.prepareFrame?.({frameIndex:e,frameCount:i,timeSeconds:e/r,frameRate:r,signal:t.signal})),this.N(t.signal),await this.j(e,t.signal),this.N(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas})}finally{u(),this.B?.reject(/* @__PURE__ */new Error("Video export frame rendering was interrupted.")),this.B=null,this.L(d),this.H(l),e.frameCount=s,e.millis=a,h&&void 0!==c&&(e.secs=c),o?e.loop():e.noLoop()}}j(t,e){if(this.B)throw new Error("A video export frame is already pending.");const i=this._;return x(new Promise((e,r)=>{this.B={frameIndex:t,resolve:e,reject:r};try{i.redraw(1)}catch(n){this.B=null,r(n)}}),`Video export frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.B?.frameIndex===t&&(this.B=null),e})}O(){const t=this.B;if(t)try{this.A.clearRect(0,0,this.canvas.width,this.canvas.height),this.A.drawImage(this.S,0,0,this.S.width,this.S.height,0,0,this.canvas.width,this.canvas.height),this.B=null,t.resolve()}catch(e){this.B=null,t.reject(e)}}$(t,e){const i=document.createElement("canvas");return i.width=Math.max(1,Math.round(t)),i.height=Math.max(1,Math.round(e)),i}F(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),value:this._[t]}))}V(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),descriptor:Object.getOwnPropertyDescriptor(this._,t)}))}D(t){Object.defineProperty(this._,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.P,set:t=>{this.P=t}}),Object.defineProperty(this._,"millis",{configurable:!0,enumerable:!0,get:()=>this.I,set:t=>{this.I=t}}),t&&Object.defineProperty(this._,"secs",{configurable:!0,enumerable:!0,get:()=>this.I/1e3,set:t=>{this.I=1e3*t}})}U(t,e){const i=this._,r=i.frameRate;i.deltaTime=()=>e,i.frameRate=function(e){return void 0===e?t:r.call(this,e)}}R(){this._.resizeCanvas=()=>{}}H(t){const e=this._;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}L(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this._,e.key,e.descriptor):delete this._[e.key]}N(t){if(t?.aborted)throw g()}},k='(function() {\n\tvar r = ((t, r) => () => (r || (t((r = { exports: {} }).exports, r), t = null), r.exports))((t) => {\n\t\tvar r = Object.defineProperty;\n\t\tr(t, "__esModule", { value: !0 }), ((t, e) => {\n\t\t\tfor (var n in e) r(t, n, {\n\t\t\t\tget: e[n],\n\t\t\t\tenumerable: !0\n\t\t\t});\n\t\t})(t, {\n\t\t\tGIFEncoder: () => I,\n\t\t\tapplyPalette: () => b,\n\t\t\tdefault: () => x,\n\t\t\tnearestColor: () => C,\n\t\t\tnearestColorIndex: () => k,\n\t\t\tnearestColorIndexWithDistance: () => U,\n\t\t\tprequantize: () => A,\n\t\t\tquantize: () => y,\n\t\t\tsnapColorsToPalette: () => v\n\t\t});\n\t\tvar e = {\n\t\t\tsignature: "GIF",\n\t\t\tversion: "89a",\n\t\t\ttrailer: 59,\n\t\t\textensionIntroducer: 33,\n\t\t\tapplicationExtensionLabel: 255,\n\t\t\tgraphicControlExtensionLabel: 249,\n\t\t\timageSeparator: 44,\n\t\t\tsignatureSize: 3,\n\t\t\tversionSize: 3,\n\t\t\tglobalColorTableFlagMask: 128,\n\t\t\tcolorResolutionMask: 112,\n\t\t\tsortFlagMask: 8,\n\t\t\tglobalColorTableSizeMask: 7,\n\t\t\tapplicationIdentifierSize: 8,\n\t\t\tapplicationAuthCodeSize: 3,\n\t\t\tdisposalMethodMask: 28,\n\t\t\tuserInputFlagMask: 2,\n\t\t\ttransparentColorFlagMask: 1,\n\t\t\tlocalColorTableFlagMask: 128,\n\t\t\tinterlaceFlagMask: 64,\n\t\t\tidSortFlagMask: 32,\n\t\t\tlocalColorTableSizeMask: 7\n\t\t};\n\t\tfunction n(t = 256) {\n\t\t\tlet r = 0, e = new Uint8Array(t);\n\t\t\treturn {\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn e.buffer;\n\t\t\t\t},\n\t\t\t\treset() {\n\t\t\t\t\tr = 0;\n\t\t\t\t},\n\t\t\t\tbytesView: () => e.subarray(0, r),\n\t\t\t\tbytes: () => e.slice(0, r),\n\t\t\t\twriteByte(t) {\n\t\t\t\t\tn(r + 1), e[r] = t, r++;\n\t\t\t\t},\n\t\t\t\twriteBytes(t, o = 0, a = t.length) {\n\t\t\t\t\tn(r + a);\n\t\t\t\t\tfor (let n = 0; n < a; n++) e[r++] = t[n + o];\n\t\t\t\t},\n\t\t\t\twriteBytesView(t, o = 0, a = t.byteLength) {\n\t\t\t\t\tn(r + a), e.set(t.subarray(o, o + a), r), r += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction n(t) {\n\t\t\t\tvar n = e.length;\n\t\t\t\tif (n >= t) return;\n\t\t\t\tt = Math.max(t, n * (n < 1048576 ? 2 : 1.125) >>> 0), 0 != n && (t = Math.max(t, 256));\n\t\t\t\tconst o = e;\n\t\t\t\te = new Uint8Array(t), r > 0 && e.set(o.subarray(0, r), 0);\n\t\t\t}\n\t\t}\n\t\tvar o = [\n\t\t\t0,\n\t\t\t1,\n\t\t\t3,\n\t\t\t7,\n\t\t\t15,\n\t\t\t31,\n\t\t\t63,\n\t\t\t127,\n\t\t\t255,\n\t\t\t511,\n\t\t\t1023,\n\t\t\t2047,\n\t\t\t4095,\n\t\t\t8191,\n\t\t\t16383,\n\t\t\t32767,\n\t\t\t65535\n\t\t], a = function(t, r, e, a, i = n(512), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003)) {\n\t\t\tconst s = c.length, u = Math.max(2, a);\n\t\t\tl.fill(0), f.fill(0), c.fill(-1);\n\t\t\tlet p = 0, y = 0;\n\t\t\tconst h = u + 1, w = h;\n\t\t\tlet d = !1, A = w, b = (1 << A) - 1;\n\t\t\tconst M = 1 << h - 1, g = M + 1;\n\t\t\tlet v = M + 2, m = 0, k = e[0], U = 0;\n\t\t\tfor (let n = s; n < 65536; n *= 2) ++U;\n\t\t\tU = 8 - U, i.writeByte(u), I(M);\n\t\t\tconst C = e.length;\n\t\t\tfor (let n = 1; n < C; n++) t: {\n\t\t\t\tconst t = e[n], r = (t << 12) + k;\n\t\t\t\tlet o = t << U ^ k;\n\t\t\t\tif (c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tconst a = 0 === o ? 1 : s - o;\n\t\t\t\tfor (; c[o] >= 0;) if (o -= a, o < 0 && (o += s), c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tI(k), k = t, v < 4096 ? (f[o] = v++, c[o] = r) : (c.fill(-1), v = M + 2, d = !0, I(M));\n\t\t\t}\n\t\t\treturn I(k), I(g), i.writeByte(0), i.bytesView();\n\t\t\tfunction I(t) {\n\t\t\t\tfor (p &= o[y], y > 0 ? p |= t << y : p = t, y += A; y >= 8;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\tif ((v > b || d) && (d ? (A = w, b = (1 << A) - 1, d = !1) : (++A, b = 12 === A ? 1 << A : (1 << A) - 1)), t == g) {\n\t\t\t\t\tfor (; y > 0;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\t\tm > 0 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfunction i(t, r, e) {\n\t\t\treturn t << 8 & 63488 | r << 2 & 992 | e >> 3;\n\t\t}\n\t\tfunction l(t, r, e, n) {\n\t\t\treturn t >> 4 | 240 & r | (240 & e) << 4 | (240 & n) << 8;\n\t\t}\n\t\tfunction c(t, r, e) {\n\t\t\treturn t >> 4 << 8 | 240 & r | e >> 4;\n\t\t}\n\t\tfunction f(t, r, e) {\n\t\t\treturn t < r ? r : t > e ? e : t;\n\t\t}\n\t\tfunction s(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction u(t, r, e) {\n\t\t\tvar n = 0, o = 1e100;\n\t\t\tconst a = t[r], i = a.cnt, l = a.ac, c = a.rc, f = a.gc, u = a.bc;\n\t\t\tfor (var p = a.fw; 0 != p; p = t[p].fw) {\n\t\t\t\tconst r = t[p], a = r.cnt, h = i * a / (i + a);\n\t\t\t\tif (!(h >= o)) {\n\t\t\t\t\tvar y = 0;\n\t\t\t\t\te && (y += h * s(r.ac - l)) >= o || (y += h * s(r.rc - c)) >= o || (y += h * s(r.gc - f)) >= o || (y += h * s(r.bc - u)) >= o || (o = y, n = p);\n\t\t\t\t}\n\t\t\t}\n\t\t\ta.err = o, a.nn = n;\n\t\t}\n\t\tfunction p() {\n\t\t\treturn {\n\t\t\t\tac: 0,\n\t\t\t\trc: 0,\n\t\t\t\tgc: 0,\n\t\t\t\tbc: 0,\n\t\t\t\tcnt: 0,\n\t\t\t\tnn: 0,\n\t\t\t\tfw: 0,\n\t\t\t\tbk: 0,\n\t\t\t\ttm: 0,\n\t\t\t\tmtm: 0,\n\t\t\t\terr: 0\n\t\t\t};\n\t\t}\n\t\tfunction y(t, r, e = {}) {\n\t\t\tconst { format: n = "rgb565", clearAlpha: o = !0, clearAlphaColor: a = 0, clearAlphaThreshold: y = 0, oneBitAlpha: w = !1 } = e;\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tconst d = new Uint32Array(t.buffer);\n\t\t\tlet A = !1 !== e.useSqrt;\n\t\t\tconst b = "rgba4444" === n, M = function(t, r) {\n\t\t\t\tconst e = new Array("rgb444" === r ? 4096 : 65536), n = t.length;\n\t\t\t\tif ("rgba4444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 24 & 255, a = r >> 16 & 255, i = r >> 8 & 255, c = 255 & r, f = l(c, i, a, n);\n\t\t\t\t\tlet s = f in e ? e[f] : e[f] = p();\n\t\t\t\t\ts.rc += c, s.gc += i, s.bc += a, s.ac += n, s.cnt++;\n\t\t\t\t}\n\t\t\t\telse if ("rgb444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, i = 255 & r, l = c(i, a, n);\n\t\t\t\t\tlet f = l in e ? e[l] : e[l] = p();\n\t\t\t\t\tf.rc += i, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\telse for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, l = 255 & r, c = i(l, a, n);\n\t\t\t\t\tlet f = c in e ? e[c] : e[c] = p();\n\t\t\t\t\tf.rc += l, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}(d, n), g = M.length, v = g - 1, m = new Uint32Array(g + 1);\n\t\t\tfor (var k = 0, U = 0; U < g; ++U) {\n\t\t\t\tconst t = M[U];\n\t\t\t\tif (null != t) {\n\t\t\t\t\tvar C = 1 / t.cnt;\n\t\t\t\t\tb && (t.ac *= C), t.rc *= C, t.gc *= C, t.bc *= C, M[k++] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar I, F, z;\n\t\t\tfor (s(r) / k < .022 && (A = !1), U = 0; U < k - 1; ++U) M[U].fw = U + 1, M[U + 1].bk = U, A && (M[U].cnt = Math.sqrt(M[U].cnt));\n\t\t\tfor (A && (M[U].cnt = Math.sqrt(M[U].cnt)), U = 0; U < k; ++U) {\n\t\t\t\tu(M, U, !1);\n\t\t\t\tvar B = M[U].err;\n\t\t\t\tfor (F = ++m[0]; F > 1 && !(M[I = m[z = F >> 1]].err <= B); F = z) m[F] = I;\n\t\t\t\tm[F] = U;\n\t\t\t}\n\t\t\tvar E = k - r;\n\t\t\tfor (U = 0; U < E;) {\n\t\t\t\tfor (var x;;) {\n\t\t\t\t\tvar G = m[1];\n\t\t\t\t\tif ((x = M[G]).tm >= x.mtm && M[x.nn].mtm <= x.tm) break;\n\t\t\t\t\tfor (x.mtm == v ? G = m[1] = m[m[0]--] : (u(M, G, !1), x.tm = U), B = M[G].err, F = 1; (z = F + F) <= m[0] && (z < m[0] && M[m[z]].err > M[m[z + 1]].err && z++, !(B <= M[I = m[z]].err)); F = z) m[F] = I;\n\t\t\t\t\tm[F] = G;\n\t\t\t\t}\n\t\t\t\tvar S = M[x.nn], T = x.cnt, q = S.cnt;\n\t\t\t\tC = 1 / (T + q), b && (x.ac = C * (T * x.ac + q * S.ac)), x.rc = C * (T * x.rc + q * S.rc), x.gc = C * (T * x.gc + q * S.gc), x.bc = C * (T * x.bc + q * S.bc), x.cnt += S.cnt, x.mtm = ++U, M[S.bk].fw = S.fw, M[S.fw].bk = S.bk, S.mtm = v;\n\t\t\t}\n\t\t\tlet R = [];\n\t\t\tvar P = 0;\n\t\t\tfor (U = 0;; ++P) {\n\t\t\t\tlet t = f(Math.round(M[U].rc), 0, 255), r = f(Math.round(M[U].gc), 0, 255), e = f(Math.round(M[U].bc), 0, 255), n = 255;\n\t\t\t\tb && (n = f(Math.round(M[U].ac), 0, 255), w && (n = n <= ("number" == typeof w ? w : 127) ? 0 : 255), o && n <= y && (t = r = e = a, n = 0));\n\t\t\t\tconst i = b ? [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te,\n\t\t\t\t\tn\n\t\t\t\t] : [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te\n\t\t\t\t];\n\t\t\t\tif (h(R, i) || R.push(i), 0 == (U = M[U].fw)) break;\n\t\t\t}\n\t\t\treturn R;\n\t\t}\n\t\tfunction h(t, r) {\n\t\t\tfor (let e = 0; e < t.length; e++) {\n\t\t\t\tconst n = t[e];\n\t\t\t\tlet o = n[0] === r[0] && n[1] === r[1] && n[2] === r[2], a = !(n.length >= 4 && r.length >= 4) || n[3] === r[3];\n\t\t\t\tif (o && a) return !0;\n\t\t\t}\n\t\t\treturn !1;\n\t\t}\n\t\tfunction w(t, r) {\n\t\t\tvar e, n = 0;\n\t\t\tfor (e = 0; e < t.length; e++) {\n\t\t\t\tconst o = t[e] - r[e];\n\t\t\t\tn += o * o;\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\t\tfunction d(t, r) {\n\t\t\treturn r > 1 ? Math.round(t / r) * r : t;\n\t\t}\n\t\tfunction A(t, { roundRGB: r = 5, roundAlpha: e = 10, oneBitAlpha: n = null } = {}) {\n\t\t\tconst o = new Uint32Array(t.buffer);\n\t\t\tfor (let a = 0; a < o.length; a++) {\n\t\t\t\tconst t = o[a];\n\t\t\t\tlet i = t >> 24 & 255, l = t >> 16 & 255, c = t >> 8 & 255, f = 255 & t;\n\t\t\t\ti = d(i, e), n && (i = i <= ("number" == typeof n ? n : 127) ? 0 : 255), f = d(f, r), c = d(c, r), l = d(l, r), o[a] = i << 24 | l << 16 | c << 8 | f;\n\t\t\t}\n\t\t}\n\t\tfunction b(t, r, e = "rgb565") {\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (r.length > 256) throw new Error("applyPalette() only works with 256 colors or less");\n\t\t\tconst n = new Uint32Array(t.buffer), o = n.length, a = "rgb444" === e ? 4096 : 65536, f = new Uint8Array(o), s = new Array(a);\n\t\t\tif ("rgba4444" === e) for (let i = 0; i < o; i++) {\n\t\t\t\tconst t = n[i], e = t >> 24 & 255, o = t >> 16 & 255, a = t >> 8 & 255, c = 255 & t, u = l(c, a, o, e);\n\t\t\t\tf[i] = u in s ? s[u] : s[u] = M(c, a, o, e, r);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst t = "rgb444" === e ? c : i;\n\t\t\t\tfor (let e = 0; e < o; e++) {\n\t\t\t\t\tconst o = n[e], a = o >> 16 & 255, i = o >> 8 & 255, l = 255 & o, c = t(l, i, a);\n\t\t\t\t\tf[e] = c in s ? s[c] : s[c] = g(l, i, a, r);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f;\n\t\t}\n\t\tfunction M(t, r, e, n, o) {\n\t\t\tlet a = 0, i = 1e100;\n\t\t\tfor (let l = 0; l < o.length; l++) {\n\t\t\t\tconst c = o[l];\n\t\t\t\tlet f = m(c[3] - n);\n\t\t\t\tf > i || (f += m(c[0] - t), f > i || (f += m(c[1] - r), f > i || (f += m(c[2] - e), f > i || (i = f, a = l))));\n\t\t\t}\n\t\t\treturn a;\n\t\t}\n\t\tfunction g(t, r, e, n) {\n\t\t\tlet o = 0, a = 1e100;\n\t\t\tfor (let i = 0; i < n.length; i++) {\n\t\t\t\tconst l = n[i];\n\t\t\t\tlet c = m(l[0] - t);\n\t\t\t\tc > a || (c += m(l[1] - r), c > a || (c += m(l[2] - e), c > a || (a = c, o = i)));\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction v(t, r, e = 5) {\n\t\t\tif (!t.length || !r.length) return;\n\t\t\tconst n = t.map((t) => t.slice(0, 3)), o = e * e, a = t[0].length;\n\t\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\t\tlet e = r[i];\n\t\t\t\te = e.length < a ? [\n\t\t\t\t\te[0],\n\t\t\t\t\te[1],\n\t\t\t\t\te[2],\n\t\t\t\t\t255\n\t\t\t\t] : e.length > a ? e.slice(0, 3) : e.slice();\n\t\t\t\tconst l = U(n, e.slice(0, 3), w), c = l[0], f = l[1];\n\t\t\t\tf > 0 && f <= o && (t[c] = e);\n\t\t\t}\n\t\t}\n\t\tfunction m(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction k(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction U(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn [o, n];\n\t\t}\n\t\tfunction C(t, r, e = w) {\n\t\t\treturn t[k(t, r, e)];\n\t\t}\n\t\tfunction I(t = {}) {\n\t\t\tconst { initialCapacity: r = 4096, auto: o = !0 } = t, i = n(r), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003);\n\t\t\tlet s = !1;\n\t\t\treturn {\n\t\t\t\treset() {\n\t\t\t\t\ti.reset(), s = !1;\n\t\t\t\t},\n\t\t\t\tfinish() {\n\t\t\t\t\ti.writeByte(e.trailer);\n\t\t\t\t},\n\t\t\t\tbytes: () => i.bytes(),\n\t\t\t\tbytesView: () => i.bytesView(),\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn i.buffer;\n\t\t\t\t},\n\t\t\t\tget stream() {\n\t\t\t\t\treturn i;\n\t\t\t\t},\n\t\t\t\twriteHeader: u,\n\t\t\t\twriteFrame(t, r, e, n = {}) {\n\t\t\t\t\tconst { transparent: p = !1, transparentIndex: y = 0, delay: h = 0, palette: w = null, repeat: d = 0, colorDepth: A = 8, dispose: b = -1 } = n;\n\t\t\t\t\tlet M = !1;\n\t\t\t\t\tif (o ? s || (M = !0, u(), s = !0) : M = Boolean(n.first), r = Math.max(0, Math.floor(r)), e = Math.max(0, Math.floor(e)), M) {\n\t\t\t\t\t\tif (!w) throw new Error("First frame must include a { palette } option");\n\t\t\t\t\t\t(function(t, r, e, n, o = 8) {\n\t\t\t\t\t\t\tconst a = o - 1 << 4 | 128 | E(n.length) - 1;\n\t\t\t\t\t\t\tz(t, r), z(t, e), t.writeBytes([\n\t\t\t\t\t\t\t\ta,\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t})(i, r, e, w, A), F(i, w), d >= 0 && function(t, r) {\n\t\t\t\t\t\t\tt.writeByte(33), t.writeByte(255), t.writeByte(11), B(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), z(t, r), t.writeByte(0);\n\t\t\t\t\t\t}(i, d);\n\t\t\t\t\t}\n\t\t\t\t\tconst g = Math.round(h / 10);\n\t\t\t\t\t(function(t, r, e, n, o) {\n\t\t\t\t\t\tvar a, i;\n\t\t\t\t\t\tt.writeByte(33), t.writeByte(249), t.writeByte(4), o < 0 && (o = 0, n = !1), n ? (a = 1, i = 2) : (a = 0, i = 0), r >= 0 && (i = 7 & r), i <<= 2, t.writeByte(0 | i | a), z(t, e), t.writeByte(o || 0), t.writeByte(0);\n\t\t\t\t\t})(i, b, g, p, y);\n\t\t\t\t\tconst v = Boolean(w) && !M;\n\t\t\t\t\t(function(t, r, e, n) {\n\t\t\t\t\t\tif (t.writeByte(44), z(t, 0), z(t, 0), z(t, r), z(t, e), n) {\n\t\t\t\t\t\t\tconst r = E(n.length) - 1;\n\t\t\t\t\t\t\tt.writeByte(128 | r);\n\t\t\t\t\t\t} else t.writeByte(0);\n\t\t\t\t\t})(i, r, e, v ? w : null), v && F(i, w), function(t, r, e, n, o = 8, i, l, c) {\n\t\t\t\t\t\ta(e, n, r, o, t, i, l, c);\n\t\t\t\t\t}(i, t, r, e, A, l, c, f);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction u() {\n\t\t\t\tB(i, "GIF89a");\n\t\t\t}\n\t\t}\n\t\tfunction F(t, r) {\n\t\t\tconst e = 1 << E(r.length);\n\t\t\tfor (let n = 0; n < e; n++) {\n\t\t\t\tlet e = [\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t\t];\n\t\t\t\tn < r.length && (e = r[n]), t.writeByte(e[0]), t.writeByte(e[1]), t.writeByte(e[2]);\n\t\t\t}\n\t\t}\n\t\tfunction z(t, r) {\n\t\t\tt.writeByte(255 & r), t.writeByte(r >> 8 & 255);\n\t\t}\n\t\tfunction B(t, r) {\n\t\t\tfor (var e = 0; e < r.length; e++) t.writeByte(r.charCodeAt(e));\n\t\t}\n\t\tfunction E(t) {\n\t\t\treturn Math.max(Math.ceil(Math.log2(t)), 1);\n\t\t}\n\t\tvar x = I;\n\t})();\n\tconst e = (0, r.GIFEncoder)();\n\tlet n = 1, o = 1, a = 16, i = 0;\n\tconst l = self;\n\tl.addEventListener("message", (t) => {\n\t\tconst c = t.data;\n\t\ttry {\n\t\t\tif ("init" === c.type) return n = c.width ?? n, o = c.height ?? o, a = c.delay ?? a, i = c.repeat ?? i, void l.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "ready"\n\t\t\t});\n\t\t\tif ("frame" === c.type && c.buffer) {\n\t\t\t\tconst t = new Uint8ClampedArray(c.buffer), f = (0, r.quantize)(t, 256, {}), s = (0, r.applyPalette)(t, f);\n\t\t\t\te.writeFrame(s, n, o, {\n\t\t\t\t\tpalette: f,\n\t\t\t\t\tdelay: a,\n\t\t\t\t\trepeat: 0 === c.frameIndex ? i : -1\n\t\t\t\t}), l.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "frame-complete"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ("finish" === c.type) {\n\t\t\t\te.finish();\n\t\t\t\tconst t = e.bytes(), r = t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength);\n\t\t\t\tl.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "complete",\n\t\t\t\t\tbuffer: r\n\t\t\t\t}, [r]);\n\t\t\t}\n\t\t} catch (f) {\n\t\t\tl.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "error",\n\t\t\t\tmessage: f instanceof Error ? f.message : "GIF worker failed"\n\t\t\t});\n\t\t}\n\t});\n})();\n',T="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",k],{type:"text/javascript;charset=utf-8"});function M(t){let e;try{if(e=T&&(self.URL||self.webkitURL).createObjectURL(T),!e)throw"";const i=new Worker(e,{name:t?.name});return i.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),i}catch(i){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(k),{name:t?.name})}}var _=class{G;q=/* @__PURE__ */new Map;W;X=0;Y=!1;constructor(t,e,i,r,n){this.G=new M,this.G.addEventListener("message",this.J),this.G.addEventListener("error",this.K),n?.addEventListener("abort",this.dispose,{once:!0}),this.W=this.Z({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.W,await this.Z({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.W;const t=await this.Z({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.Y){this.Y=!0,this.G.terminate();for(const t of this.q.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.q.clear()}};Z(t,e=[]){if(this.Y)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.X;return new Promise((r,n)=>{this.q.set(i,{resolve:r,reject:n}),this.G.postMessage({...t,id:i},e)})}J=t=>{const e=t.data,i=this.q.get(e.id);i&&(this.q.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};K=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.q.values())i.reject(e);this.q.clear()}},C=y(),A=class{_;C;constructor(t,e){this._=t,this.C=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new r).$downloadFile(e,t.filename)}async $generateGIFBlob(t={}){const e=this.k(t),i=this._.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new E(this._,this.C,r,n),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,C.GIFEncoder)():null,h="undefined"==typeof Worker?null:new _(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.N(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.N(e.signal);const n=s.getImageData(0,0,r.width,r.height);if(h)await h.encodeFrame(n.data.buffer,i);else if(a){const t=n.data,o=(0,C.quantize)(t,256,{}),s=(0,C.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.tt(e.signal)}}),this.N(e.signal),h)i=await h.finish();else{if(!a)throw new Error("No GIF encoder is available.");{a.finish();const t=a.bytes();i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}return t.onProgress?.({state:"completed",totalFrames:e.frameCount}),new Blob([i],{type:"image/gif"})}catch(c){throw t.onProgress?.({state:"error",message:c instanceof Error?c.message:"GIF export failed"}),c}finally{h?.dispose()}}k(t){return{filename:t.filename,frameCount:Math.max(1,Math.abs(Math.round(t.frameCount??300))),frameRate:Math.max(1,Math.abs(t.frameRate??60)),scale:Math.max(Number.EPSILON,Math.abs(t.scale??1)),repeat:Math.max(-1,Math.round(t.repeat??0)),signal:t.signal,prepareFrame:t.prepareFrame}}N(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}tt(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}};function S(t){if(!t)throw new Error("Assertion failed.")}var B,P=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},I=t=>t&&t[t.length-1],$=t=>t>=0&&t<2**32,F=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},V=t=>{const e=F(t);return 1&e?e+1>>1:-(e>>1)},O=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),D=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),U=/* #__PURE__ */new TextEncoder,R={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},N={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},z={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},j=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),L=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),H=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}},G=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},q=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},W=t=>{throw new Error(`Unexpected value: ${t}`)},X=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2);return i?r|n<<8|o<<16:r<<16|n<<8|o},Y=(t,e,i)=>Math.max(e,Math.min(i,t)),Q=(t,e)=>Math.round(t/e)*e,J=(t,e)=>Math.round(t*e)/e,K=(t,e)=>Math.floor(t*e)/e,Z=/^[a-z]{3}$/,tt=1e6*(1+Number.EPSILON),et=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},it=null,rt=()=>null!==it?it:it="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),nt=null,ot=()=>null!==nt?nt:nt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),st=null,at=()=>{if(null!==st)return st;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?st=Number(t[1]):null},ht=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},ct=t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},lt=(t,e)=>{if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},dt=t=>{S(Number.isInteger(t.num)),S(Number.isInteger(t.den)),S(0!==t.den);let e=Math.abs(t.num),i=Math.abs(t.den);for(;0!==i;){const t=e%i;e=i,i=t}const r=e||1;return{num:t.num/r,den:t.den/r}},ut=(t,e)=>{if("object"!=typeof t||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},ft=t=>Array.isArray(t)?t:[t],pt=class{constructor(){this.et=/* @__PURE__ */new Map}on(t,e,i){this.et.has(t)||this.et.set(t,/* @__PURE__ */new Set);const r={fn:e,once:i?.once??!1};return this.et.get(t).add(r),()=>{this.et.get(t)?.delete(r)}}it(...t){const[e,i]=t,r=this.et.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},mt=t=>null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(t=>"string"==typeof t);!function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"}(B||(B={}));var wt=class t{constructor(){}static get level(){return t.rt}static set level(e){if(e!==B.Silent&&e!==B.Errors&&e!==B.Warnings&&e!==B.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.rt=e}static get nt(){return t.ot??=new pt}static on(e,i,r){return t.nt.on(e,i,r)}static st(...e){t.nt.it("error",e),t.rt>=B.Errors&&console.error(...e)}static ht(...e){t.nt.it("warn",e),t.rt>=B.Warnings&&console.warn(...e)}static ct(...e){t.nt.it("info",e),t.rt>=B.Info&&console.info(...e)}};wt.rt=B.Info,wt.ot=null;var bt,yt,vt=class{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof e)throw new TypeError("mimeType must be a string.")}},gt=class{constructor(t,e,i,r){if(this.data=t,this.mimeType=e,this.name=i,this.description=r,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==e&&"string"!=typeof e)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}},xt=class t{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let r=this.pos;r<i;r++){const t=Math.floor(r/8);let n=this.bytes[t];const o=7-(7&r);n&=~(1<<o),n|=(e&1<<i-r-1)>>i-r-1<<o,this.bytes[t]=n}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new t(this.bytes);return e.pos=this.pos,e}},Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],kt=[-1,1,2,3,4,5,6,8],Tt=t=>{let e=Et.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const r=kt.indexOf(t.numberOfChannels);if(-1===r)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),15===e&&(n+=24);const o=Math.ceil(n/8),s=new Uint8Array(o),a=new xt(s);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),15===e&&a.writeBits(24,i),a.writeBits(4,r),s},Mt=["avc","hevc","vp9","av1","vp8","prores"],_t=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Ct=["aac","opus","mp3","vorbis","flac","ac3","eac3"],At=[...Ct,..._t],St=["webvtt"],Bt=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Pt=[{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}],It=[{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}],$t=[{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}],Ft=["ap4x","ap4h","apch","apcn","apcs","apco"],Vt=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Ot=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Bt.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??I(Bt),s=o?o.level:0;return`avc1.${t.toString(16).padStart(2,"0")}00${s.toString(16).padStart(2,"0")}`}if("hevc"===t){const t="",n=1,o="6",s=e*i,a=Pt.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??I(Pt);return`hev1.${t}${n}.${o}.${a.tier}${a.level}.B0`}if("vp8"===t)return"vp8";if("vp9"===t){const t=e*i;return`vp09.00.${(It.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??I(It)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=$t.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??I($t);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Vt.filter(t=>t.alpha===n);let s=o[0].fourCc,a=1/0;for(const{fourCc:e,bitrate:i}of o){const n=Math.abs(i*t-r);n<a&&(a=n,s=e)}return s}throw W(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Dt=t=>{const e=t.split("."),i=Number(e[1]),r=e[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(e[3])?0:1)<<6)+0+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},Ut=/^pcm-([usf])(\d+)(be)?$/,Rt=t=>{if(S(_t.includes(t)),"ulaw"===t)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===t)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Ut.exec(t);let i;return S(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},Nt=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ft],zt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,jt=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Lt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Ht=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Gt=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof t)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("object"!=typeof t.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Nt.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 Mediabunny 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(void 0!==t.decoderConfig.displayAspectWidth&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectHeight&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectWidth!=(void 0!==t.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==t.decoderConfig.description&&!L(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(R);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(N);if(null!=e.transfer&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(z);if(null!=e.matrix&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)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(!zt.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(!jt.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("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!Lt.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!Ht.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Ft.some(e=>t.decoderConfig.codec.startsWith(e))&&!Ft.some(e=>t.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Ft.join(", ")}.`)},qt=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Wt=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!qt.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!L(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!_t.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${_t.join(", ")}).`)},Xt=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof t)throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof t.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof t.config.description)throw new TypeError("Subtitle metadata config description must be a string.")},Yt=[48e3,44100,32e3],Qt=[24e3,22050,16e3];!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(bt||(bt={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(yt||(yt={}));var Jt,Kt=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(-1===r||r>=t.length-2)break;e=r;let n=0;e+3<t.length&&0===t[e+1]&&0===t[e+2]&&1===t[e+3]?n=4:0===t[e+1]&&1===t[e+2]&&(n=3),0!==n?(-1!==i&&e>i&&(yield{offset:i,length:e-i}),i=e+n,e=i):e++}-1!==i&&i<t.length&&(yield{offset:i,length:t.length-i})},Zt=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=X(r,i,!1):(S(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},te=t=>31&t,ee=t=>{const e=[],i=t.length;for(let r=0;r<i;r++)r+2<i&&0===t[r]&&0===t[r+1]&&3===t[r+2]?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},ie=(new Uint8Array([0,0,0,1]),{1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}}),re=t=>{const e=F(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)F(t),F(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},ne=t=>t>>1&63,oe=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=/* @__PURE__ */new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},se=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&V(t);for(let e=0;e<i;e++)V(t)}else F(t)},ae=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=he(t,r,e,i)},he=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(F(t)+1):e-1,t.readBits(1),F(t);const o=r[s]??0;for(let e=0;e<=o;e++)t.readBits(1)||t.readBits(1);n=r[s]}else{const e=F(t),i=F(t);for(let r=0;r<e;r++)F(t),t.readBits(1);for(let r=0;r<i;r++)F(t),t.readBits(1);n=e+i}return n},ce=(t,e)=>{let i=2,r=2,n=2,o=0,s=0,a={num:1,den:1};if(t.readBits(1)){const e=t.readBits(8);if(255===e)a={num:t.readBits(16),den:t.readBits(16)};else{const t=ie[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(F(t),F(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(F(t),F(t),F(t),F(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&F(t),t.readBits(1)&&le(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=F(t),F(t),F(t),F(t),F(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},le=(t,e,i)=>{let r=!1,n=!1,o=!1;e&&(r=1===t.readBits(1),n=1===t.readBits(1),(r||n)&&(o=1===t.readBits(1),o&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),o&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let s=0;s<=i;s++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?F(t):i=1===t.readBits(1);let s=1;i||(s=F(t)+1),r&&de(t,s,o),n&&de(t,s,o)}},de=(t,e,i)=>{for(let r=0;r<e;r++)F(t),F(t),i&&(F(t),F(t)),t.readBits(1)};!function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"}(Jt||(Jt={}));var ue,fe=t=>{const e=D(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(ue||(ue={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var pe,me=[1,2,3,6],we=/* #__PURE__ */new Uint8Array(0),be=class t{constructor(t,e,i,r,n=-1,o,s){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=n,t===we&&void 0===o)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===o&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===we}get microsecondTimestamp(){return Math.trunc(tt*this.timestamp)}get microsecondDuration(){return Math.trunc(tt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new t(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!=typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}},ye=class{constructor(t){this.value=t}},ve=class{constructor(t){this.value=t}},ge=class{constructor(t){this.value=t}},xe=class{constructor(t){this.value=t}};!function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"}(pe||(pe={})),pe.EBML,pe.Segment,pe.SeekHead,pe.Info,pe.Cluster,pe.Tracks,pe.Cues,pe.Attachments,pe.Chapters,pe.Tags;var Ee=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,ke=t=>t<256n?1:t<65536n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,Te=t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-1048576&&t<1<<20?3:t>=-134217728&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,Me=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap,this.dataOffsets=/* @__PURE__ */new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Ee(t)){let i=0;switch(e){case 6:this.helperView.setUint8(i++,t/2**40|0);case 5:this.helperView.setUint8(i++,t/2**32|0);case 4:this.helperView.setUint8(i++,t>>24);case 3:this.helperView.setUint8(i++,t>>16);case 2:this.helperView.setUint8(i++,t>>8);case 1:this.helperView.setUint8(i++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(t,e=ke(t)){let i=0;for(let r=e-1;r>=0;r--)this.helperView.setUint8(i++,Number(t>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=Te(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)})(t)){let i=0;switch(e){case 1:this.helperView.setUint8(i++,128|t);break;case 2:this.helperView.setUint8(i++,64|t>>8),this.helperView.setUint8(i++,t);break;case 3:this.helperView.setUint8(i++,32|t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 4:this.helperView.setUint8(i++,16|t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 5:this.helperView.setUint8(i++,8|t/2**32&7),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 6:this.helperView.setUint8(i++,4|t/2**40&3),this.helperView.setUint8(i++,t/2**32|0),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(t=>t.charCodeAt(0))))}writeEBML(t){if(null!==t)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(const e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){const e=this.writer.getPos(),i=-1===t.size?1:t.size??4;-1===t.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(t,r),this.writeEBML(t.data),-1!==t.size){const t=this.writer.getPos()-r,n=this.writer.getPos();this.writer.seek(e),this.writeVarInt(t,i),this.writer.seek(n)}}else if("number"==typeof t.data){const e=t.size??Ee(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??ke(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if("string"==typeof t.data)this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof ye)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof ve)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof ge){const e=t.size??Te(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof xe){const e=U.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else W(t.data)}},_e={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"},Ce=t=>{const e=t.filePos,i=new xt(di(t,9));if(4095!==i.readBits(12))return null;if(i.skipBits(1),0!==i.readBits(2))return null;const r=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const s=i.readBits(3);if(0===s)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const a=i.readBits(13);i.skipBits(11);const h=i.readBits(2)+1;if(1!==h)throw new Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===r?t.filePos-=2:c=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:a,numberOfAacFrames:h,crcCheck:c,startPos:e}},Ae=/* @__PURE__ */e((t,e)=>{e.exports={}}),Se=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});Symbol.dispose??=Symbol("Symbol.dispose");var Be=-1/0,Pe=-1/0,Ie=null;"undefined"!=typeof FinalizationRegistry&&(Ie=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-Be>=1e3&&(wt.st("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Be=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Pe>=1e3&&(wt.st("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Pe=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var $e=class{constructor(){this.lt=0,this.dt=null}},Fe=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ve=new Set(Fe),Oe=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(tt*this.timestamp)}get microsecondDuration(){return Math.trunc(tt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.ut=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!Ve.has(i.format))throw new TypeError("init.format must be one of: "+Fe.join(", "));if(!Number.isInteger(i.codedWidth)||i.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(i.codedHeight)||i.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.layout){if(!Array.isArray(i.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const t of i.layout){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==i.visibleRect&&ut(i.visibleRect,"init.visibleRect"),void 0!==i.displayWidth&&(!Number.isInteger(i.displayWidth)||i.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==i.displayHeight&&(!Number.isInteger(i.displayHeight)||i.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==i.displayWidth!=(void 0!==i.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=i.format,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0;const t=i.layout??qe(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.ft=i.wt?O(e):O(e).slice(),this.bt=t,this.colorSpace=new ze(r)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==i?.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i?.timestamp&&!Number.isFinite(i?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==i?.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==i?.visibleRect&&ut(i.visibleRect,"init.visibleRect"),this.ft=e,this.bt=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6,this.colorSpace=new ze(e.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*tt),duration:Math.trunc((i.duration??0)*tt)||void 0}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=new OffscreenCanvas(r,n),s=o.getContext("2d",{alpha:rt(),willReadFrequently:!0});if(!s)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");s.drawImage(e,0,0),this.ft=o,this.bt=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:r,height:n},this.squarePixelWidth=r,this.squarePixelHeight=n,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new ze({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof $e))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.ft=e,e.lt++,this.format=e.getFormat(),null!==this.format&&!Fe.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=i?.encodeOptions??{},this.pixelAspectRatio=dt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ie?.register(this,{type:"video",data:this.ft},this)}clone(){if(this.ut)throw new Error("VideoSample is closed.");return S(null!==this.ft),this.ft instanceof $e?new t(this.ft,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):je(this.ft)?new t(this.ft.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.ft instanceof Uint8Array?(S(this.bt),new t(this.ft,{format:this.format,layout:this.bt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,wt:!0})):new t(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.ut||(Ie?.unregister(this),this.ft instanceof $e?(this.ft.lt--,0===this.ft.lt&&this.ft.close()):je(this.ft)?this.ft.close():this.ft=null,this.ut=!0)}allocationSize(t={}){if(Ge(t),this.ut)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot get allocation size when format is null.");return je(this.ft)?this.ft.allocationSize(t):Xe(this,t).allocationSize}async copyTo(e,i={}){if(!L(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ge(i),this.ut)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(S(null!==this.ft),je(this.ft))return this.ft.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format)){if(!(this.ft instanceof $e)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const t=this.toVideoFrame(),r=await t.copyTo(e,i);return t.close(),r}{const r={stack:[],error:void 0,hasError:!1};try{const n=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e}(r,await this.ft.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},i.colorSpace??"srgb"),!1);if(!(n instanceof t))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return await n.copyTo(e,i)}catch(c){r.error=c,r.hasError=!0}finally{Se(r)}}}const r=Xe(this,i);S(this.format);const n=O(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=We(this.format);let s;if(this.ft instanceof $e){let t=this.ft.getDataPlanes();if(t instanceof Promise&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.ft instanceof Uint8Array)S(this.bt),S(this.bt.length===o.length),s=this.bt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.ft.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.ft.getContext("2d");S(t),s=[{data:O(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.ut)throw new Error("VideoSample is closed.");if(S(null!==this.ft),this.ft instanceof $e){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this.ft.getDataPlanes();if(t instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const e=t.reduce((t,e)=>t+e.data.byteLength,0),i=new Uint8Array(e);let r=0;const n=[];for(const o of t)i.set(o.data,r),n.push(r),r+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((t,e)=>({offset:n[e],stride:t.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return je(this.ft)?new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.ft instanceof Uint8Array?(S(this.bt),new VideoFrame(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.bt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.ut)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.yt(c,l,d,u,this.rotation));const b=this.toCanvasImageSource();t.save();const y=f+m/2,v=p+w/2;t.translate(y,v),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(b,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&He(e.crop,"options.");const i=t.canvas.width,r=t.canvas.height,n=e.rotation??this.rotation,[o,s]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a,h,c,l,d=e.crop;d&&(d=Le(d,o,s));const{sx:u,sy:f,sWidth:p,sHeight:m}=this.yt(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??s,n);if("fill"===e.fit)a=0,h=0,c=i,l=r;else{const[t,n]=e.crop?[e.crop.width,e.crop.height]:[o,s],d="contain"===e.fit?Math.min(i/t,r/n):Math.max(i/t,r/n);c=t*d,l=n*d,a=(i-c)/2,h=(r-l)/2}t.save();const w=n%180==0?1:c/l;t.translate(i/2,r/2),t.rotate(n*Math.PI/180),t.scale(1/w,w),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),u,f,p,m,a,h,c,l),t.restore()}yt(t,e,i,r,n){return 90===n?[t,e,i,r]=[e,this.squarePixelHeight-t-i,r,i]:180===n?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-r]:270===n&&([t,e,i,r]=[this.squarePixelWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this.ut)throw new Error("VideoSample is closed.");if(S(null!==this.ft),this.ft instanceof $e||this.ft instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this.ft}async transform(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&He(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const i=P(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=Le(o,r,n));const s=o?o.width:r,a=o?o.height:n,h=s/a;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/h):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*h):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=a),c=Q(c,e.roundDimensionsTo??1),l=Q(l,e.roundDimensionsTo??1);const d={width:c,height:l,fit:e.fit??"fill",rotation:i,crop:o??{left:0,top:0,width:r,height:n},alpha:e.alpha??"keep"};for(const t of De){let e=t(this,d);if(e instanceof Promise&&(e=await e),null!==e)return e}let u=null,f=!1;for(const t of Re)if(t.canvas.width===d.width&&t.canvas.height===d.height){u=t.canvas,t.age=Ne++;break}if(null===u){if("undefined"!=typeof OffscreenCanvas)u=new OffscreenCanvas(d.width,d.height);else{if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");u=document.createElement("canvas"),u.width=d.width,u.height=d.height}f=!0,Re.length>=Ue&&Re.splice(((t,e)=>{let i=-1,r=1/0;for(let n=0;n<t.length;n++){const o=e(t[n]);o<r&&(r=o,i=n)}return i})(Re,t=>t.age),1),Re.push({canvas:u,age:Ne++})}const p=u.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return p.imageSmoothingQuality="high","discard"===d.alpha?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):f||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new t(u,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||"object"!=typeof t)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},De=[],Ue=3,Re=[],Ne=0,ze=class{constructor(t){if(void 0!==t){if(!t||"object"!=typeof t)throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(R);if(null!=t.primaries&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(N);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(z);if(null!=t.matrix&&!r.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},je=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,Le=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),o=Math.min(t.width,e-r),s=Math.min(t.height,i-n);return S(o>=0),S(s>=0),{left:r,top:n,width:o,height:s}},He=(t,e)=>{if(!t||"object"!=typeof t)throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ge=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.colorSpace&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==t.format&&"string"!=typeof t.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!=typeof e)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.rect){if(!t.rect||"object"!=typeof t.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==t.rect.x&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==t.rect.y&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==t.rect.width&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==t.rect.height&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},qe=(t,e,i)=>{const r=We(t),n=[];let o=0;for(const s of r){const t=Math.ceil(e/s.widthDivisor),r=Math.ceil(i/s.heightDivisor),a=t*s.sampleBytes,h=a*r;n.push({offset:o,stride:a}),o+=h}return n},We=t=>{const e=(t,e,i,r,n)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return n&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:W(t),S(!1)}},Xe=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Ye(i,r,t.codedWidth,t.codedHeight,t.format),o=e.layout;let s;if(e.format&&e.format!==t.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(e.format))throw new Error("NotSupportedError: Invalid destination format.");s=e.format}else s=t.format;return Je(n,s,o)},Ye=(t,e,i,r,n)=>{const o={...t};if(void 0!==e){if(0===e.width||0===e.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");o.x=e.x||0,o.y=e.y||0,o.width=e.width||0,o.height=e.height||0}if(!Qe(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Qe=(t,e)=>{if(null===t)return!0;const i=We(t);for(let r=0;r<i.length;r++){const t=i[r],n=t.widthDivisor,o=t.heightDivisor;if((e.x||0)%n!==0)return!1;if((e.y||0)%o!==0)return!1}return!0},Je=(t,e,i)=>{const r=We(e),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let o=0;const s=[],a=[];for(let h=0;h<n;h++){const e=r[h],n=e.sampleBytes,c=e.widthDivisor,l=e.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(t.y||0)/l),d.sourceHeight=Math.ceil(Math.trunc(t.height||0)/l),d.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/c)*n,d.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/c)*n,void 0!==i){const t=i[h];if(t.stride<d.sourceWidthBytes)throw new TypeError(`Stride for plane ${h} is too small.`);d.destinationOffset=t.offset,d.destinationStride=t.stride}else d.destinationOffset=o,d.destinationStride=d.sourceWidthBytes;const u=d.destinationStride*d.sourceHeight+d.destinationOffset;if(u>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(u),o=Math.max(o,u);for(let t=0;t<h;t++){const e=s[t];if(!(a[h]<=e.destinationOffset||a[t]<=d.destinationOffset))throw new TypeError("Planes overlap.")}s.push(d)}return{allocationSize:o,computedLayouts:s}},Ke=/* @__PURE__ */new Map,Ze=(t,e)=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding options must be an object.");if(void 0!==e.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const i=e.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==e.latencyMode&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==e.fullCodecString&&"string"!=typeof e.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==e.fullCodecString&&((r=e.fullCodecString).startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":"vp8"===r?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":Ft.includes(r)?"prores":"mp3"===r||"mp4a.69"===r||"mp4a.6B"===r||"mp4a.6b"===r||"mp4a.40.34"===r?"mp3":r.startsWith("mp4a.40.")||"mp4a.67"===r?"aac":"opus"===r?"opus":"vorbis"===r?"vorbis":"flac"===r?"flac":"ac-3"===r||"ac3"===r?"ac3":"ec-3"===r||"eac3"===r?"eac3":"ulaw"===r?"ulaw":"alaw"===r?"alaw":Ut.test(r)?r:"webvtt"===r?"webvtt":null)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);var r;if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==e.contentHint&&"string"!=typeof e.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},ti=t=>{const e=t.bitrateMode,i=t.quality.vt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Ot(t.codec,t.width,t.height,r,"keep"===t.alpha),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:i,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(n=t.codec,"avc"===n?{avc:{format:"avc"}}:"hevc"===n?{hevc:{format:"hevc"}}:{})};var n},n=[];return null!==i.quantizer&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),S(n.length>0),n},ei=class{constructor(t){if("number"!=typeof t&&"string"!=typeof t||(t={quality:t}),!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if("string"==typeof t.quality?!(t.quality in ii):"number"!=typeof t.quality||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(void 0!==t.preferBitrate&&"boolean"!=typeof t.preferBitrate)throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this.gt="string"==typeof t.quality?ii[t.quality]:t.quality,this.xt=t.preferBitrate??!1,this.Et=void 0,this.kt=void 0}else{if(void 0!==t.bitrate&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==t.quantizer&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===t.bitrate&&void 0===t.quantizer)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this.gt=void 0,this.xt=!1,this.Et=t.bitrate,this.kt=t.quantizer}this.Tt=t.bitrateMode}vt(t,e,i,r){const n=ri[t];let o=null,s=this.Tt??r??"variable";if(void 0!==this.kt){if(n)if(this.kt<n.min||this.kt>n.max){if(void 0===this.Et)throw new Error(`Quantizer ${this.kt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.kt,void 0===this.Et&&(s="quantizer");else if(void 0===this.Et)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this.Et&&n&&!this.xt&&(S(void 0!==this.gt),o=Y(Math.round((a=n.worst)+(n.best-a)*this.gt),n.min,n.max));var a;let h;if(void 0!==this.Et)h=this.Et;else{let r=this.gt;void 0===r&&(S(null!==o&&n),r=Y((o-n.worst)/(n.best-n.worst),0,1)),h=oi(t,e,i,ni(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Mt(t,e,i){return void 0!==this.Et?this.Et:(S(void 0!==this.gt),oi(t,e,i,ni(this.gt)))}_t(t){if(_t.includes(t)||"flac"===t)return;if(void 0!==this.Et)return this.Et;if(void 0===this.gt)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const e=ni(this.gt),i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[t];if(!i)throw new Error(`Unhandled codec: ${t}`);let r=i*e;return"aac"===t?r=[96e3,128e3,16e4,192e3].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t):"opus"===t||"vorbis"===t?r=Math.max(6e3,r):"mp3"===t&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t)),1e3*Math.round(r/1e3)}},ii={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},ri={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},ni=t=>.3*Math.exp(2.5538*t),oi=(t,e,i,r)=>{const n=e*i,o=3e6*Math.pow(n/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333}[t]*r;return 1e3*Math.ceil(o/1e3)},si=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void S(!1),ai=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!Mt.includes(t))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(void 0!==n&&!(n instanceof ei))throw new TypeError("quality, when provided, must be a Quality.");if(void 0!==n&&void 0!==o)throw new TypeError("quality and bitrate cannot both be provided.");if(void 0!==o&&!(o instanceof ei)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Ze(t,s);const a=hi(n,o)??new ei({bitrate:1e6});let h;try{h=ti({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=Ke.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(ci.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of h)if((await VideoEncoder.isConfigSupported(e)).supported){if(!rt())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?si(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Ke.set(c,d),d},hi=(t,e)=>void 0!==t?t:void 0!==e?e instanceof ei?e:new ei({bitrate:e}):void 0,ci=[],li=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,D(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},di=(t,e)=>{((t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)})(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},ui=class{constructor(t){this.mutex=new H,this.trackTimestampInfo=/* @__PURE__ */new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},fi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,pi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,mi=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")},wi=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);S(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}},bi=/* #__PURE__ */new Uint8Array(8),yi=/* #__PURE__ */new DataView(bi.buffer),vi=t=>[(t%256+256)%256],gi=t=>(yi.setUint16(0,t,!1),[bi[0],bi[1]]),xi=t=>(yi.setInt16(0,t,!1),[bi[0],bi[1]]),Ei=t=>(yi.setUint32(0,t,!1),[bi[1],bi[2],bi[3]]),ki=t=>(yi.setUint32(0,t,!1),[bi[0],bi[1],bi[2],bi[3]]),Ti=t=>(yi.setInt32(0,t,!1),[bi[0],bi[1],bi[2],bi[3]]),Mi=t=>(yi.setUint32(0,Math.floor(t/2**32),!1),yi.setUint32(4,t,!1),[bi[0],bi[1],bi[2],bi[3],bi[4],bi[5],bi[6],bi[7]]),_i=t=>(yi.setInt32(0,Math.floor(t/2**32),!1),yi.setUint32(4,t,!1),[bi[0],bi[1],bi[2],bi[3],bi[4],bi[5],bi[6],bi[7]]),Ci=t=>(yi.setInt16(0,256*t,!1),[bi[0],bi[1]]),Ai=t=>(yi.setInt32(0,65536*t,!1),[bi[0],bi[1],bi[2],bi[3]]),Si=t=>(yi.setInt32(0,2**30*t,!1),[bi[0],bi[1],bi[2],bi[3]]),Bi=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},Pi=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Ii=t=>{const e=t*(Math.PI/180),i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},$i=/* #__PURE__ */Ii(0),Fi=t=>[Ai(t[0]),Ai(t[1]),Si(t[2]),Ai(t[3]),Ai(t[4]),Si(t[5]),Ai(t[6]),Ai(t[7]),Si(t[8])],Vi=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),Oi=(t,e,i,r,n)=>Vi(t,[vi(e),Ei(i),r??[]],n),Di=()=>Vi("styp",[Pi("iso5"),ki(0),Pi("iso5"),Pi("iso6"),Pi("mp41"),Pi("cmfc"),Pi("dash")]),Ui=(t,e)=>{let i=t.maxWrittenEndTimestamp-t.minWrittenTimestamp;return Number.isFinite(i)||(i=0),Oi("sidx",1,0,[ki(1),ki(cn),Mi(dn(t.minWrittenTimestamp,cn)),Mi(0),gi(0),gi(1),ki(2147483647&e),ki(dn(i,cn)),ki(0)])},Ri=t=>({type:"mdat",largeSize:t}),Ni=t=>Vi("moov",void 0,[zi(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Li(e,t.creationTime)),t.isFragmented?_r(t.trackDatas):null,Rr(t)]),zi=(t,e)=>{const i=Math.max(0,...e.map(t=>dn(ji(t),cn)+dn(t.startTimestampOffset??0,cn))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!$(t)||!$(i),o=n?Mi:ki;return Oi("mvhd",+n,0,[o(t),o(t),ki(cn),o(i),Ai(1),Ci(1),Array(10).fill(0),Fi($i),Array(24).fill(0),ki(r)])},ji=t=>{if(0===t.samples.length)return 0;let e=1/0,i=-1/0;for(let r=0;r<t.samples.length;r++){const n=t.samples[r];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>i&&(i=n.timestamp+n.duration)}return e===1/0?0:i-e},Li=(t,e)=>{const i=ln(t),r=null!==t.startTimestampOffset&&t.startTimestampOffset>0;return Vi("trak",void 0,[Hi(t,e),r?Gi(t,t.startTimestampOffset):null,qi(t,e),void 0!==i.name?Vi("udta",void 0,[Vi("name",[...U.encode(i.name)])]):null])},Hi=(t,e)=>{const i=dn(ji(t),cn)+dn(t.startTimestampOffset??0,cn),r=!$(e)||!$(i),n=r?Mi:ki;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=Ii(e??0)}else o=$i;let s=2;!1!==t.track.metadata.disposition?.default&&(s|=1);const a="video"===t.type?0:"audio"===t.type?1:"subtitle"===t.type?2:W(t);return Oi("tkhd",+r,s,[n(e),n(e),ki(t.track.id),ki(0),n(i),Array(8).fill(0),gi(0),gi(a),Ci("audio"===t.type?1:0),gi(0),Fi(o),Ai("video"===t.type?t.info.width:0),Ai("video"===t.type?t.info.height:0)])},Gi=(t,e)=>{const i=dn(e,cn),r=dn(ji(t),cn),n=!$(i)||!$(r),o=n?Mi:ki,s=n?_i:Ti;return Vi("edts",void 0,[Oi("elst",n?1:0,0,[ki(2),o(i),s(-1),Ai(1),o(r),s(0),Ai(1)])])},qi=(t,e)=>Vi("mdia",void 0,[Wi(t,e),Qi(!0,Xi[t.type],Yi[t.type]),Ji(t)]),Wi=(t,e)=>{const i=dn(ji(t),t.timescale),r=!$(e)||!$(i),n=r?Mi:ki;return Oi("mdhd",+r,0,[n(e),n(e),ki(t.timescale),n(i),gi(Zr(t.track.metadata.languageCode??"und")),gi(0)])},Xi={video:"vide",audio:"soun",subtitle:"text"},Yi={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Qi=(t,e,i,r="\0\0\0\0")=>Oi("hdlr",0,0,[t?Pi("mhlr"):ki(0),Pi(e),Pi(r),ki(0),ki(0),Pi(i,!0)]),Ji=t=>Vi("minf",void 0,[Ki[t.type](),Zi(),ir(t)]),Ki={video:()=>Oi("vmhd",0,1,[gi(0),gi(0),gi(0),gi(0)]),audio:()=>Oi("smhd",0,0,[gi(0),gi(0)]),subtitle:()=>Oi("nmhd",0,0)},Zi=()=>Vi("dinf",void 0,[tr()]),tr=()=>Oi("dref",0,0,[ki(1)],[er()]),er=()=>Oi("url ",0,1),ir=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return Vi("stbl",void 0,[rr(t),vr(t),e?Tr(t):null,e?Mr(t):null,xr(t),Er(t),kr(t),gr(t)])},rr=t=>{let e;if("video"===t.type)e=nr(Wr(t.track.source.Ct,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Yr(t.track.source.Ct,t.muxer.isQuickTime);S(i),e=hr(i,t)}else"subtitle"===t.type&&(e=yr(Jr[t.track.source.Ct],t));return S(e),Oi("stsd",0,0,[ki(1)],[e])},nr=(t,e)=>Vi(t,[Array(6).fill(0),gi(1),gi(0),gi(0),Array(12).fill(0),gi(e.info.width),gi(e.info.height),ki(4718592),ki(4718592),ki(0),gi(1),vi(10),Pi("Mediabunny"),Array(21).fill(0),gi(e.info.hasAlphaChannel?32:24),xi(65535)],[Xr[e.track.source.Ct]?.(e)??null,or(e),j(e.info.decoderConfig.colorSpace)?sr(e):null]),or=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:Vi("pasp",[ki(t.info.pixelAspectRatio.num),ki(t.info.pixelAspectRatio.den)]),sr=t=>Vi("colr",[Pi(t.muxer.isQuickTime?"nclc":"nclx"),gi(R[t.info.decoderConfig.colorSpace.primaries]),gi(N[t.info.decoderConfig.colorSpace.transfer]),gi(z[t.info.decoderConfig.colorSpace.matrix]),t.muxer.isQuickTime?[]:vi((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),ar=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),s=i[5]?Number(i[5]):e.colorSpace?.primaries?R[e.colorSpace.primaries]:2,a=i[6]?Number(i[6]):e.colorSpace?.transfer?N[e.colorSpace.transfer]:2,h=i[7]?Number(i[7]):e.colorSpace?.matrix?z[e.colorSpace.matrix]:2;return Oi("vpcC",1,0,[vi(r),vi(n),vi(o),vi(s),vi(a),vi(h),gi(0)])},hr=(t,e)=>{let i,r=0,n=16;const o=_t.includes(e.track.source.Ct);if(o){const t=e.track.source.Ct,{sampleSize:i}=Rt(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),gi(1),gi(r),gi(0),ki(0),gi(e.info.numberOfChannels),gi(n),gi(0),gi(0),gi(e.info.sampleRate<65536?e.info.sampleRate:0),gi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),gi(1),gi(r),gi(0),ki(0),gi(e.info.numberOfChannels),gi(Math.min(n,16)),xi(t),gi(0),gi(e.info.sampleRate<65536?e.info.sampleRate:0),gi(0),o?[ki(1),ki(n/8),ki(e.info.numberOfChannels*n/8)]:[ki(0),ki(0),ki(0)],ki(2)]}return Vi(t,i,[Qr(e.track.source.Ct,e.muxer.isQuickTime)?.(e)??null])},cr=t=>{let e;switch(t.track.source.Ct){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source.Ct}`)}let i=[...vi(e),...vi(21),...Ei(0),...ki(0),...ki(0)];if(t.info.decoderConfig.description){const e=O(t.info.decoderConfig.description);i=[...i,...vi(5),...Bi(e.byteLength),...e]}return i=[...gi(1),...vi(0),...vi(4),...Bi(i.length),...i,...vi(6),...vi(1),...vi(2)],i=[...vi(3),...Bi(i.length),...i],Oi("esds",0,0,i)},lr=t=>Vi("wave",void 0,[dr(t),ur(t),Vi("\0\0\0\0")]),dr=t=>Vi("frma",[Pi(Yr(t.track.source.Ct,t.muxer.isQuickTime))]),ur=t=>{const{littleEndian:e}=Rt(t.track.source.Ct);return Vi("enda",[gi(+e)])},fr=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=/* @__PURE__ */new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){S(a.byteLength>=18);const t=fe(O(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return Vi("dOps",[vi(0),vi(e),gi(i),ki(r),xi(n),vi(o),...s])},pr=t=>{const e=t.info.decoderConfig?.description;S(e);const i=O(e);return Oi("dfLa",0,0,[...i.subarray(4)])},mr=t=>{const{littleEndian:e,sampleSize:i}=Rt(t.track.source.Ct);return Oi("pcmC",0,0,[vi(+e),vi(8*i)])},wr=t=>{const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new xt(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=/* @__PURE__ */new Uint8Array(3),r=new xt(i);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),Vi("dac3",[...i])},br=t=>{const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new xt(t);e.skipBits(16);const i=e.readBits(2);if(e.skipBits(3),0!==i&&2!==i)return null;const r=e.readBits(11),n=e.readBits(2);let o,s=0;3===n?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),h=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const l=me[o];let d;return d=n<3?Yt[n]/1e3:Qt[s]/1e3,{dataRate:Math.round((r+1)*d/(16*l)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:h,numDepSub:0,chanLoc:0}]}})(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let i=16;for(const s of e.substreams)i+=23,s.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),n=new Uint8Array(r),o=new xt(n);o.writeBits(13,e.dataRate),o.writeBits(3,e.substreams.length-1);for(const s of e.substreams)o.writeBits(2,s.fscod),o.writeBits(5,s.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,s.bsmod),o.writeBits(3,s.acmod),o.writeBits(1,s.lfeon),o.writeBits(3,0),o.writeBits(4,s.numDepSub),s.numDepSub>0?o.writeBits(9,s.chanLoc):o.writeBits(1,0);return Vi("dec3",[...n])},yr=(t,e)=>Vi(t,[Array(6).fill(0),gi(1)],[Kr[e.track.source.Ct](e)]),vr=t=>Oi("stts",0,0,[ki(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[ki(t.sampleCount),ki(t.sampleDelta)])]),gr=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return Oi("stss",0,0,[ki(e.length),e.map(([t])=>ki(t+1))])},xr=t=>Oi("stsc",0,0,[ki(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[ki(t.firstChunk),ki(t.samplesPerChunk),ki(1)])]),Er=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=Rt(t.track.source.Ct);return Oi("stsz",0,0,[ki(e*t.info.numberOfChannels),ki(t.samples.reduce((e,i)=>e+dn(i.duration,t.timescale),0))])}return Oi("stsz",0,0,[ki(0),ki(t.samples.length),t.samples.map(t=>ki(t.size))])},kr=t=>t.finalizedChunks.length>0&&I(t.finalizedChunks).offset>=2**32?Oi("co64",0,0,[ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>Mi(t.offset))]):Oi("stco",0,0,[ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>ki(t.offset))]),Tr=t=>Oi("ctts",1,0,[ki(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[ki(t.sampleCount),Ti(t.sampleCompositionTimeOffset)])]),Mr=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;S(t.compositionTimeOffsetTable.length>0),S(t.samples.length>0);for(let s=0;s<t.compositionTimeOffsetTable.length;s++){const r=t.compositionTimeOffsetTable[s];e=Math.min(e,r.sampleCompositionTimeOffset),i=Math.max(i,r.sampleCompositionTimeOffset)}for(let s=0;s<t.samples.length;s++){const e=t.samples[s];r=Math.min(r,dn(e.timestamp,t.timescale)),n=Math.max(n,dn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:Oi("cslg",0,0,[Ti(o),Ti(e),Ti(i),Ti(r),Ti(n)])},_r=t=>Vi("mvex",void 0,t.map(Cr)),Cr=t=>Oi("trex",0,0,[ki(t.track.id),ki(1),ki(0),ki(0),ki(0)]),Ar=(t,e)=>Vi("moof",void 0,[Sr(t),...e.map(Pr)]),Sr=t=>Oi("mfhd",0,0,[ki(t)]),Br=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},Pr=t=>Vi("traf",void 0,[Ir(t),$r(t),Fr(t)]),Ir=t=>{S(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Br(i)};return Oi("tfhd",0,131128,[ki(t.track.id),ki(r.duration),ki(r.size),ki(r.flags)])},$r=t=>(S(t.currentChunk),Oi("tfdt",1,0,[Mi(dn(t.currentChunk.startTimestamp,t.timescale))])),Fr=t=>{S(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(Br),n=t.currentChunk.samples.map(e=>dn(e.timestamp-e.decodeTimestamp,t.timescale)),o=new Set(e),s=new Set(i),a=new Set(r),h=new Set(n),c=2===a.size&&r[0]!==r[1],l=o.size>1,d=s.size>1,u=!c&&a.size>1,f=h.size>1||[...h].some(t=>0!==t);let p=0;return p|=1,p|=4*+c,p|=256*+l,p|=512*+d,p|=1024*+u,p|=2048*+f,Oi("trun",1,p,[ki(t.currentChunk.samples.length),ki(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?ki(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?ki(e[o]):[],d?ki(i[o]):[],u?ki(r[o]):[],f?Ti(n[o]):[]])])},Vr=(t,e)=>Oi("tfra",1,0,[ki(t.track.id),ki(63),ki(t.finalizedChunks.length),t.finalizedChunks.map(i=>[Mi(dn(i.samples[0].timestamp,t.timescale)),Mi(i.moofOffset),ki(e+1),ki(1),ki(1)])]),Or=()=>Vi("vtte"),Dr=(t,e,i,r,n)=>Vi("vttc",void 0,[null!==n?Vi("vsid",[Ti(n)]):null,null!==i?Vi("iden",[...U.encode(i)]):null,null!==e?Vi("ctim",[...U.encode(mi(e))]):null,null!==r?Vi("sttg",[...U.encode(r)]):null,Vi("payl",[...U.encode(t)])]),Ur=t=>Vi("vtta",[...U.encode(t)]),Rr=t=>{const e=[],i=t.format.At.metadataFormat??"auto",r=t.output.St;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=Hr(r);t&&e.push(t)}else if("mdta"===i){const t=Gr(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&Nr(e,t.output.St);return 0===e.length?null:Vi("udta",void 0,e)},Nr=(t,e)=>{for(const{key:i,value:r}of ht(e))switch(i){case"title":t.push(zr("©nam",r));break;case"description":t.push(zr("©des",r));break;case"artist":t.push(zr("©ART",r));break;case"album":t.push(zr("©alb",r));break;case"albumArtist":t.push(zr("albr",r));break;case"genre":t.push(zr("©gen",r));break;case"date":t.push(zr("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(zr("©cmt",r));break;case"lyrics":t.push(zr("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:W(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(zr(i,r)):r instanceof Uint8Array&&t.push(Vi(i,Array.from(r))))}},zr=(t,e)=>{const i=U.encode(e);return Vi(t,[gi(i.length),gi(Zr("und")),Array.from(i)])},jr={"image/jpeg":13,"image/png":14,"image/bmp":27},Lr=(t,e)=>{const i=[];for(const{key:r,value:n}of ht(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:qr(n)});break;case"description":i.push({key:e?"description":"©des",value:qr(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:qr(n)});break;case"album":i.push({key:e?"album":"©alb",value:qr(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:qr(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:qr(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:qr(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:qr(n)});break;case"date":i.push({key:e?"date":"©day",value:qr(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:Vi("data",[ki(jr[t.mimeType]??0),ki(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:qr(e)})}else i.push({key:"trkn",value:Vi("data",[ki(0),ki(0),gi(0),gi(n),gi(t.tracksTotal??0),gi(0)])});break;case"discNumber":e||i.push({key:"disc",value:Vi("data",[ki(0),ki(0),gi(0),gi(n),gi(t.discsTotal??0),gi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:W(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];null==n||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof n?i.push({key:r,value:qr(n)}):n instanceof Uint8Array?i.push({key:r,value:Vi("data",[ki(0),ki(0),Array.from(n)])}):n instanceof vt&&i.push({key:r,value:Vi("data",[ki(jr[n.mimeType]??0),ki(0),Array.from(n.data)])}))}return i},Hr=t=>{const e=Lr(t,!1);return 0===e.length?null:Oi("meta",0,0,void 0,[Qi(!1,"mdir","","appl"),Vi("ilst",void 0,e.map(t=>Vi(t.key,void 0,[t.value])))])},Gr=t=>{const e=Lr(t,!0);return 0===e.length?null:Vi("meta",void 0,[Qi(!1,"mdta",""),Oi("keys",0,0,[ki(e.length)],e.map(t=>Vi("mdta",[...U.encode(t.key)]))),Vi("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...ki(e+1));return Vi(i,void 0,[t.value])}))])},qr=t=>Vi("data",[ki(1),ki(0),...U.encode(t)]),Wr=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Xr={avc:t=>t.info.decoderConfig&&Vi("avcC",[...O(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&Vi("hvcC",[...O(t.info.decoderConfig.description)]),vp8:ar,vp9:ar,av1:t=>Vi("av1C",Dt(t.info.decoderConfig.codec)),prores:null},Yr=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Qr=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return cr;case"opus":return fr;case"flac":return pr;case"ac3":return wr;case"eac3":return br}if(e)switch(t){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return lr}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return mr}return null},Jr={webvtt:"wvtt"},Kr={webvtt:t=>Vi("vttC",[...U.encode(t.info.config.description)])},Zr=t=>{S(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},tn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Bt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.Pt(e),t.Bt=!0}start(){S(!this.started),this.target.It(),this.started=!0}write(t){S(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.$t(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return S(this.started&&!this.finalized),this.target.Ft()}async finalize(){S(this.started&&!this.finalized),await this.target.Vt(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},en=(Ae(),class extends pt{constructor(){super(...arguments),this.Bt=!1,this.Ot=null,this.onwrite=null}Pt(t){!1!==this.Ot&&(this.Ot=t)}Dt(t,e){this.onwrite?.(t,e),this.it("write",{start:t,end:e})}slice(t){if(!Number.isInteger(t)||t<0)throw new TypeError("offset must be a non-negative integer.");return new an(this,t)}}),rn=65536,nn=2**32,on=class extends en{constructor(t={}){if(super(),this.buffer=null,this.Ut=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.At=t,this.Rt="resize"in/* @__PURE__ */new ArrayBuffer(0),this.Rt)try{this.Nt=new ArrayBuffer(rn,{maxByteLength:nn})}catch{this.Nt=new ArrayBuffer(rn),this.Rt=!1}else this.Nt=new ArrayBuffer(rn);this.zt=new Uint8Array(this.Nt)}jt(t){let e=this.Nt.byteLength;for(;e<t;)e*=2;if(e!==this.Nt.byteLength){if(e>nn)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.Rt)this.Nt.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.zt,0),this.Nt=t,this.zt=i}}}It(){}$t(t,e){this.jt(e+t.byteLength),this.zt.set(t,e),this.Ut=Math.max(this.Ut,e+t.byteLength),this.Dt(e,e+t.byteLength)}async Ft(){}async Vt(){this.buffer=this.Nt.slice(0,this.Ut),this.At.onFinalize&&await this.At.onFinalize(this.buffer),this.it("finalized")}async Lt(){}Ht(t,e){return this.zt.slice(t,e)}},sn=class extends en{constructor(t,e={}){if(super(),this.Gt=[],this.qt=0,this.Wt=0,this.Xt=null,this.Yt=null,this.Qt=[],!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this.Jt=t,this.At=e,this.Kt=e.chunked??!1,this.Zt=e.chunkSize??16777216}It(){this.Xt=this.Jt.getWriter()}$t(t,e){if(e>this.qt){const t=e-this.qt;this.$t(new Uint8Array(t),this.qt)}this.Gt.push({data:t.slice(),start:e}),this.qt=Math.max(this.qt,e+t.byteLength),this.Dt(e,e+t.byteLength)}async Ft(){if(null!==this.Yt)throw this.Yt;if(S(this.Xt),0===this.Gt.length)return;const t=[],e=[...this.Gt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Gt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.Xt.desiredSize&&this.Xt.desiredSize<=0&&await this.Xt.ready,this.Kt)this.te(i.data,i.start),this.ee();else{if(!0===this.Ot&&i.start!==this.Wt)throw new Error("Internal error: Monotonicity violation.");this.Xt.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.Yt??=t}),this.Wt=i.start+i.data.byteLength}}this.Gt.length=0}te(t,e){let i=this.Qt.findIndex(t=>t.start<=e&&e<t.start+this.Zt);-1===i&&(i=this.ie(e));const r=this.Qt[i],n=e-r.start,o=t.subarray(0,Math.min(this.Zt-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.re(r,s),0===r.written[0].start&&r.written[0].end===this.Zt&&(r.shouldFlush=!0),this.Qt.length>2){for(let t=0;t<this.Qt.length-1;t++)this.Qt[t].shouldFlush=!0;this.ee()}o.byteLength<t.byteLength&&this.te(t.subarray(o.byteLength),e+o.byteLength)}re(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){const o=Math.floor(i+(r-i+1)/2);t.written[o].start<=e.start?(i=o+1,n=o):r=o-1}for(t.written.splice(n+1,0,e),(-1===n||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)}ie(t){const e={start:Math.floor(t/this.Zt)*this.Zt,data:new Uint8Array(this.Zt),written:[],shouldFlush:!1};return this.Qt.push(e),this.Qt.sort((t,e)=>t.start-e.start),this.Qt.indexOf(e)}ee(t=!1){S(this.Xt);for(let e=0;e<this.Qt.length;e++){const i=this.Qt[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Ot&&e!==this.Wt)throw new Error("Internal error: Monotonicity violation.");this.Xt.write({type:"write",data:i.data.subarray(t.start,t.end),position:e}).catch(t=>{this.Yt??=t}),this.Wt=i.start+t.end}this.Qt.splice(e--,1)}}}async Vt(){if(this.Kt&&this.ee(!0),null!==this.Yt)throw this.Yt;S(this.Xt),await this.Xt.ready,await this.Xt.close(),this.it("finalized")}async Lt(){return this.Xt?.close()}},an=class extends en{constructor(t,e){super(),this.ne=t,this.oe=e}It(){}$t(t,e){this.ne.$t(t,this.oe+e),this.Dt(e,e+t.byteLength)}Ft(){return this.ne.Ft()}async Vt(){this.it("finalized")}async Lt(){}Pt(t){super.Pt(t),this.ne.Pt(t)}},hn=class{constructor(t,e){if(this.rootPath=t,this.getTarget=e,"string"!=typeof t)throw new TypeError("rootPath must be a string.");if("function"!=typeof e)throw new TypeError("getTarget must be a function.")}},cn=57600,ln=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},dn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},un=class extends ui{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new on,this.auxWriter=new tn(this.auxTarget,!1),this.auxBoxWriter=new wi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=q(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=e,this.isQuickTime=e instanceof In,this.isCmaf=e instanceof Pn,this.minimumFragmentDuration=e.At.minimumFragmentDuration??(e instanceof Pn?1/0:1),this.auxWriter.start()}async start(){const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output.se(t=>void 0!==this.format.At.fastStart?"fragmented"===this.format.At.fastStart:t instanceof on),this.boxWriter=new wi(this.writer),this.fastStart=this.format.At.fastStart??(this.writer.target instanceof on&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output.ae())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const t=new tn(await this.output.he(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new wi(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.Ct);{const t=this.initBoxWriter??this.boxWriter;if(S(t),this.format.At.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return Vi("ftyp",t.isQuickTime?[Pi("qt "),ki(e),Pi("qt ")]:t.fragmented?t.cmaf?[Pi("iso5"),ki(e),Pi("iso5"),Pi("iso6"),Pi("mp41"),Pi("cmfc"),Pi("dash")]:[Pi("iso5"),ki(e),Pi("iso5"),Pi("iso6"),Pi("mp41")]:[Pi("isom"),ki(e),Pi("isom"),t.holdsAvc?Pi("avc1"):[],Pi("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format.At.onFtyp){const{data:e,start:i}=t.writer.stopTrackingWrites();this.format.At.onFtyp(e,i)}this.ftypSize=t.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output.tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(S(this.writer),S(this.boxWriter),this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ri(!0),this.boxWriter.writeBox(this.mdat));await(this.writer?.flush()),t()}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ct]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings)].join(", ")}"`),e})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Gt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};S(void 0!==n.codedWidth),S(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.Ct||n.description){if("hevc"===t.source.Ct&&!n.description){const t=(t=>{try{const e=[],i=[],r=[],n=[];for(const h of Kt(t)){const o=t.subarray(h.offset,h.offset+h.length),s=ne(o[0]);s===yt.VPS_NUT?e.push(o):s===yt.SPS_NUT?i.push(o):s===yt.PPS_NUT?r.push(o):s!==yt.PREFIX_SEI_NUT&&s!==yt.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new xt(ee(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:h,general_level_idc:c}=oe(e,i);F(e);const l=F(e);let d=0;3===l&&(d=e.readBits(1));const u=F(e),f=F(e);let p=u,m=f;if(e.readBits(1)){const t=F(e),i=F(e),r=F(e),n=F(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}const w=F(e),b=F(e);F(e);const y=e.readBits(1)?0:i;let v=0;for(let t=y;t<=i;t++)F(e),v=F(e),F(e);F(e),F(e),F(e),F(e),F(e),F(e),e.readBits(1)&&e.readBits(1)&&se(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),F(e),F(e),e.skipBits(1));const g=F(e);if(ae(e,g),e.readBits(1)){const t=F(e);for(let i=0;i<t;i++)F(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,k=2,T=0,M=0,_={num:1,den:1};if(e.readBits(1)){const t=ce(e,i);_=t.pixelAspectRatio,x=t.colourPrimaries,E=t.transferCharacteristics,k=t.matrixCoefficients,T=t.fullRangeFlag,M=t.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:_,colourPrimaries:x,transferCharacteristics:E,matrixCoefficients:k,fullRangeFlag:T,maxDecFrameBuffering:v+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:h,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:M}}catch(e){return wt.st("Error parsing HEVC SPS:",e),null}})(i[0]);if(!o)return null;let s=0;if(r.length>0){const t=r[0],e=new xt(ee(t));e.skipBits(16),F(e),F(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),F(e),F(e),V(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&F(e),V(e),V(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),n=e.readBits(1);s=i||n?i&&!n?2:!i&&n?3:0:0}const a=[...e.length?[{arrayCompleteness:1,nalUnitType:yt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:yt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:yt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ne(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:s,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:a}}catch(e){return wt.st("Error building HEVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)})(t),o=!0}}else{const t=(t=>{try{const e=[],i=[],r=[];for(const s of Kt(t)){const n=t.subarray(s.offset,s.offset+s.length),o=te(n[0]);o===bt.SPS?e.push(n):o===bt.PPS?i.push(n):o===bt.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=new xt(ee(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),n=e.readAlignedByte();F(e);let o=1,s=0,a=0,h=0;if((100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i)&&(o=F(e),3===o&&(h=e.readBits(1)),s=F(e),a=F(e),e.skipBits(1),e.readBits(1)))for(let t=0;t<(3!==o?8:12);t++)if(e.readBits(1)){const i=t<6?16:64;let r=8,n=8;for(let t=0;t<i;t++)0!==n&&(n=(r+V(e)+256)%256),r=0===n?r:n}F(e);const c=F(e);if(0===c)F(e);else if(1===c){e.skipBits(1),V(e),V(e);const t=F(e);for(let i=0;i<t;i++)V(e)}F(e),e.skipBits(1);const l=F(e),d=F(e),u=16*(l+1),f=16*(d+1);let p=u,m=f;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=F(e),i=F(e),r=F(e),n=F(e);let s,a;0===(0===h?o:0)?(s=1,a=2-w):(s=3===o?1:2,a=(1===o?2:1)*(2-w)),p-=s*(t+i),m-=a*(r+n)}let b=2,y=2,v=2,g=0,x={num:1,den:1},E=null,k=null;if(e.readBits(1)){if(e.readBits(1)){const t=e.readBits(8);if(255===t)x={num:e.readBits(16),den:e.readBits(16)};else{const e=ie[t];e&&(x=e)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),g=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),y=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&(F(e),F(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&re(e);const i=e.readBits(1);i&&re(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),F(e),F(e),F(e),F(e),E=F(e),k=F(e))}if(null===E)if(S(null===k),(44===i||86===i||100===i||110===i||122===i||244===i)&&16&r)E=0,k=0;else{const t=l+1,e=(2-w)*(d+1),i=Bt.find(t=>t.level>=n)??I(Bt),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);E=r,k=r}return S(null!==k),{profileIdc:i,constraintFlags:r,levelIdc:n,frameMbsOnlyFlag:w,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:a,codedWidth:u,codedHeight:f,displayWidth:p,displayHeight:m,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:y,fullRangeFlag:g,numReorderFrames:E,maxDecFrameBuffering:k}}catch(e){return wt.st("Error parsing AVC SPS:",e),null}})(e[0]);S(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return wt.st("Error building AVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if(100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication){S(null!==t.chromaFormat),S(null!==t.bitDepthLumaMinus8),S(null!==t.bitDepthChromaMinus8),S(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)})(t),o=!0}const s=(t=>{const e=t<0?-1:1;let i=0,r=1,n=1,o=0,s=t=Math.abs(t);for(;;){const t=Math.floor(s),a=t*n+i,h=t*o+r;if(h>1e6)return{num:e*n,den:o};if(i=n,r=o,n=a,o=h,s=1/(s-t),!isFinite(s))break}return{num:e*n,den:o}})(1/(t.metadata.frameRate??57600)).den,a=n.displayAspectWidth,h=n.displayAspectHeight,c=void 0===a||void 0===h?{num:1,den:1}:dt({num:a*n.codedHeight,den:h*n.codedWidth}),l="ap4h"===n.codec||"ap4x"===n.codec,d={muxer:this,track:t,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:c,decoderConfig:n,requiresAnnexBTransformation:o,hasAlphaChannel:l},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Wt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ct&&!n.description){const t=Ce(li.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Et[t.samplingFrequencyIndex],r=kt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Tt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&_t.includes(t.source.Ct),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:e},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;Xt(e),S(e),S(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...Kt(n)].map(t=>n.subarray(t.offset,t.offset+t.length));if(0===t.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");n=(t=>{const e=t.reduce((t,e)=>t+4+e.byteLength,0),i=new Uint8Array(e);let r=0;for(const n of t){const t=new DataView(i.buffer,i.byteOffset,i.byteLength);t.setUint32(r,n.byteLength,!1),r+=4,i.set(n,r),r+=n.byteLength}return i})(t)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);const o=this.createSampleForTrack(r,n,e.timestamp,e.duration,e.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ce(li.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);let o=e.timestamp,s=e.duration;if(r.info.requiresPcmTransformation){const t=Rt(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(s=n.byteLength/t/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){const t=o-r.info.expectedNextPcmPacketTimestamp;if(t<.01)o=r.info.expectedNextPcmPacketTimestamp;else{const e=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,t);o=r.info.expectedNextPcmPacketTimestamp+e}}r.info.expectedNextPcmPacketTimestamp=o+s}const a=this.createSampleForTrack(r,n,o,s,e.type);await this.registerSample(r,a)}finally{r()}}async padWithSilence(t,e,i){const r=dn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=Rt(t.info.decoderConfig.codec),s=r*t.info.numberOfChannels,a=new Uint8Array(n*s).fill(o),h=this.createSampleForTrack(t,new Uint8Array(a.buffer),e,i,"key");await this.registerSample(t,h)}return i}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0),"webvtt"===t.source.Ct&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=/* @__PURE__ */new Set([]);for(const h of t.cueQueue)S(h.timestamp<=e),S(t.lastCueEndTimestamp<=h.timestamp+h.duration),i.add(Math.max(h.timestamp,t.lastCueEndTimestamp)),i.add(h.timestamp+h.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=Or();this.auxBoxWriter.writeBox(e);const i=this.auxTarget.Ht(0,this.auxWriter.getPos()),r=this.createSampleForTrack(t,i,t.lastCueEndTimestamp,n-t.lastCueEndTimestamp,"key");await this.registerSample(t,r),t.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let e=0;e<t.cueQueue.length;e++){const i=t.cueQueue[e];if(i.timestamp>=o)break;fi.lastIndex=0;const r=fi.test(i.text),s=i.timestamp+i.duration;let a=t.cueToSourceId.get(i);if(void 0===a&&o<s&&(a=t.nextSourceId++,t.cueToSourceId.set(i,a)),i.notes){const t=Ur(i.notes);this.auxBoxWriter.writeBox(t)}const h=Dr(i.text,r?n:null,i.identifier??null,i.settings??null,a??null);this.auxBoxWriter.writeBox(h),s===o&&t.cueQueue.splice(e--,1)}const s=this.auxTarget.Ht(0,this.auxWriter.getPos()),a=this.createSampleForTrack(t,s,n,o-n,"key");await this.registerSample(t,a),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:e,size:e.byteLength,type:n,timescaleUnitsToNextSample:dn(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp);let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=dn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):I(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented||(t.startTimestampOffset??=i[0]);for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=dn(e.timestamp-e.decodeTimestamp,t.timescale),o=dn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){S(t.lastSample);const i=dn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(S(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=I(t.timeToSampleTable);if(S(e),1===e.sampleCount){e.sampleDelta=r;const i=t.timeToSampleTable[t.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,t.timeToSampleTable.pop(),e=i)}else e.sampleDelta!==r&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:r}));e.sampleDelta===o?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=I(t.compositionTimeOffsetTable);S(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=dn(e.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));t.lastSample=e}if(t.timestampProcessingQueue.length=0,S(t.lastSample),S(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){S("key"===e.type);const i=dn(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if(S(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&n&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null}),S(t.currentChunk),t.currentChunk.samples.push(e),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,e.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,e.timestamp+e.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,e.timestamp))}async finalizeCurrentChunk(t){if(S(!this.isFragmented),S(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+dn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&I(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)S(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(S(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.sampleQueue.length&&!n.closed)break t;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(e=n,i=n.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!this.isCmaf){S(this.isFragmented);const e=this.nextFragmentNumber++;if(1===e){const t=this.initBoxWriter??this.boxWriter;S(t),this.format.At.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=Ni(this);if(t.writeBox(e),this.format.At.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.format.At.onMoov(e,i)}if(this.isCmaf){S(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.se(!0),this.boxWriter=new wi(this.writer);const t=this.boxWriter.measureBox(Di()),e=this.boxWriter.measureBox(Ui(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}S(this.writer),S(this.boxWriter);const i=this.trackDatas.filter(t=>t.currentChunk),r=Ar(e,i),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(const u of i){u.currentChunk.offset=s,u.currentChunk.moofOffset=n;for(const t of u.currentChunk.samples)s+=t.size;a=Math.min(a,u.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of i)u.currentChunk.offset+=8;this.format.At.onMoof&&this.writer.startTrackingWrites();const l=Ar(e,i);if(this.boxWriter.writeBox(l),this.format.At.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoof(t,e,a)}S(this.writer.getPos()===o),this.format.At.onMdat&&this.writer.startTrackingWrites();const d=Ri(c);d.size=h,this.boxWriter.writeBox(d),this.writer.seek(o+(c?16:8));for(const u of i)for(const t of u.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}for(const u of i)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){if(S(this.writer),S(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();const t=Ni(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;S(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ri(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const t of i.sampleQueue)await this.addSampleToTrack(i,t);i.sampleQueue.length=0}}await this.addSampleToTrack(t,e)}else t.sampleQueue.push(e)}computeSampleTableSizeUpperBound(){S("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;S(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===t.source.Ct&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}ensureOneEnabledTrack(){for(const t of["video","audio","subtitle"]){const e=this.trackDatas.filter(e=>e.type===t);if(0!==e.length&&!e.some(t=>!1!==t.track.metadata.disposition?.default)){const t=e[0];t.track.metadata.disposition={...t.track.metadata.disposition,default:!0}}}}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source.Ct&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const i of this.trackDatas){await this.finalizeCurrentChunk(i),S(null!==i.startTimestampOffset);for(let t=0;t<i.samples.length;t++){const e=i.samples[t];e.timestamp-=i.startTimestampOffset,e.decodeTimestamp-=i.startTimestampOffset}}if(S(this.writer),S(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=Ri(!1);for(let i=0;i<2;i++){const e=Ni(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)S(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format.At.onMoov&&this.writer.startTrackingWrites();const e=Ni(this);if(this.boxWriter.writeBox(e),this.format.At.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoov(t,e)}this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)S(t.data),this.writer.write(t.data),t.data=null;if(this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}}else if(this.isFragmented)if(this.isCmaf){const t=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Di()),this.boxWriter.writeBox(Ui(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,Vi("mfra",void 0,[...e.map(Vr),Oi("mfro",0,0,[ki(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{S(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);S(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}const i=Ni(this);if("reserve"===this.fastStart){S(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format.At.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.format.At.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format.At.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoov(t,e)}}var e;t()}},fn="Mediabunny",pn={video:1,audio:2,subtitle:17},mn=class extends ui{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=q(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.se(!!this.format.At.appendOnly),this.ebmlWriter=new Me(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format.At.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:pe.EBML,data:[{id:pe.EBMLVersion,data:1},{id:pe.EBMLReadVersion,data:1},{id:pe.EBMLMaxIDLength,data:4},{id:pe.EBMLMaxSizeLength,data:8},{id:pe.DocType,data:this.format instanceof Fn?"webm":"matroska"},{id:pe.DocTypeVersion,data:2},{id:pe.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format.At.onEbmlHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onEbmlHeader(t,e)}}maybeCreateSeekHead(t){if(this.format.At.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),s={id:pe.SeekHead,data:[{id:pe.Seek,data:[{id:pe.SeekID,data:e},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:i},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:r},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:n},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:o},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:pe.Duration,data:new ve(0)};this.segmentDuration=t;const e={id:pe.Info,data:[{id:pe.TimestampScale,data:1e6},{id:pe.MuxingApp,data:fn},{id:pe.WritingApp,data:fn},this.format.At.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:pe.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){const i=_e[e.track.source.Ct];S(i);let r=0;if("audio"===e.type&&"opus"===e.track.source.Ct){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=fe(O(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:pe.TrackEntry,data:[{id:pe.TrackNumber,data:e.track.id},{id:pe.TrackUID,data:e.track.id},{id:pe.TrackType,data:pn[e.type]},!1===e.track.metadata.disposition?.default?{id:pe.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:pe.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:pe.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:pe.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:pe.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:pe.FlagCommentary,data:1}:null,{id:pe.FlagLacing,data:0},{id:pe.Language,data:e.track.metadata.languageCode??"und"},{id:pe.CodecID,data:i},e.codecPrivate?{id:pe.CodecPrivate,data:O(e.codecPrivate)}:null,{id:pe.CodecDelay,data:0},{id:pe.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:pe.Name,data:new xe(e.track.metadata.name)}:null,"video"===e.type?this.videoSpecificTrackInfo(e):null,"audio"===e.type?this.audioSpecificTrackInfo(e):null,"subtitle"===e.type?this.subtitleSpecificTrackInfo(e):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,rotation:i}=t.track.metadata,r=[e?{id:pe.DefaultDuration,data:1e9/e}:null],n=i?P(-i):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,s=t.info.decoderConfig.colorSpace,a={id:pe.Video,data:[{id:pe.PixelWidth,data:t.info.width},{id:pe.PixelHeight,data:t.info.height},o?{id:pe.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:pe.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:pe.DisplayUnit,data:3}:null,t.info.alphaMode?{id:pe.AlphaMode,data:1}:null,j(s)?{id:pe.Colour,data:[{id:pe.MatrixCoefficients,data:z[s.matrix]},{id:pe.TransferCharacteristics,data:N[s.transfer]},{id:pe.Primaries,data:R[s.primaries]},{id:pe.Range,data:s.fullRange?2:1}]}:null,n?{id:pe.Projection,data:[{id:pe.ProjectionType,data:0},{id:pe.ProjectionPoseRoll,data:new ye((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=_t.includes(t.track.source.Ct)?Rt(t.track.source.Ct):null;return[{id:pe.Audio,data:[{id:pe.SamplingFrequency,data:new ye(t.info.sampleRate)},{id:pe.Channels,data:t.info.numberOfChannels},e?{id:pe.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:pe.SimpleTag,data:[{id:pe.TagName,data:new xe(e)},"string"==typeof i?{id:pe.TagString,data:new xe(i)}:{id:pe.TagBinary,data:i}]})},i=this.output.St,r=/* @__PURE__ */new Set;for(const{key:n,value:o}of ht(i))switch(n){case"title":e("TITLE",o),r.add("TITLE");break;case"description":e("DESCRIPTION",o),r.add("DESCRIPTION");break;case"artist":e("ARTIST",o),r.add("ARTIST");break;case"album":e("ALBUM",o),r.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),r.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),r.add("GENRE");break;case"comment":e("COMMENT",o),r.add("COMMENT");break;case"lyrics":e("LYRICS",o),r.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":e("PART_NUMBER",void 0!==i.tracksTotal?`${o}/${i.tracksTotal}`:o.toString()),r.add("PART_NUMBER");break;case"discNumber":e("DISC",void 0!==i.discsTotal?`${o}/${i.discsTotal}`:o.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:W(n)}if(i.raw)for(const n in i.raw){const t=i.raw[n];null==t||r.has(n)||("string"==typeof t||t instanceof Uint8Array)&&e(n,t)}0!==t.length&&(this.tagsElement={id:pe.Tags,data:[{id:pe.Tag,data:[{id:pe.Targets,data:[{id:pe.TargetTypeValue,data:50},{id:pe.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.St,e=[],i=/* @__PURE__ */new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(ct(n.mimeType)??""));;){t=0n;for(let e=0;e<8;e++)t<<=8n,t|=BigInt(Math.floor(256*Math.random()));if(0n!==t&&!i.has(t))break}i.add(t),e.push({id:pe.AttachedFile,data:[void 0!==n.description?{id:pe.FileDescription,data:new xe(n.description)}:null,{id:pe.FileName,data:new xe(r)},{id:pe.FileMediaType,data:n.mimeType},{id:pe.FileData,data:n.data},{id:pe.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof gt&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&<(t.data,o.data))||e.push({id:pe.AttachedFile,data:[void 0!==o.description?{id:pe.FileDescription,data:new xe(o.description)}:null,{id:pe.FileName,data:new xe(o.name??"")},{id:pe.FileMediaType,data:o.mimeType??""},{id:pe.FileData,data:o.data},{id:pe.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:pe.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:pe.Segment,size:this.format.At.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format.At.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format.At.onSegmentHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onSegmentHeader(t,e)}}createCues(){this.cues={id:pe.Cues,data:[]}}get segmentDataOffset(){return S(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ct]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings.filter(Boolean))].join(", ")}"`),e})({isWebM:this.format instanceof Fn,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Gt(i),S(i),S(i.decoderConfig),S(void 0!==i.decoderConfig.codedWidth),S(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:dt({num:n,den:o}),a={track:t,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:i.decoderConfig,alphaMode:!!e.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return"vp9"===t.source.Ct?a.codecPrivate=new Uint8Array((t=>{const e=t.split(".");return[1,1,Number(e[1]),2,1,Number(e[2]),3,1,Number(e[3]),4,1,e[4]?Number(e[4]):1]})(a.info.decoderConfig.codec)):"av1"===t.source.Ct?a.codecPrivate=new Uint8Array(Dt(a.info.decoderConfig.codec)):"prores"===t.source.Ct&&(a.codecPrivate=U.encode(i.decoderConfig.codec)),this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Wt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ct&&!n.description){const t=Ce(li.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Et[t.samplingFrequencyIndex],r=kt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Tt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;Xt(e),S(e),S(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:U.encode(e.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if("prores"===t.source.Ct){if(n.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");n=n.subarray(8)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);let s=e.timestamp,a=e.duration;void 0!==t.metadata.frameRate&&(s=J(s,t.metadata.frameRate),a=J(a,t.metadata.frameRate));const h=r.info.alphaMode?e.sideData.alpha??null:null,c=this.createInternalChunk(n,s,a,e.type,h);"vp9"===t.source.Ct&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ce(li.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);const s=this.createInternalChunk(n,e.timestamp,e.duration,e.type);r.chunkQueue.push(s),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0);let n=e.text;const o=Math.round(1e3*e.timestamp);fi.lastIndex=0,n=n.replace(fi,t=>`<${mi((t=>{const e=pi.exec(t);if(!e)throw new Error("Expected match.");return 36e5*Number(e[1]||"0")+6e4*Number(e[2])+1e3*Number(e[3])+Number(e[4])})(t.slice(1,-1))-o)}>`);const s=U.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?U.encode(a):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{r()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.chunkQueue.length&&!n.closed)break t;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(e=n,i=n.chunkQueue[0].timestamp)}if(!e)break;const r=e.chunkQueue.shift();this.writeBlock(e,r)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if("key"!==e.type)return;if(!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new xt(e.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(3===n&&i.skipBits(1),i.readBits(1))return;if(0!==i.readBits(1))return;if(i.skipBits(2),4817730!==i.readBits(24))return;n>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((t,e,i,r)=>{for(let n=e;n<i;n++){const e=Math.floor(n/8);let o=t[e];const s=7-(7&n);o&=~(1<<s),o|=(r&1<<i-n-1)>>i-n-1<<s,t[e]=o}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,r,n=null){return{data:t,type:r,timestamp:e,duration:i,additions:n}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),r=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.closed});let n=!1;if(this.currentCluster){S(null!==this.currentClusterStartMsTimestamp),S(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.At.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const s=/* @__PURE__ */new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:pe.BlockGroup,data:[{id:pe.Block,data:[s,e.data]},"delta"===e.type?{id:pe.ReferenceBlock,data:new ge(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:pe.BlockAdditions,data:[{id:pe.BlockMore,data:[{id:pe.BlockAddID,data:1},{id:pe.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:pe.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:pe.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format.At.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:pe.Cluster,size:this.format.At.appendOnly?-1:5,data:[{id:pe.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(S(this.currentCluster),!this.format.At.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.At.onCluster){S(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=/* @__PURE__ */new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)S(this.cues),this.cues.data.push({id:pe.CuePoint,data:[{id:pe.CueTime,data:r},...n.map(e=>({id:pe.CueTrackPositions,data:[{id:pe.CueTrack,data:e.track.id},{id:pe.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),S(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.At.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new ve(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),S(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},wn=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},bn=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r}),yn=class{constructor(){this.ce=null,this.le=null,this.ut=!1}de(){if(!this.ce)throw new Error("Source is not connected to an output track.");if("canceled"===this.ce.output.state)throw new Error("Output has been canceled.");if("finalizing"===this.ce.output.state||"finalized"===this.ce.output.state)throw new Error("Output has been finalized.");if("pending"===this.ce.output.state)throw new Error("Output has not started.");if(this.ut)throw new Error("Source is closed.")}async It(){}async ue(t){}close(){if(this.le)return;const t=this.ce;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===t.output.state)throw new Error("Cannot call close before output has been started.");this.le=(async()=>{await this.ue(!1),this.ut=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output.fe.onTrackClose(t)})()}async pe(t){return this.le??=(async()=>{await this.ue(t),this.ut=!0})()}},vn=class extends yn{constructor(t){if(super(),this.ce=null,!Mt.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Mt.join(", ")}.`);this.Ct=t}},gn=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},xn=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new et,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.de();const n=this.encodingConfig,o=n.sizeChangeBehavior??"deny";let s=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(s=!0,"deny"===o))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(void 0!==n.transform?.width||void 0!==n.transform?.height||void 0!==n.transform?.rotate||void 0!==n.transform?.crop||!0===n.transform?.force||s&&"passThrough"!==o){let i=n.transform?.width,r=n.transform?.height,a=n.transform?.fit??"fill";s&&"passThrough"!==o&&(S(this.outputWidth),S(this.outputHeight),S("deny"!==o),i=this.outputWidth,r=this.outputHeight,a=o);const h=await t.transform({width:i,height:r,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:a,alpha:n.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const a=n.transform?.frameRate;if(void 0!==a){const n=t.timestamp+t.duration,o=K(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(e instanceof Promise&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof Oe?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new Oe(i)):o.push(new Oe(i,{timestamp:t.timestamp,duration:t.duration}))}catch(n){for(const e of o)e!==t&&e.close();for(const i of e)(i instanceof Oe&&i!==t||"undefined"!=typeof VideoFrame&&i instanceof VideoFrame)&&i.close();throw n}r=o}else r=[t];try{for(const t of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),S(this.encoderInitialized),this.closed)break;const i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(t.timestamp/i),n={...this.defaultEncodeOptions,...t.encodeOptions,...e},o={...n,keyFrame:void 0!==n.keyFrame?n.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,o)).catch(t=>this.setError(t)).finally(()=>{this.customEncoderQueueSize--,e.close()});this.customEncoderQueueSize>=4&&await i}else{S(this.encoder);const e=t.toVideoFrame(),i=G(this.preciseTimings,e.timestamp,t=>t.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===e.timestamp?(r.timestamp!==t.timestamp&&(r.timestampIsValid=!1),r.duration!==t.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:e.timestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(e.format&&!e.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(e,o)}finally{e.close()}}else{this.splitter||(this.splitter=new kn);const{colorFrame:t,alphaFrame:i}=await this.splitter.split(e);this.alphaFrameQueue.push(i);try{this.encoder.encode(t,o)}finally{t.close()}}else try{this.encoder.encode(e,o)}finally{e.close()}this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.lastMuxerPromise}}finally{for(const e of r)e!==t&&e.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;S(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=wn(t,this.frameRateLastSample.clone(),!1);r.setTimestamp(this.frameRateLastTimestamp+o/i),r.setDuration(1/i),await this.processAndEncode(r,e)}catch(n){t.error=n,t.hasError=!0}finally{bn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=hi(this.encodingConfig.quality,this.encodingConfig.bitrate);S(void 0!==e);const i=ti({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source.ce?.metadata.frameRate});let r,n=null;for(const t of i){const e=t.config;if(this.encodingConfig.onEncoderConfig?.(e),r=ci.find(t=>t.supports(this.encodingConfig.codec,e)),r){n=t;break}if("undefined"!=typeof VideoEncoder){if(e.alpha="discard","keep"===this.encodingConfig.alpha&&(e.latencyMode="quality"),!(e.width%2!=1&&e.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if((await VideoEncoder.isConfigSupported(e)).supported){n=t;break}}}if(!n){if("undefined"==typeof VideoEncoder)throw new Error("VideoEncoder is not supported by this browser.");const t=i[0].config,e=i.map(({config:t,quantizer:e})=>null!==e?`quantizer ${e}`:`${t.bitrate} bps`);throw new Error(`This specific encoder configuration (${t.codec}, ${e.join(" / ")}, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`)}const o=n.config;if(null!==n.quantizer&&(this.defaultEncodeOptions=si(this.encodingConfig.codec,n.quantizer)),r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(t,e)=>{if(!(t instanceof be))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");gn(this.source.ce,t),this.encodingConfig.onEncodedPacket?.(t,e),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ce,t,e).catch(t=>{this.setError(t)})},this.customEncoder.onError=t=>{this.setError(t)},await this.customEncoder.init();else{const t=[],e=[];let i=0,r=0;const n=(t,e,i)=>{const r={};if(e){const t=new Uint8Array(e.byteLength);e.copyTo(t),r.alpha=t}let n=be.fromEncodedChunk(t,r);const o=G(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&O(e.description)[4]);return Zt(t,i)}return Kt(t)})(i,e)){const e=i[t.offset],r=te(e);if(r>=bt.NON_IDR_SLICE&&r<=bt.SLICE_DPC)return"delta";if(r===bt.IDR)return"key";if(r===bt.SEI&&(!ot()||at()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=ee(e);let n=1;do{let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}if(6===t){const t=new xt(r);t.pos=8*n;const e=F(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&O(e.description)[21]);return Zt(t,i)}return Kt(t)})(i,e)){const e=ne(i[t.offset]);if(e<yt.BLA_W_LP)return"delta";if(e<=yt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new xt(i);if(2!==t.readBits(2))return null;const e=t.readBits(1);return(t.readBits(1)<<1)+e===3&&t.skipBits(1),t.readBits(1)?null:0===t.readBits(1)?"key":"delta"}case"av1":{let t=!1;for(const{type:e,data:r}of function*(t){const e=new xt(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return t>=2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);S(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}}(i))if(1===e){const e=new xt(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new xt(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:W(t),S(!1)}})(this.encodingConfig.codec,i.decoderConfig,n.data)),(s&&s.microsecondTimestamp===t.timestamp||null!==a)&&(n=n.clone({timestamp:s?.timestampIsValid?s.timestamp:void 0,duration:s?.durationIsValid?s.duration:void 0,type:a??void 0})),gn(this.source.ce,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ce,n,i).catch(t=>{this.setError(t)}),this.emittedEncoderPackets++},s=/* @__PURE__ */new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(o,s)=>{if(!this.alphaEncoder)return void n(o,null,s);const a=this.alphaFrameQueue.shift();S(void 0!==a),a?(this.alphaEncoder.encode(a,{...this.defaultEncodeOptions,keyFrame:"key"===o.type}),r++,a.close(),t.push({chunk:o,meta:s})):0===r?n(o,null,s):(e.push(i+r),t.push({chunk:o,meta:s}))},error:t=>{t.stack=s,this.setError(t)}}),this.encoder.configure(o),"keep"===this.encodingConfig.alpha){const s=/* @__PURE__ */new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(S(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();S(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=s,this.setError(t)}}),this.alphaEncoder.configure(o)}}S(this.source.ce),this.muxer=this.source.ce.output.fe,this.encoderInitialized=!0})()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=K(this.frameRateLastEndTimestamp,t);await this.padFrameRate(e)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await(this.alphaEncoder?.flush()),await new Promise(t=>setTimeout(t,25))))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},En=null,kn=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!En){const t=new Blob([`(${Tn.toString()})()`],{type:"application/javascript"});En=URL.createObjectURL(t)}this.worker=new Worker(En),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=q();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Tn=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",t=>{const{id:r,sourceFrame:n}=t.data;e=e.then(async()=>{try{const{colorFrame:t,alphaFrame:e}=await i(n);self.postMessage({id:r,colorFrame:t,alphaFrame:e},{transfer:[t,e]})}catch(t){self.postMessage({id:r,error:t.message})}finally{n.close()}})});const i=async e=>{const i=e.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=e.allocationSize();if(t&&t.byteLength===o||(t=new Uint8Array(o)),await e.copyTo(t),"RGBA"===i||"BGRA"===i)return r(t,i,e);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return n(t,i,e);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=r*n,s=o+Math.ceil(r/2)*Math.ceil(n/2)*2,a=new Uint8Array(s);for(let l=0,d=3;l<o;l++,d+=4)a[l]=t[d];a.fill(128,o);const h=new VideoFrame(t,{format:"RGBA"===e?"RGBX":"BGRX",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),c={format:"I420",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[a.buffer]};return{colorFrame:h,alphaFrame:new VideoFrame(a,c)}},n=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=e.includes("P10"),s=e.includes("P12"),a=o||s?2:1;let h,c;e.startsWith("I420")?(h=Math.ceil(r/2),c=Math.ceil(n/2)):e.startsWith("I422")?(h=Math.ceil(r/2),c=n):(h=r,c=n);const l=r*n,d=l*a,u=l*a+h*c*a*2,f=e.replace("A",""),p=Math.ceil(r/2)*Math.ceil(n/2),m=new Uint8Array(d+p*a*2),w=u;m.set(t.subarray(w,w+d),0);const b=d,y=o?512:s?2048:128;1===a?m.fill(y,b):new Uint16Array(m.buffer,b,2*p).fill(y);const v=o?"I420P10":s?"I420P12":"I420",g=new VideoFrame(t.subarray(0,u),{format:f,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),x={format:v,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[m.buffer]};return{colorFrame:g,alphaFrame:new VideoFrame(m,x)}}},Mn=class extends vn{constructor(t,e){if(!("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(t=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding config must be an object.");if(!Mt.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Mt.join(", ")}.`);const e=t.bitrate;if(void 0===t.quality&&void 0===e)throw new TypeError("config.quality must be provided.");if(void 0!==t.quality&&void 0!==e)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(void 0!==t.quality&&!(t.quality instanceof ei))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof ei)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==t.keyFrameInterval&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==t.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==t.transform){if("object"!=typeof t.transform||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==t.transform.width&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==t.transform.height&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==t.transform.fit&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.transform.width&&void 0!==t.transform.height&&void 0===t.transform.fit&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==t.transform.fit&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(void 0!==t.transform.rotate&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.transform.crop&&He(t.transform.crop,"config.transform."),void 0!==t.transform.process&&"function"!=typeof t.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.");if(void 0!==t.transform.frameRate&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==t.transform.force&&"boolean"!=typeof t.transform.force)throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(void 0!==t.onEncodedPacket&&"function"!=typeof t.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==t.onEncoderConfig&&"function"!=typeof t.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(void 0!==t.onEncodedSample&&"function"!=typeof t.onEncodedSample)throw new TypeError("config.onEncodedSample, when provided, must be a function.");Ze(t.codec,t)})(e),super(e.codec),this.me=new xn(this,e),this.we=t}add(t,e=0,i){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new Oe(this.we,{timestamp:t,duration:e});return this.me.add(r,!0,i)}ue(t){return this.me.flushAndClose(t)}},_n=class extends yn{constructor(t){if(super(),this.ce=null,!At.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${At.join(", ")}.`);this.Ct=t}},Cn=class extends yn{constructor(t){if(super(),this.ce=null,!St.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${St.join(", ")}.`);this.Ct=t}},An=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Mt.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>At.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>St.includes(t))}be(t){return""}},Sn=class extends An{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this.At=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:1,max:t}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}ye(t){return new un(t,this)}},Bn=class extends Sn{constructor(t){super(t)}get ve(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Mt,...Ct,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...St]}be(t){return(new In).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Pn=class extends Sn{constructor(t){super(t)}get ve(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Mt,...Ct,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...St]}},In=class extends Sn{constructor(t){super(t)}get ve(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Mt,...At]}be(t){return(new Bn).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},$n=class extends An{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.appendOnly&&"boolean"!=typeof t.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==t.minimumClusterDuration&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==t.onEbmlHeader&&"function"!=typeof t.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==t.onSegmentHeader&&"function"!=typeof t.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==t.onCluster&&"function"!=typeof t.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this.At=t}ye(t){return new mn(t,this)}get ve(){return"Matroska"}getSupportedTrackCounts(){const t=127;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:1,max:t}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Mt,...Ct,..._t.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...St]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},Fn=class extends $n{constructor(t){super(t)}getSupportedCodecs(){return[...Mt.filter(t=>["vp8","vp9","av1"].includes(t)),...At.filter(t=>["opus","vorbis"].includes(t)),...St]}get ve(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}be(t){return(new $n).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},Vn=["video","audio","subtitle"],On=class t{constructor(t,e,i,r,n){this.id=t,this.output=e,this.type=i,this.source=r,this.metadata=n}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=ft(this.metadata.group),r=ft(e.metadata.group);for(const t of i){if(this.type!==e.type&&r.some(e=>t===e))return!0;if(r.some(e=>t.ge.has(e)))return!0}return!1}},Dn=class extends On{constructor(t,e,i,r){super(t,e,"video",i,r)}},Un=class extends On{constructor(t,e,i,r){super(t,e,"audio",i,r)}},Rn=class extends On{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},Nn=class t{constructor(){this.ge=/* @__PURE__ */new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.ge.add(e),e.ge.add(this)}},zn=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&(e=t.languageCode,!Z.test(e)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var e;if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.group&&!(t.group instanceof Nn)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof Nn))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},jn=class extends pt{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.xe)throw new TypeError(t);const e=this.Ee();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Nn,this.tracks=[],this.ke=null,this.Te=/* @__PURE__ */new Set,this.Me=null,this._e=null,this.Ce=null,this.Ae=null,this.Se=new H,this.St={},this.Be=null,this.xe=null,this.Pe=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof An))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof en||t.target instanceof hn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof en&&this.Ie(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof en)&&"function"!=typeof t.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this.$e=t.target,this.ke=t.onFinalize??null,this.Fe=t.initTarget??null,this.Fe instanceof en&&this.Ie(this.Fe),this.fe=t.format.ye(this)}Ve(t){S(this.$e instanceof hn);const e=this.$e.getTarget(t),i=t=>{if(!(t instanceof en))throw new TypeError("getTarget must return a Target.");return t};return e instanceof Promise?e.then(i):i(e)}async Oe(t){S(this.$e instanceof hn);const e=await this.Ve(t);return this.it("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Lt():this.Ie(e),e}Ie(t){this.Te.add(t),t.on("finalized",()=>this.Te.delete(t),{once:!0})}async he(){if(S(null!==this.Fe),this.Fe instanceof en)return this.Fe;const t=await this.Fe();return"canceled"===this.state?await t.Lt():this.Ie(t),t}ae(){return null!==this.Fe}Ee(){if(this.Be)return this.Be;if(this.xe)return this.xe;if(this.$e instanceof en)return this.it("target",{target:this.$e,request:null,isRoot:!0}),this.Be=this.$e,this.$e;const t={path:this.$e.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this.Ve(t),i=e=>("canceled"===this.state?e.Lt():this.Ie(e),this.it("target",{target:e,request:t,isRoot:!0}),this.Be=e,e);return e instanceof Promise?this.xe=e.then(i):i(e)}se(t){return this.Me??=(async()=>{const e=await this.Ee(),i=new tn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof vn))throw new TypeError("source must be a VideoSource.");if(zn(e),void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&e.rotation)throw new Error(`${this.format.ve} does not support video rotation metadata.`);if(void 0!==e.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);const i={...e};return i.group??=this.defaultTrackGroup,this.De(new Dn(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof _n))throw new TypeError("source must be an AudioSource.");zn(e);const i={...e};return i.group??=this.defaultTrackGroup,this.De(new Un(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Cn))throw new TypeError("source must be a SubtitleSource.");zn(e);const i={...e};return i.group??=this.defaultTrackGroup,this.De(new Rn(this.tracks.length+1,this,t,i))}setMetadataTags(t){if((t=>{if(!t||"object"!=typeof t)throw new TypeError("tags must be an object.");if(void 0!==t.title&&"string"!=typeof t.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==t.description&&"string"!=typeof t.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==t.artist&&"string"!=typeof t.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==t.album&&"string"!=typeof t.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==t.albumArtist&&"string"!=typeof t.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==t.trackNumber&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==t.tracksTotal&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==t.discNumber&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==t.discsTotal&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==t.genre&&"string"!=typeof t.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==t.date&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==t.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||e instanceof Uint8Array||e instanceof vt||e instanceof gt||mt(e)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this.St=t}De(t){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t.source.ce)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((e,i)=>e+(i.type===t.type?1:0),0),r=e[t.type].max;if(i===r)throw new Error(0===r?`${this.format.ve} does not support ${t.type} tracks.`:`${this.format.ve} does not support more than ${r} ${t.type} track${1===r?"":"s"}.`);const n=e.total.max;if(this.tracks.length===n)throw new Error(`${this.format.ve} does not support more than ${n} tracks${1===n?"":"s"} in total.`);if(t.isVideoTrack()){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support video tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported video codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}else if(t.isAudioTrack()){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support audio tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported audio codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}else if(t.isSubtitleTrack()){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support subtitle tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported subtitle codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}return this.tracks.push(t),t.source.ce=t,t}hasEnoughTracks(){const t=this.format.getSupportedTrackCounts();for(const i of Vn)if(this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0)<t[i].min)return!1;const e=t.total.min;return!(this.tracks.length<e)}async start(){const t=this.format.getSupportedTrackCounts();for(const i of Vn){const e=this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0),r=t[i].min;if(e<r)throw new Error(r===t[i].max?`${this.format.ve} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format.ve} requires at least ${r} ${i} track${1===r?"":"s"}.`)}const e=t.total.min;if(this.tracks.length<e)throw new Error(e===t.total.max?`${this.format.ve} requires exactly ${e} track${1===e?"":"s"}.`:`${this.format.ve} requires at least ${e} track${1===e?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this._e?(wt.ht("Output has already been started."),this._e):this._e=(async()=>{this.state="started";const t=this.Se.acquire();try{await this.fe.start();const t=this.tracks.map(t=>t.source.It());await Promise.all(t)}finally{(await t)()}})()}getMimeType(){return this.fe.getMimeType()}async cancel(){return this.Ce?(wt.ht("Output has already been canceled."),this.Ce):"finalizing"!==this.state&&"finalized"!==this.state?this.Ce=(async()=>{this.state="canceled";const t=await this.Se.acquire();try{const t=this.tracks.map(t=>t.source.pe(!0));await Promise.all(t),await Promise.all([...this.Te].map(t=>t.Lt())),this.Te.clear()}finally{t()}})():void("finalized"===this.state&&wt.ht("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this.Ae?(wt.ht("Output has already been finalized."),this.Ae):this.Ae=(async()=>{this.state="finalizing";const t=await this.Se.acquire();try{const t=this.tracks.map(t=>t.source.pe(!1));if(await Promise.all(t),await this.fe.finalize(),this.Me){const t=await this.Me;t.finalized||(await t.flush(),await t.finalize())}this.ke&&await this.ke(),this.state="finalized"}finally{await Promise.all([...this.Te].map(t=>t.Lt().catch(()=>{}))),this.Te.clear(),t()}})()}},Ln={low:"medium",medium:"high",high:"very-high"},Hn=["low","medium","high","ultra"],Gn={medium:.3*Math.exp(1.2769),high:.3*Math.exp(2.5538*.75),"very-high":.3*Math.exp(2.5538)},qn={avc:1,vp9:.6,vp8:1.2};function Wn(t,e,i){const r=e/i;return Math.ceil(t*r*1.1/8+1e6)}function Xn(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new v("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new v("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);const n=t.bitrate,o="string"==typeof n&&Hn.includes(n)?n:null,s="ultra"===o?"ultra":o?"constant-quality":"bitrate",a="number"==typeof n&&Number.isFinite(n)&&n>0?Math.round(n):"ultra"===o?function(t,e,i){return Math.max(1e6,Math.round(t*e*i*.5))}(i,r,t.frameRate):function(t,e,i,r){const n=i*r,o=3e6*Math.pow(n/2073600,.95),s=qn[e]??1;return Math.max(25e4,1e3*Math.ceil(o*s*Gn[Ln[t]]/1e3))}(o??"medium",e,i,r),h=o&&"ultra"!==o?Ln[o]:void 0;return{format:t.format,extension:"mp4"===t.format?".mp4":".webm",mimeType:"mp4"===t.format?"video/mp4":"video/webm",codec:e,bitrate:a,bitrateMode:t.bitrateMode,qualityPreset:o,rateControlIntent:s,qualityLevel:h,contentHint:(c=t.contentHint,""===c||"motion"===c||"detail"===c||"text"===c?c:"text"),estimatedBytes:Wn(a,t.frameCount,t.frameRate),latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:i,height:r,transparent:t.transparent};var c}function Yn(t,e){if(!(e||t.estimatedBytes<=1e8))throw new v("VIDEO_OUTPUT_TOO_LARGE",`The estimated ${function(t){return t>=1e9?`${(t/1e9).toFixed(1)} GB`:`${Math.round(t/1e6)} MB`}(t.estimatedBytes)} video is too large for an in-memory export. Use saveVideo() in a browser with the File System Access API, lower the resolution, duration, or quality, or pass allowLargeInMemory: true to toVideoBlob().`)}var Qn=["vp9","vp8"],Jn=["avc"],Kn=class{async $record(t,e,i,r={kind:"blob",allowLargeInMemory:t.allowLargeInMemory??!1}){this.N(t.signal),this.Ue();const n=await this.Re(t);this.Ne(t,"video export plan",n),"blob"===r.kind&&Yn(n,r.allowLargeInMemory),this.ze(i,"recording","probing",0,n.frameCount,n);const o="mp4"===n.format?new Bn:new Fn,s="stream"===r.kind?new sn(r.writable,{chunked:!0}):new on,a=new jn({format:o,target:s}),h=this.je(n);let c;const l=new Mn(e.canvas,{codec:n.codec,quality:h,alpha:n.transparent?"keep":"discard",latencyMode:n.latencyMode,hardwareAcceleration:n.hardwareAcceleration,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:"deny",contentHint:n.contentHint,onEncoderConfig:e=>{c="quantizer"===e.bitrateMode?"quantizer":"ultra"===n.rateControlIntent?"bitrate-fallback":"bitrate",this.Ne(t,"video encoder config",e,{rateControl:c})}});a.addVideoTrack(l,{frameRate:n.frameRate});let d=!1,u=!1;const f=()=>{d||(d=!0,l.close())};try{if(await x(a.start(),"Video output did not start within 30000ms.",t.signal,3e4),this.ze(i,"recording","probing",0,n.frameCount,n,c),await e.$render({frameCount:n.frameCount,frameRate:n.frameRate,signal:t.signal,prepareFrame:t.prepareFrame,onFrame:async({frameIndex:e})=>{this.N(t.signal),await this.Le(l.add(e/n.frameRate,1/n.frameRate),t.signal),this.ze(i,"recording","capturing",e+1,n.frameCount,n,c)}}),this.N(t.signal),f(),this.ze(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n,c),await x(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.ze(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n,c),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new v("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(p){f(),await(async()=>{if(!u){u=!0;try{await a.cancel()}catch{}}})();const t=this.He(p);throw i?.({state:"error",message:t.message,estimatedBytes:n.estimatedBytes}),t}}async Re(t){const e=Xn(t),i="mp4"===t.format?new Bn:new Fn,r="mp4"===t.format?Jn:Qn,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t)),o=this.je(e);let s=null;for(const a of n)if(await ai(a,{width:e.width,height:e.height,quality:o,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,contentHint:e.contentHint})){s=a;break}if(!s)throw new v("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${r.join(" or ")} at ${e.width}x${e.height}. Try a browser/device with native WebCodecs encoding support or reduce the export dimensions.`);return Xn(t,s)}je(t){const e=function(t){return"ultra"===t.rateControlIntent?{kind:"ultra",bitrate:t.bitrate}:t.qualityLevel?{kind:"named",level:t.qualityLevel}:{kind:"bitrate",bitrate:t.bitrate,bitrateMode:t.bitrateMode}}(t);return"named"===e.kind?new ei(e.level):"ultra"===e.kind?new ei({bitrate:e.bitrate,bitrateMode:"variable",quantizer:0}):new ei({bitrate:e.bitrate,bitrateMode:e.bitrateMode})}Ue(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new v("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}Le(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(g());const n=()=>r(g());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}N(t){if(t?.aborted)throw g()}ze(t,e,i,r,n,o,s){t?.({state:e,phase:i,frameIndex:r,frame:r,totalFrames:n,progress:n>0?r/n:0,rateControl:s,estimatedBytes:o.estimatedBytes})}He(t){return t instanceof v?t:new v("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}Ne(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Zn=class{Ge;_;C;constructor(t,e){this.Ge=new Kn,this._=t,this.C=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.k(e,t),n=Xn(i),o=this.qe();if(!o){Yn(n,!1);const o=await this.We(i,{kind:"blob",allowLargeInMemory:!1},t.onProgress);if(!o)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");return void(new r).$downloadFile(o,this.Xe(t.filename,`.${e}`))}let s;try{s=await(await o({suggestedName:this.Xe(t.filename,`.${e}`)??`textmode-export.${e}`,types:[{description:"mp4"===e?"MP4 video":"WebM video",accept:{["mp4"===e?"video/mp4":"video/webm"]:[`.${e}`]}}]})).createWritable()}catch(a){const t=function(t){return t instanceof v?"VIDEO_EXPORT_ABORTED"===t.code?t:void 0:t instanceof DOMException&&"AbortError"===t.name||t instanceof Error&&"AbortError"===t.name?g():void 0}(a);if(t)throw t;throw new v("VIDEO_EXPORT_FAILED",a instanceof Error?a.message:"Could not open the selected output file.",a)}await this.We(i,{kind:"stream",writable:s},t.onProgress)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.k(e,t);Xn(i);const r=await this.We(i,{kind:"blob",allowLargeInMemory:Boolean(t.allowLargeInMemory)},t.onProgress);if(!r)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async We(t,e,i){const r=new E(this._,this.C,t.width,t.height);try{return await this.Ge.$record(t,r,i,e)}catch(n){throw i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n}}k(t,e){const i=this.Ye(e.frameRate,60),r=this.Ye(e.frameCount,300),n=this.Qe(e.pixelDensity,1),o=this.Je(),s=Math.max(1,Math.round(this._.canvas.width/o*n)),a=Math.max(1,Math.round(this._.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,bitrate:this.Et(e.bitrate),bitrateMode:this.Tt(e.bitrateMode),contentHint:this.Ke(e.contentHint),latencyMode:this.Ze(e.latencyMode),hardwareAcceleration:this.ti(e.hardwareAcceleration),keyFrameInterval:this.ei(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),allowLargeInMemory:Boolean(e.allowLargeInMemory),signal:e.signal,prepareFrame:e.prepareFrame}}Ye(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}Qe(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}Et(t){return"number"==typeof t&&Number.isFinite(t)&&t>0||"low"===t||"medium"===t||"high"===t||"ultra"===t?t:"medium"}Tt(t){return"constant"===t||"variable"===t?t:"variable"}Ke(t){return""===t||"motion"===t||"detail"===t||"text"===t?t:"text"}Ze(t){return"quality"===t||"realtime"===t?t:"quality"}ti(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}ei(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}Je(){const t=this._.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}qe(){return globalThis.showSaveFilePicker}Xe(t,e){if(!t)return;const i=t.trim();return i?i.toLowerCase().endsWith(e)?i:`${i}${e}`:void 0}},to=class extends i{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let a=0;a<r.rows;a++)for(let t=0;t<r.cols;t++){const r=4*o,h=this.$getEncodedCharacterValue(e.characterPixels,r),c=this.$extractCellTransform(e.characterPixels,r),d=s(n,h)?.character??" ";i.push({x:t,y:a,character:d,foreground:l(e.primaryColorPixels,r),background:l(e.secondaryColorPixels,r),transform:{invert:c.isInverted,flipX:c.flipHorizontal,flipY:c.flipVertical,rotation:c.rotation}}),o++}return i}},eo="textmode.document",io="2.0.0",ro={[t.NORMAL]:"normal",[t.ADDITIVE]:"additive",[t.MULTIPLY]:"multiply",[t.SCREEN]:"screen",[t.SUBTRACT]:"subtract",[t.DARKEN]:"darken",[t.LIGHTEN]:"lighten",[t.OVERLAY]:"overlay",[t.SOFT_LIGHT]:"softLight",[t.HARD_LIGHT]:"hardLight",[t.COLOR_DODGE]:"colorDodge",[t.COLOR_BURN]:"colorBurn",[t.DIFFERENCE]:"difference",[t.EXCLUSION]:"exclusion"},no=class{k(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}ii(t){return t.includeMetadata?{createdAt:/* @__PURE__ */(new Date).toISOString(),generator:{name:"textmode.export.js",version:"1.8.0-beta.2"}}:void 0}ri(t,e){return"rgba"===e?{...t}:`#${[t.r,t.g,t.b,t.a].map(t=>t.toString(16).padStart(2,"0")).join("")}`}ni(t,e,i,r){const n=[];for(let o=0;o<i;o++){const i=o*e,s=t.slice(i,i+e).map(t=>({x:t.x,y:t.y,character:t.character,foreground:this.ri(t.foreground,r),background:this.ri(t.background,r),transform:{...t.transform}}));n.push(s)}return{encoding:"object-rows-v1",rows:n}}oi(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}si(t,e){const i=(new to).$extractCellData(t);return this.ni(i,t.grid.cols,t.grid.rows,e.colorMode)}ai(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:ro[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.oi(t),cells:this.si(t,e)}}$generateJSONData(e,i={}){const r=this.k(i),n=this.ii(r);if("all"===r.target){const i=function(e){return[e.layers.base,...e.layers.all].map(i=>{const r=c(e,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??t.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(e),o=i[0].grid;return{format:eo,formatVersion:io,target:"all",...n?{metadata:n}:{},canvas:{width:o.width,height:o.height},layers:i.map(t=>this.ai(t,r))}}const o=c(e,r.layer);return{format:eo,formatVersion:io,target:"selected",...n?{metadata:n}:{},canvas:{width:o.grid.width,height:o.grid.height},grid:this.oi(o),layer:{id:o.id,cells:this.si(o,r)}}}$generateJSONString(t,e={}){const i=this.k(e),r=this.$generateJSONData(t,i),n="number"==typeof i.pretty?i.pretty:i.pretty?2:0;return JSON.stringify(r,null,n)}$saveJSON(t,e={}){const i=this.k(e);(new r).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename)}},oo="textmode-export-overlay__stack",so="textmode-export-overlay__stack--dense",ao="textmode-export-overlay__stack--compact",ho="textmode-export-overlay__section",co="textmode-export-overlay--dragging",lo="textmode-export-overlay__label",uo="textmode-export-overlay__field",fo="textmode-export-overlay__field--compact",po="textmode-export-overlay__field--dense",mo="textmode-export-overlay__field--full",wo="textmode-export-overlay__field--channel",bo="textmode-export-overlay__input",yo="textmode-export-overlay__muted",vo="textmode-export-overlay__button--primary",go="textmode-export-overlay__button--secondary",xo="textmode-export-overlay__button--full",Eo="textmode-export-overlay__link-icon",ko=class{element;mounted=!1;destroyed=!1;mount(t){if(this.destroyed)throw new Error("Cannot mount a destroyed component");if(this.mounted)return;const e=this.render();t.appendChild(e),this.element=e,this.onMount(),this.mounted=!0}unmount(){this.mounted&&this.element&&(this.hi(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this.ci(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}hi(){}ci(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}},To=class t extends ko{static li="http://www.w3.org/2000/svg";di;get dragHandleElement(){if(!this.di)throw new Error("Header drag handle is not mounted yet");return this.di}render(){this.di=void 0;const t=document.createElement("div");t.classList.add(oo,so,"textmode-export-overlay__header");const e=document.createElement("div");e.classList.add("textmode-export-overlay__header-title-row");const i=document.createElement("div");i.classList.add("textmode-export-overlay__header-identity");const r=this.ui("Move export overlay","textmode-export-overlay__grab-handle",[{d:"M9 5h.01"},{d:"M15 5h.01"},{d:"M9 12h.01"},{d:"M15 12h.01"},{d:"M9 19h.01"},{d:"M15 19h.01"}]);this.di=r;const n=document.createElement("strong");n.textContent="textmode.export.js",n.classList.add("textmode-export-overlay__title");const o=document.createElement("div");o.classList.add("textmode-export-overlay__header-links");const s=this.fi("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",Eo,[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"}]),a=this.fi("https://code.textmode.art/docs/support","Support textmode.export.js","textmode-export-overlay__support-icon",[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"},{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"},{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"}]);o.appendChild(s),o.appendChild(a),i.appendChild(r),i.appendChild(n),e.appendChild(i),e.appendChild(o);const h=document.createElement("div");return h.classList.add("textmode-export-overlay__divider"),t.appendChild(e),t.appendChild(h),t}ui(t,e,i){const r=document.createElement("button");return r.type="button",r.classList.add(e),r.setAttribute("aria-label",t),r.title=t,r.appendChild(this.pi(Eo,i)),r}fi(t,e,i,r){const n=document.createElement("a");return n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("textmode-export-overlay__support-link"),n.setAttribute("aria-label",e),n.appendChild(this.pi(i,r)),n}pi(e,i){const r=document.createElementNS(t.li,"svg");r.setAttribute("xmlns",t.li),r.setAttribute("width","18"),r.setAttribute("height","18"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.classList.add(e);for(const n of i){const e=document.createElementNS(t.li,"path");for(const[t,i]of Object.entries(n))e.setAttribute(t,i);r.appendChild(e)}return r}},Mo=class extends ko{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(uo),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(lo),e.textContent=this.props.label,this.props.labelFor&&(e.htmlFor=this.props.labelFor),t.appendChild(e),this.props.description){const e=document.createElement("span");e.classList.add(yo),e.textContent=this.props.description,t.appendChild(e)}return t}attachControl(t){this.root.appendChild(t)}update(t){this.props=t,super.update(t)}onUpdate(t){const e=this.root;for(;e.firstChild;)e.removeChild(e.firstChild);this.props=t,e.classList.add(uo),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(lo),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(yo),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(fo,po,mo,wo),e){case"compact":t.classList.add(fo);break;case"dense":t.classList.add(po);break;case"full":t.classList.add(mo);break;case"channel":t.classList.add(wo)}}},_o=class extends ko{props;select;handleChange=()=>{this.props.defaultValue=this.select.value};constructor(t){super(),this.props=t}render(){return this.select=document.createElement("select"),this.select.classList.add(bo),this.props.id&&(this.select.id=this.props.id),this.populateOptions(),this.select.addEventListener("change",this.handleChange),this.select}get selectElement(){return this.select}get value(){return this.select.value}set value(t){this.select&&(this.select.value=t),this.props.defaultValue=t}hi(){this.select.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,this.populateOptions(),t.defaultValue&&(this.select.value=t.defaultValue)}update(t){this.props={...this.props,...t},this.select&&(t.id&&(this.select.id=t.id),t.options&&this.populateOptions(),void 0!==t.defaultValue&&(this.select.value=t.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const t of this.props.options){const e=document.createElement("option");e.value=t.value,e.textContent=t.label,this.select.appendChild(e)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}},Co=class extends ko{props;button;constructor(t){super(),this.props=t}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add("textmode-export-overlay__button"),"secondary"===this.props.variant?this.button.classList.add(go):this.button.classList.add(vo),this.props.fullWidth&&this.button.classList.add(xo),this.button.disabled=Boolean(this.props.disabled),this.button}get buttonElement(){return this.button}setLabel(t){this.props.label=t,this.button.textContent=t}setDisabled(t){this.props.disabled=t,this.button.disabled=t}onUpdate(t){this.props=t,this.button.textContent=t.label,this.button.disabled=Boolean(t.disabled),"secondary"===t.variant?(this.button.classList.add(go),this.button.classList.remove(vo)):(this.button.classList.add(vo),this.button.classList.remove(go)),this.button.classList.toggle(xo,Boolean(t.fullWidth))}},Ao=class{et={};mi(t){const e=this.et[t];if(e)return e;const i=/* @__PURE__ */new Set;return this.et[t]=i,i}$on(t,e){const i=this.mi(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.et[t]}}$emit(t,e){const i=this.et[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.et))delete this.et[t]}},So=class{wi;et=/* @__PURE__ */new Set;constructor(t){this.wi=t}get snapshot(){return Object.freeze({...this.wi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.wi[o]!==t[o]){i=!0;break}if(!i)return;this.wi=Object.assign({},this.wi,t);const r=this.snapshot;for(const o of[...this.et])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.et.add(t),t(this.snapshot),()=>{this.et.delete(t)}}$reset(t){this.wi=t;const e=this.snapshot;for(const i of[...this.et])i(e)}},Bo=/* @__PURE__ */new Set(["txt","json","svg","image"]),Po=class{api;constructor(t){this.api=t}async $copy(t,e){switch(t){case"txt":{const t=this.api.toString(e);await navigator.clipboard.writeText(t);break}case"json":{const t=this.api.toJSONString(e);await navigator.clipboard.writeText(t);break}case"svg":{const t=this.api.toSVG(e);await navigator.clipboard.writeText(t);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}static isClipboardFormat(t){return Bo.has(t)}},Io={txt:(t,e)=>Promise.resolve(t.saveStrings(e)),json:(t,e)=>Promise.resolve(t.saveJSON(e)),image:(t,e)=>t.saveCanvas(e),svg:(t,e)=>Promise.resolve(t.saveSVG(e)),gif:(t,e,i)=>{const r={...e,onProgress:i.onGIFProgress};return t.saveGIF(r)},video:(t,e,i)=>{const r={...e,onProgress:i.onVideoProgress};return t.saveVideo(r)}},$o=class{api;events;constructor(t,e){this.api=t,this.events=e}async $requestExport(t,e,i={}){this.events.$emit("export:request",{format:t});try{const r={onGIFProgress:i.onGIFProgress?e=>{i.onGIFProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"gif"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0,onVideoProgress:i.onVideoProgress?e=>{i.onVideoProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"video"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0};await Io[t](this.api,e,r),this.events.$emit("export:success",{format:t})}catch(r){throw this.events.$emit("export:error",{format:t,error:r}),r}}},Fo=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Vo=class{key;constructor(t="textmode.export.overlay.position.v1"){this.key=t}load(){try{const t=window.localStorage.getItem(this.key);if(!t)return;const e=JSON.parse(t);if(1!==e.version||!Fo(e.offsetX)||!Fo(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(Fo(t)&&Fo(e))try{const i={version:1,offsetX:t,offsetY:e};window.localStorage.setItem(this.key,JSON.stringify(i))}catch{}}clear(){try{window.localStorage.removeItem(this.key)}catch{}}},Oo=class{modifier;host;surface;storage;animationFrameId=null;handleUpdate;bound=!1;dragHandle;dragState;position;renderedOffset;handlePointerDown=t=>this.onPointerDown(t);handlePointerMove=t=>this.onPointerMove(t);handlePointerUp=t=>this.onPointerUp(t);handleKeyDown=t=>this.onKeyDown(t);constructor(t,e,i=e,r=new Vo){this.modifier=t,this.host=e,this.surface=i,this.storage=r,this.handleUpdate=()=>this.scheduleUpdate();const n=this.storage.load();this.position=n?{mode:"custom",offsetX:n.offsetX,offsetY:n.offsetY}:{mode:"auto",offsetX:8,offsetY:8},this.renderedOffset={offsetX:this.position.offsetX,offsetY:this.position.offsetY}}getPosition(){return Object.freeze({...this.position})}setPosition(t,e={}){Number.isFinite(t.offsetX)&&Number.isFinite(t.offsetY)&&(this.position={mode:"custom",offsetX:t.offsetX,offsetY:t.offsetY},this.scheduleUpdate(),(e.persist??1)&&this.storage.save(this.position.offsetX,this.position.offsetY))}resetPosition(){this.position={mode:"auto",offsetX:8,offsetY:8},this.storage.clear(),this.scheduleUpdate()}scheduleUpdate(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=requestAnimationFrame(()=>this.update())}bind(){this.bound||(window.addEventListener("resize",this.handleUpdate),window.addEventListener("scroll",this.handleUpdate,!0),this.bound=!0,this.handleUpdate())}attachDragHandle(t){this.dragHandle!==t&&(this.detachDragHandle(),this.dragHandle=t,t.addEventListener("pointerdown",this.handlePointerDown),t.addEventListener("keydown",this.handleKeyDown))}detachDragHandle(){this.dragHandle&&(this.dragHandle.removeEventListener("pointerdown",this.handlePointerDown),this.dragHandle.removeEventListener("keydown",this.handleKeyDown),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp),this.dragHandle=void 0,this.dragState=void 0,this.surface.classList.remove(co))}onPointerDown(t){if(0===t.button&&this.dragHandle){t.preventDefault(),this.dragState={pointerId:t.pointerId,startClientX:t.clientX,startClientY:t.clientY,startOffsetX:this.renderedOffset.offsetX,startOffsetY:this.renderedOffset.offsetY},this.surface.classList.add(co),this.dragHandle.addEventListener("pointermove",this.handlePointerMove),this.dragHandle.addEventListener("pointerup",this.handlePointerUp),this.dragHandle.addEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.setPointerCapture?.(t.pointerId)}catch{}}}onPointerMove(t){this.dragState&&t.pointerId===this.dragState.pointerId&&(t.preventDefault(),this.setPosition({offsetX:this.dragState.startOffsetX+t.clientX-this.dragState.startClientX,offsetY:this.dragState.startOffsetY+t.clientY-this.dragState.startClientY},{persist:!1}))}onPointerUp(t){if(this.dragState&&t.pointerId===this.dragState.pointerId&&this.dragHandle){t.preventDefault(),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.hasPointerCapture?.(t.pointerId)&&this.dragHandle.releasePointerCapture?.(t.pointerId)}catch{}this.surface.classList.remove(co),this.dragState=void 0,"custom"===this.position.mode&&this.storage.save(this.position.offsetX,this.position.offsetY)}}onKeyDown(t){const e=t.shiftKey?32:8,i=this.renderedOffset;switch(t.key){case"ArrowUp":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY-e});break;case"ArrowDown":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY+e});break;case"ArrowLeft":t.preventDefault(),this.setPosition({offsetX:i.offsetX-e,offsetY:i.offsetY});break;case"ArrowRight":t.preventDefault(),this.setPosition({offsetX:i.offsetX+e,offsetY:i.offsetY});break;case"Home":t.preventDefault(),this.resetPosition()}}update(){if(this.animationFrameId=null,"none"===this.host.style.display)return;const t=this.modifier.canvas.getBoundingClientRect(),e=this.clampToViewport(t,this.position.offsetX,this.position.offsetY);this.host.style.top=`${t.top+window.scrollY+e.offsetY}px`,this.host.style.left=`${t.left+window.scrollX+e.offsetX}px`,this.renderedOffset=e}clampToViewport(t,e,i){const r=this.surface.getBoundingClientRect(),n=r.width||this.host.getBoundingClientRect().width||0,o=r.height||this.host.getBoundingClientRect().height||0,s=Math.max(8,window.innerWidth-n-8),a=Math.max(8,window.innerHeight-o-8),h=this.clamp(t.left+e,8,s),c=this.clamp(t.top+i,8,a);return{offsetX:h-t.left,offsetY:c-t.top}}clamp(t,e,i){return Math.min(Math.max(t,e),i)}dispose(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1),this.detachDragHandle()}},Do=class extends ko{capabilities;bi;yi=/* @__PURE__ */new Set;constructor(t,e){super(),this.bi=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}gi(t){return this.yi.add(t),t}hi(){for(const t of this.yi)t.unmount()}ci(){for(const t of this.yi)t.destroy();this.yi.clear()}},Uo=class extends ko{props;checkbox;labelElement;handleChange=()=>{this.props.defaultChecked=this.checkbox.checked};constructor(t){super(),this.props=t}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add("textmode-export-overlay__checkbox"),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=Boolean(this.props.defaultChecked),this.checkbox.addEventListener("change",this.handleChange);const t=document.createElement("span");return t.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(t),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(t){this.checkbox.checked=t}hi(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,t.id&&(this.checkbox.id=t.id,this.labelElement.htmlFor=t.id),this.checkbox.checked=Boolean(t.defaultChecked),this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=t.label)}},Ro=class extends ko{props;input;handleInput=()=>{this.props.defaultValue=this.input.value};constructor(t){super(),this.props=t}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(bo),this.props.id&&(this.input.id=this.props.id),void 0!==this.props.maxLength&&(this.input.maxLength=this.props.maxLength),void 0!==this.props.defaultValue&&(this.input.value=this.props.defaultValue),this.input.addEventListener("input",this.handleInput),this.input}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t}hi(){this.input.removeEventListener("input",this.handleInput)}onUpdate(t){this.props=t,t.id&&(this.input.id=t.id),void 0!==t.maxLength&&(this.input.maxLength=t.maxLength),void 0!==t.defaultValue&&(this.input.value=t.defaultValue)}},No=class extends ko{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new Mo({label:"layer",labelFor:t.id,variant:"full"}),this.select=new _o({id:t.id,options:[],defaultValue:t.provider.getDefaultId()})}render(){const t=document.createElement("div");return this.field.mount(t),this.refresh(),this.select.mount(this.field.root),t}get layer(){const t=this.provider.getLayerById(this.select.value);if(t)return t;const e=this.provider.getDefaultId();return this.select.value=e,this.provider.getLayerById(e)}setDisabled(t){this.select.selectElement.disabled=t}refresh(){const t=this.provider.getOptions(),e=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),i=t.some(t=>t.id===e)?e:this.provider.getDefaultId();this.select.update({options:t.map(t=>({value:t.id,label:t.label})),defaultValue:i}),this.select.value=i}hi(){this.select.unmount(),this.field.unmount()}ci(){this.select.destroy(),this.field.destroy()}},zo=class extends Do{layerTarget;trailingSpaces=this.gi(new Uo({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.gi(new Ro({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.gi(new No({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new Mo({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return e.mount(t),this.emptyCharacter.mount(e.root),t}getOptions(){const t=this.bi.defaultOptions,e=this.emptyCharacter.value||t.emptyCharacter;return{layer:this.layerTarget?.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:e}}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.bi.defaultOptions;this.trailingSpaces.checked=t.preserveTrailingSpaces??!1,this.emptyCharacter.value=t.emptyCharacter??" "}},jo=class extends Do{layerTarget;layerTargetContainer;target=this.gi(new _o({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.gi(new Uo({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.gi(new Uo({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.gi(new _o({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.gi(new No({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Mo({label:"target",labelFor:"textmode-export-json-target",variant:"full"});e.mount(t),this.target.mount(e.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),t.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(t),this.includeMetadata.mount(t);const i=new Mo({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return i.mount(t),this.colorMode.mount(i.root),this.updateLayerTargetVisibility(),t}getOptions(){const t=this.target.value;return{target:t,layer:"selected"===t?this.layerTarget?.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.bi.defaultOptions;this.target.value=t.target??"selected",this.prettyPrint.checked="number"==typeof t.pretty?t.pretty>0:t.pretty??!0,this.includeMetadata.checked=t.includeMetadata??!0,this.colorMode.value=t.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){const t="selected"===this.target.value;this.layerTargetContainer&&(this.layerTargetContainer.style.display=t?"":"none"),this.layerTarget?.setDisabled(!t)}},Lo="textmode-export-number-input",Ho=`${Lo}__field`,Go=`${Lo}__controls`,qo=`${Lo}__control`,Wo=`${Lo}__display`,Xo=`${Wo}--visible`,Yo=t=>{const e=document.createElement("button");return e.type="button",e.className=qo,e.textContent=t>0?"▲":"▼",e},Qo=class extends ko{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=/* @__PURE__ */new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=Lo,this.input=document.createElement("input"),this.input.type="number",this.input.value=this.props.defaultValue,Object.assign(this.input,this.props.attributes),this.input.className=Ho,this.display=document.createElement("div"),this.display.className=Wo;const e=document.createElement("div");return e.className=Go,this.incrementButton=Yo(1),this.decrementButton=Yo(-1),e.appendChild(this.incrementButton),e.appendChild(this.decrementButton),t.appendChild(this.input),t.appendChild(this.display),t.appendChild(e),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(t),this.updateDisplay(),t}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t,this.updateDisplay()}refresh(){this.updateDisplay()}ci(){this.clearHoldTimers(),this.disabledObserver?.disconnect()}bindStepControls(){const t=t=>()=>{if(this.input.disabled)return;const e=this.input.value,i=this.input.getAttribute("step");if(i&&"any"!==i)t>0?this.input.stepUp():this.input.stepDown();else{const e=t>0?1:-1,i=Number.parseFloat(this.input.value||"0"),r=Number.isFinite(i)?i+e:e;this.input.value=String(r)}var r;this.input.value!==e&&((r=this.input).dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},e=t(1),i=t(-1),r=(t,e)=>i=>{if(this.suppressClickAfterPointer.get(t))return this.suppressClickAfterPointer.set(t,!1),void i.preventDefault();e()};this.incrementButton.addEventListener("click",r(this.incrementButton,e)),this.decrementButton.addEventListener("click",r(this.decrementButton,i))}bindHoldBehavior(){const t=(t,e)=>{const i=e>0?()=>this.incrementButton.click():()=>this.decrementButton.click();t.addEventListener("pointerdown",e=>{if(0===e.button){e.preventDefault(),this.suppressClickAfterPointer.set(t,!0),this.activePointerId=e.pointerId;try{t.setPointerCapture(e.pointerId)}catch{}i(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(i,80)},380)}});const r=()=>{if(void 0!==this.activePointerId){try{t.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),r()};t.addEventListener("pointerup",n),t.addEventListener("pointerleave",n),t.addEventListener("pointercancel",n)};t(this.incrementButton,1),t(this.decrementButton,-1)}bindInputListeners(){const t=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",t),this.input.addEventListener("change",t)}observeDisabledState(t){const e=()=>{const e=this.input.disabled;this.incrementButton.disabled=e,this.decrementButton.disabled=e,t.classList.toggle("is-disabled",e),e?(this.display.classList.remove(Xo),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};"undefined"!=typeof MutationObserver&&(this.disabledObserver=new MutationObserver(e),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),e()}updateDisplay(){const t=this.props.formatDisplay;if(!t)return this.display.textContent="",this.display.classList.remove(Xo),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const e=this.input.value,i=Number.parseFloat(e),r=t(Number.isFinite(i)?i:NaN,e,this.input);r?(this.display.textContent=r,this.display.classList.add(Xo),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(Xo),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){void 0!==this.holdTimeoutId&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),void 0!==this.holdIntervalId&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}},Jo=class extends ko{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?oo:void 0,"stackDense"===this.variant?so:void 0,"stackCompact"===this.variant?ao:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?ho:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Ko=class extends Do{formatSelect=this.gi(new _o({id:"textmode-export-image-format",options:[{value:"png",label:"PNG (.png)"},{value:"jpg",label:"JPG (.jpg)"},{value:"webp",label:"WEBP (.webp)"}],defaultValue:"png"}));scaleInput=this.gi(new Qo({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Mo({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return r.mount(e.root),this.scaleInput.mount(r.root),this.scaleInput.inputElement.id="textmode-export-image-scale",t}getOptions(){const t=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(t)?t:this.bi.defaultOptions?.scale??1}}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const t=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0}applyDefaults(){const t=this.bi.defaultOptions;this.formatSelect.value=t.format??"png",this.scaleInput.value=String(t.scale??1)}},Zo=class extends Do{layerTarget;includeBackground=this.gi(new Uo({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.gi(new _o({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.gi(new Qo({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.gi(new No({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new Jo("row");e.mount(t);const i=new Mo({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new Mo({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return r.mount(e.root),this.strokeWidth.mount(r.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),t}getOptions(){return{layer:this.layerTarget?.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const t=Number.parseFloat(this.strokeWidth.value);return"stroke"!==this.drawMode.value||Number.isFinite(t)&&t>=0}refreshLayerTargets(){this.layerTarget?.refresh()}updateStrokeControls(){const t="stroke"===this.drawMode.value;this.strokeWidth.inputElement.disabled=!t,this.strokeWidth.refresh()}applyDefaults(){const t=this.bi.defaultOptions;this.includeBackground.checked=t.includeBackgroundRectangles??!0,this.drawMode.value=t.drawMode??"fill",this.strokeWidth.value=String(t.strokeWidth??1),this.strokeWidth.refresh()}},ts={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},es=class extends ko{props;container;messageElement;constructor(t){super(),this.props=t}render(){this.container=document.createElement("div"),this.container.classList.add("textmode-export-overlay__status"),"gif"===this.props.context?this.container.classList.add("textmode-export-overlay__status--gif"):"video"===this.props.context&&this.container.classList.add("textmode-export-overlay__status--video");const t=document.createElement("span");return t.classList.add("textmode-export-overlay__status-title"),t.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add("textmode-export-overlay__status-value"),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(t),this.container.appendChild(this.messageElement),this.container}setMessage(t,e="neutral"){this.messageElement.textContent=t,this.applyVariant(e)}onUpdate(t){this.props=t,this.setMessage(t.message,t.variant??"neutral")}applyVariant(t){this.messageElement.classList.remove(...Object.values(ts)),this.messageElement.classList.add(ts[t])}},is=class extends Do{frameCountInput=this.gi(new Qo({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.gi(new Qo({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.gi(new Qo({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.gi(new Qo({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(t,e)=>Number.isFinite(t)?0===t?"∞":null:""===e.trim()?null:e}));status=this.gi(new es({title:"status",message:"ready to record",variant:"neutral",context:"gif"}));recordingState="idle";constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});i.mount(e.root),this.frameCountInput.mount(i.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const r=new Mo({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});r.mount(e.root),this.frameRateInput.mount(r.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const n=new Jo("row");n.mount(t);const o=new Mo({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});o.mount(n.root),this.scaleInput.mount(o.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const s=new Mo({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return s.mount(n.root),this.repeatInput.mount(s.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(t),t}getOptions(){const t=this.bi.defaultOptions;return{frameCount:this.safeParseInt(this.frameCountInput.value,t.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,t.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,t.scale??1),repeat:this.safeParseInt(this.repeatInput.value,t.repeat??0)}}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseInt(this.frameRateInput.value,10),i=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;switch(this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.scaleInput.inputElement.disabled=i,this.repeatInput.inputElement.disabled=i,t){case"recording":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`recording ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`encoding ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage(e?.message??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(t){if("recording"!==t.state&&"encoding"!==t.state||!t.totalFrames)"completed"===t.state?this.status.setMessage("GIF saved successfully","active"):"error"===t.state&&this.status.setMessage(t.message??"failed to export GIF","alert");else{const e="recording"===t.state?"recording":"encoding";this.status.setMessage(`${e} ${t.frameIndex??0}/${t.totalFrames}`,"active")}}applyDefaults(){const t=this.bi.defaultOptions;this.frameCountInput.value=String(t.frameCount??300),this.frameRateInput.value=String(t.frameRate??60),this.scaleInput.value=String(t.scale??1),this.repeatInput.value=String(t.repeat??0),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(t,e){const i=Number.parseInt(t,10);return Number.isFinite(i)?i:e}safeParseFloat(t,e){const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}},rs=class extends Do{formatSelect=this.gi(new _o({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));bitrateSelect=this.gi(new _o({id:"textmode-export-video-bitrate",options:[{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"},{value:"ultra",label:"ultra (near-lossless)"}],defaultValue:"medium"}));frameRateInput=this.gi(new Qo({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.gi(new Qo({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));bitrateModeSelect=this.gi(new _o({id:"textmode-export-video-bitrate-mode",options:[{value:"variable",label:"variable"},{value:"constant",label:"constant"}],defaultValue:"variable"}));latencyModeSelect=this.gi(new _o({id:"textmode-export-video-latency-mode",options:[{value:"quality",label:"quality"},{value:"realtime",label:"realtime"}],defaultValue:"quality"}));hardwareAccelerationSelect=this.gi(new _o({id:"textmode-export-video-hardware-acceleration",options:[{value:"no-preference",label:"no preference"},{value:"prefer-hardware",label:"prefer hardware"},{value:"prefer-software",label:"prefer software"}],defaultValue:"no-preference"}));keyFrameIntervalInput=this.gi(new Qo({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.gi(new Uo({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.gi(new es({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.gi(new es({title:"estimate",message:"logical dimensions · duration · size",variant:"neutral",context:"video"}));recordingState="idle";resizeObserver;constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Mo({label:"bitrate preset",labelFor:"textmode-export-video-bitrate",variant:"compact"});r.mount(e.root),this.bitrateSelect.mount(r.root);const n=new Jo("row");n.mount(t);const o=new Mo({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});o.mount(n.root),this.frameCountInput.mount(o.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const s=new Mo({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});s.mount(n.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const a=new Jo("row");a.mount(t);const h=new Mo({label:"bitrate mode",labelFor:"textmode-export-video-bitrate-mode",variant:"compact"});h.mount(a.root),this.bitrateModeSelect.mount(h.root);const c=new Mo({label:"encoder mode",labelFor:"textmode-export-video-latency-mode",variant:"compact"});c.mount(a.root),this.latencyModeSelect.mount(c.root);const l=new Jo("row");l.mount(t);const d=new Mo({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});d.mount(l.root),this.hardwareAccelerationSelect.mount(d.root);const u=new Mo({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return u.mount(l.root),this.keyFrameIntervalInput.mount(u.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(t),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.bitrateSelect.selectElement.addEventListener("change",this.handleBitrateChange),this.frameCountInput.inputElement.addEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.addEventListener("input",this.handleEstimateChange),this.formatSelect.selectElement.addEventListener("change",this.handleEstimateChange),this.estimate.mount(t),this.status.mount(t),this.syncOutputEstimate(),this.bi.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.bi.videoDimensionsTarget)),t}getOptions(){const t=this.bi.defaultOptions,e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),r=Number.parseFloat(this.keyFrameIntervalInput.value),n=this.formatSelect.value,o={format:n,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(r)?r:t.keyFrameInterval??2,frameCount:Number.isFinite(e)?e:t.frameCount??480,frameRate:Number.isFinite(i)?i:t.frameRate??60};return"webm"===n&&(o.transparent=this.transparencyInput.checked),o}setDefaults(t){Object.assign(this.bi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.syncReadyStatus()}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseFloat(this.frameRateInput.value),i=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(t)&&t>=1&&Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;this.formatSelect.selectElement.disabled=i,this.bitrateSelect.selectElement.disabled=i,this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.bitrateModeSelect.selectElement.disabled=i,this.latencyModeSelect.selectElement.disabled=i,this.hardwareAccelerationSelect.selectElement.disabled=i,this.keyFrameIntervalInput.inputElement.disabled=i,this.transparencyInput.inputElement.disabled=i||"webm"!==this.formatSelect.value,this.syncStatus(t,e)}handleProgress(t){this.syncStatus(t.state,t)}syncStatus(t,e){switch(t){case"recording":{const t=e?.frameIndex??0,i=e?.totalFrames??this.resolvePlannedFrameCount();if(i){const e=Math.min(Math.max(0,Math.round(t)),i);this.status.setMessage(`recording ${e}/${i} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(t))} frames`,"active");break}case"encoding":this.status.setMessage("writing"===e?.phase?"writing video to disk":"finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(e?.message?`error: ${e.message}`:"recording failed","alert");break;default:this.syncReadyStatus()}}resolvePlannedFrameCount(){const t=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(t)&&t>0?Math.round(t):void 0}applyDefaults(){const t=this.bi.defaultOptions;this.formatSelect.value=t.format??"mp4",this.bitrateSelect.value=this.resolveBitratePreset(t.bitrate),this.frameCountInput.value=String(t.frameCount??480),this.frameRateInput.value=String(t.frameRate??60),this.bitrateModeSelect.value=t.bitrateMode??"variable",this.latencyModeSelect.value=t.latencyMode??"quality",this.hardwareAccelerationSelect.value=t.hardwareAcceleration??"no-preference",this.keyFrameIntervalInput.value=String(t.keyFrameInterval??2),this.transparencyInput.checked=Boolean(t.transparent),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveBitratePreset(t){return"low"===t||"medium"===t||"high"===t||"ultra"===t?t:"medium"}handleBitrateChange=()=>{this.isRecording()||this.syncReadyStatus(),this.syncOutputEstimate()};handleEstimateChange=()=>this.syncOutputEstimate();syncReadyStatus(){"ultra"===this.bitrateSelect.value?this.status.setMessage("near-lossless; very large files and slower exports","alert"):this.status.setMessage("ready to record","neutral")}handleFormatChange=()=>{this.syncTransparencyAvailability(),this.syncOutputEstimate()};syncOutputEstimate(){if(!this.estimate.isMounted())return;const t=this.bi.videoDimensionsProvider?.(),e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value);if(!t||!Number.isFinite(e)||!Number.isFinite(i)||i<=0)return void this.estimate.setMessage("logical dimensions · duration · size","neutral");const r={format:this.formatSelect.value,frameCount:Math.max(1,Math.round(e)),frameRate:i,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,contentHint:"text",latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.parseFloat(this.keyFrameIntervalInput.value)||2,pixelDensity:1,width:t.width,height:t.height,transparent:"webm"===this.formatSelect.value&&this.transparencyInput.checked,debugLogging:!1};try{const t=Xn(r);this.estimate.setMessage(`${t.width}×${t.height} · ${(t.frameCount/t.frameRate).toFixed(1)}s · ~${this.formatBytes(t.estimatedBytes)}`,"ultra"===this.bitrateSelect.value?"alert":"neutral")}catch{this.estimate.setMessage(`${t.width}×${t.height} · MP4 requires even dimensions`,"alert")}}formatBytes(t){return t>=1e9?`${(t/1e9).toFixed(1)} GB`:`${Math.max(1,Math.round(t/1e6))} MB`}hi(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.bitrateSelect.selectElement.removeEventListener("change",this.handleBitrateChange),this.formatSelect.selectElement.removeEventListener("change",this.handleFormatChange),this.formatSelect.selectElement.removeEventListener("change",this.handleEstimateChange),this.frameCountInput.inputElement.removeEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.removeEventListener("input",this.handleEstimateChange),super.hi()}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const t="webm"===this.formatSelect.value;this.transparencyInput.root.style.display=t?"":"none",this.transparencyInput.inputElement.disabled=!t||this.isRecording(),t||(this.transparencyInput.checked=!1)}};function ns(t){return t.capabilities.recording}var os=Object.freeze({format:"txt",txt:Object.freeze({preserveTrailingSpaces:!1,emptyCharacter:" "}),json:Object.freeze({target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"}),image:Object.freeze({format:"png",scale:1}),svg:Object.freeze({includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1}),gif:Object.freeze({frameCount:300,frameRate:60,scale:1,repeat:0}),video:Object.freeze({format:"mp4",frameCount:480,frameRate:60,bitrate:"medium",bitrateMode:"variable",latencyMode:"quality",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1})});function ss(){return{format:os.format,txt:{...os.txt},json:{...os.json},image:{...os.image},svg:{...os.svg},gif:{...os.gif},video:{...os.video}}}function as(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var hs=class{xi;constructor(){this.xi=ss()}get current(){return this.snapshot()}snapshot(){return{format:(t=this.xi).format,txt:{...t.txt},json:{...t.json},image:{...t.image},svg:{...t.svg},gif:{...t.gif},video:{...t.video}};var t}get(t){return this.xi[t]}merge(t){t.format&&(this.xi.format=t.format),t.txt&&Object.assign(this.xi.txt,t.txt),t.json&&Object.assign(this.xi.json,t.json),t.image&&Object.assign(this.xi.image,t.image),t.svg&&Object.assign(this.xi.svg,t.svg),t.gif&&Object.assign(this.xi.gif,t.gif),t.video&&Object.assign(this.xi.video,t.video)}reset(t){const e=ss();if(!t)return this.xi.format=e.format,as(this.xi.txt,e.txt),as(this.xi.json,e.json),as(this.xi.image,e.image),as(this.xi.svg,e.svg),as(this.xi.gif,e.gif),void as(this.xi.video,e.video);switch(t){case"format":this.xi.format=e.format;break;case"txt":as(this.xi.txt,e.txt);break;case"json":as(this.xi.json,e.json);break;case"image":as(this.xi.image,e.image);break;case"svg":as(this.xi.svg,e.svg);break;case"gif":as(this.xi.gif,e.gif);break;case"video":as(this.xi.video,e.video)}}},cs=class{_;Ei;wi;ki;Ti;Mi;_i;Ci=/* @__PURE__ */new Map;Ai=[];Si;Bi;Pi;Ii;$i;Fi;Vi=new To;Oi=new Mo({label:"export format",labelFor:"textmode-export-format",variant:"full"});Di=new _o({id:"textmode-export-format",options:[]});Ui=new Co({label:"download file",fullWidth:!0,variant:"primary"});Ri=new Co({label:"copy to clipboard",fullWidth:!0,variant:"primary"});Ni;zi;ji=()=>{this.Li(this.Di.value)};Hi=()=>{this.Gi().catch(t=>{console.error("[textmode-export] Export failed",t)})};qi=()=>{this.Wi().catch(t=>{console.error("[textmode-export] Copy failed",t)})};constructor(t,e,i,r){this._=t,this.Ei=i;const n=this.Xi(i.current.format,r);this.wi=new So((t=>({format:t,isBusy:!1}))(n)),this.ki=new Ao,this.Ti=new $o(e,this.ki),this.Mi=new Po(e),this._i=r,this.Ni=n,this.Yi(),this.Qi()}$mount(){this.Ji(),this.Ki(),this.Fi=new Oo(this._,this.Si,this.Pi),this.Fi.attachDragHandle(this.Vi.dragHandleElement),this.Fi.bind(),this.Zi(this.Ni)}show(){this.Si&&(this.refreshLayerTargets(),this.Si.style.display="",this.Fi?.scheduleUpdate())}hide(){this.Si&&(this.Si.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this.Si&&"none"!==this.Si.style.display}refreshLayerTargets(){this.zi&&this.zi.blade.capabilities.layerTarget&&this.zi.blade.refreshLayerTargets()}resetPosition(){this.Fi.resetPosition()}getPosition(){return this.Fi.getPosition()}setPosition(t){this.Fi.setPosition(t)}setDefaults(t){t.format&&this.tr(t.format),this.Ei.merge(t),this.er(this.ir(t)),t.format&&this.Li(t.format)}getDefaults(){return this.Ei.current}resetDefaults(t){this.Ei.reset(t),"format"!==t?(this.er(t?[t]:void 0),t||this.Li(this.Ei.current.format)):this.Li(this.Ei.current.format)}$dispose(){this.Di.isMounted()&&this.Di.selectElement.removeEventListener("change",this.ji),this.Ui.isMounted()&&this.Ui.buttonElement.removeEventListener("click",this.Hi),this.Ri.isMounted()&&this.Ri.buttonElement.removeEventListener("click",this.qi);for(const t of this.Ai)t();this.Ai.length=0,this.ki.$clear();for(const t of this.Ci.values())t.blade.destroy();this.Ci.clear(),this.zi=void 0,this.Si?.isConnected&&this.Si.remove(),this.Fi?.dispose()}er(t){const e=new Set(t??this.Ci.keys());for(const[i,r]of this.Ci)e.has(i)&&(r.blade.isMounted()?(r.blade.reset(),r.needsReset=!1):r.needsReset=!0)}Yi(){for(const t of this._i){const e=t.createBlade();this.Ci.set(t.format,{definition:t,blade:e,initialized:!1,needsReset:!1})}}Xi(t,e){return e.some(e=>e.format===t)?t:e[0]?.format??t}ir(t){return this._i.map(t=>t.format).filter(e=>void 0!==t[e])}tr(t){if(!this.Ci.has(t))throw new Error(`Unknown export format: ${t}`)}Ji(){this.Si=document.createElement("div"),this.Si.dataset.plugin="textmode-export-overlay-host",this.Si.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this.Bi=this.Si.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent="@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg:#141414cc;--overlay-surface:#282828e6;--overlay-border:#ffffff24;--overlay-border-strong:#fff3;--overlay-border-focus:#a0a0a099;--overlay-focus-shadow:0 0 0 1px #8c8c8c47;--overlay-text:#fff;--overlay-muted:#c8c8c8bd;--overlay-radius:.75rem;--overlay-stack-gap:.55rem;gap:var(--overlay-stack-gap);background:var(--overlay-bg);min-width:236px;max-width:236px;color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:auto;z-index:2147483647;flex-direction:column;padding:.65rem .8rem;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;display:flex;position:absolute;top:0;left:0;box-shadow:0 12px 28px #0000004d}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__header-title-row{justify-content:space-between;align-items:center;gap:.4rem;display:flex}.textmode-export-overlay__header-identity{align-items:center;gap:.35rem;min-width:0;display:inline-flex}.textmode-export-overlay__header-links{flex:none;align-items:center;gap:.3rem;display:inline-flex}.textmode-export-overlay__grab-handle{color:#d7d7d7b8;cursor:grab;touch-action:none;background:0 0;border:1px solid #0000;border-radius:.45rem;flex:none;justify-content:center;align-items:center;width:1.45rem;height:1.45rem;padding:0;line-height:0;transition:background .18s,color .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__grab-handle:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__grab-handle:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay--dragging,.textmode-export-overlay--dragging .textmode-export-overlay__grab-handle{cursor:grabbing}.textmode-export-overlay__support-link{color:#d7d7d7d1;background:0 0;border:1px solid #0000;border-radius:.45rem;justify-content:center;align-items:center;padding:.2rem;line-height:0;text-decoration:none;transition:background .18s,color .18s,transform .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{width:1rem;height:1rem;display:block}.textmode-export-overlay__stack{gap:var(--overlay-stack-gap);flex-direction:column;display:flex}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__title{white-space:nowrap;font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{background:#ffffff29;width:100%;height:1px;margin-top:.25rem}.textmode-export-overlay__label{opacity:.9;font-weight:500}.textmode-export-overlay__checkbox{align-items:center;gap:.5rem;display:flex}.textmode-export-overlay__checkbox input[type=checkbox]{accent-color:#646464e6;width:1rem;height:1rem}.textmode-export-overlay__row{flex-wrap:wrap;align-items:flex-start;gap:.6rem;width:100%;display:flex}.textmode-export-overlay__field{flex-direction:column;flex:120px;gap:.3rem;min-width:120px;display:flex}.textmode-export-overlay__field--compact{flex:100px;min-width:100px}.textmode-export-overlay__field--dense{flex:90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{flex:100%;width:100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);width:100%;color:var(--overlay-text);font:inherit;border-radius:.4rem;padding:.35rem .5rem;line-height:1.35;transition:border-color .18s,box-shadow .18s,background .18s}.textmode-export-overlay select.textmode-export-overlay__input{appearance:none;background-image:url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(200, 200, 200, 0.74)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\");background-position:right .5rem center;background-repeat:no-repeat;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb;outline:none}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{opacity:.7;font-size:.75rem;display:block}.textmode-export-overlay__button{cursor:pointer;border:none;border-radius:.45rem;justify-content:center;align-items:center;gap:.35rem;padding:.45rem .7rem;font-weight:600;transition:background .2s,transform .2s,box-shadow .2s;display:inline-flex}.textmode-export-overlay__button--primary{color:#fff;background:#505050}.textmode-export-overlay__button--secondary{color:#fff;background:#606060}.textmode-export-overlay__button--full{width:100%}.textmode-export-overlay__button:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 7px 18px #00000073}.textmode-export-overlay__button--primary:hover:not(:disabled){background:#404040}.textmode-export-overlay__button--secondary:hover:not(:disabled){background:#4a4a4a}.textmode-export-overlay__button:disabled{cursor:default;opacity:.55;box-shadow:none;transform:none}.textmode-export-overlay__status{background:#4646462e;border:1px solid #6e6e6e38;border-radius:.45rem;flex-direction:column;gap:.25rem;padding:.45rem .55rem;display:flex}.textmode-export-overlay__status--gif{background:#5050501f;border-color:#78787840}.textmode-export-overlay__status--video{background:#4646461f;border-color:#6e6e6e40}.textmode-export-overlay__status-title{opacity:.85;text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;font-weight:600}.textmode-export-overlay__status-value{color:#dedede;font-size:.82rem;transition:color .18s}.textmode-export-overlay__status-value--neutral{color:#cfcfcf}.textmode-export-overlay__status-value--active{color:#f5f5f5}.textmode-export-overlay__status-value--alert{color:#b8b8b8}.textmode-export-number-input,.textmode-export-overlay .textmode-export-number-input{background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;align-items:stretch;width:100%;transition:border-color .18s,box-shadow .18s,background .18s;display:flex;position:relative;overflow:hidden}.textmode-export-number-input:focus-within{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-number-input.is-disabled{opacity:.55}.textmode-export-number-input__field{min-width:0;color:var(--overlay-text);font:inherit;appearance:textfield;background:0 0;border:none;flex:auto;padding:.35rem .5rem}.textmode-export-number-input__field::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field:focus{outline:none}.textmode-export-number-input__controls{border-left:1px solid #ffffff1f;flex-direction:column;min-width:1.6rem;display:flex}.textmode-export-number-input__control{color:#d0d0d0;cursor:pointer;background:#32323299;border:none;flex:1;justify-content:center;align-items:center;width:100%;padding:0;font-size:.68rem;line-height:1;transition:background .15s,color .15s;display:flex}.textmode-export-number-input__control:hover:not(:disabled){color:#fff;background:#5a5a5ad9}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;color:#c8c8c866;background:#28282880}.textmode-export-number-input:focus-within .textmode-export-number-input__control{color:#e8e8e8;background:#3c3c3cbf}.textmode-export-number-input__display{pointer-events:none;color:#f8fafc;opacity:0;align-items:center;padding:.4rem .55rem;transition:opacity .14s;display:flex;position:absolute;inset:0}.textmode-export-number-input__display--visible{opacity:1}}",this.Bi.appendChild(t),this.Pi=document.createElement("div"),this.Pi.dataset.plugin="textmode-export-overlay",this.Pi.classList.add("textmode-export-overlay",oo),this.Bi.appendChild(this.Pi),document.body.appendChild(this.Si)}Ki(){this.Vi.mount(this.Pi);const t=document.createElement("div");t.classList.add(ho),this.Pi.appendChild(t),this.Oi.mount(t),this.rr(),this.Di.mount(this.Oi.root),this.Di.selectElement.addEventListener("change",this.ji),this.Ii=document.createElement("div"),this.Ii.classList.add(oo,ao),this.Pi.appendChild(this.Ii),this.Ui.mount(this.Pi),this.Ui.buttonElement.addEventListener("click",this.Hi),this.$i=document.createElement("div"),this.$i.classList.add(oo,so),this.Pi.appendChild(this.$i),this.Ri.mount(this.$i),this.Ri.buttonElement.dataset.defaultLabel="copy to clipboard",this.Ri.buttonElement.addEventListener("click",this.qi)}rr(){const t=this._i.map(t=>({value:t.format,label:t.label}));this.Di.update({options:t,defaultValue:this.Ni})}Qi(){this.Ai.push(this.ki.$on("export:request",({format:t})=>{t===this.Ni&&(this.wi.$set({isBusy:!0,error:void 0}),this.nr())}),this.ki.$on("export:success",({format:t})=>{if(t===this.Ni){const e={isBusy:!1};"gif"===t&&(e.gifProgress=void 0),"video"===t&&(e.videoProgress=void 0),this.wi.$set(e),this.nr()}}),this.ki.$on("export:error",({format:t,error:e})=>{t===this.Ni&&(this.wi.$set({isBusy:!1,error:e}),this.nr())}),this.ki.$on("export:progress",({format:t,progress:e})=>{if(e){if("gif"===t){const t=e;this.wi.$set({gifProgress:t}),"gif"===this.zi?.definition.format&&ns(this.zi.blade)&&this.zi.blade.handleProgress(t)}else if("video"===t){const t=e;this.wi.$set({videoProgress:t}),"video"===this.zi?.definition.format&&ns(this.zi.blade)&&this.zi.blade.handleProgress(t)}this.nr()}}))}Li(t){this.Ni=t,this.wi.$set({format:t}),this.Zi(t),this.ki.$emit("format:change",{format:t})}Zi(t){const e=this.Ci.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this.zi&&this.zi.blade.unmount(),this.Ii.innerHTML="",e.blade.mount(this.Ii),e.initialized&&!e.needsReset||(e.blade.reset(),e.initialized=!0,e.needsReset=!1),this.zi=e,this.Di.value=t,this.refreshLayerTargets(),this.sr(),this.nr(),this.Fi?.scheduleUpdate()}sr(){const t=this.zi?.definition.supportsClipboard??!1;this.$i.style.display=t?"flex":"none",this.Ri.setDisabled(!t)}async Gi(){if(!this.zi)return;const t=this.zi.definition.format,e=this.zi.blade.getOptions();if(this.zi.blade.validate()){if(ns(this.zi.blade)){const r=this.zi.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this.Ti.$requestExport(t,e,{onGIFProgress:t=>{r.setRecordingState(t.state,t)},onVideoProgress:t=>{r.setRecordingState(t.state,t)}})}catch(i){throw r.setRecordingState("error"),i}return void window.setTimeout(()=>{r.setRecordingState("idle"),this.nr()},1600)}this.Ui.setDisabled(!0),this.Ui.setLabel("exporting…");try{await this.Ti.$requestExport(t,e)}finally{this.Ui.setDisabled(!1),this.Ui.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async Wi(){if(!this.zi||!this.zi.definition.supportsClipboard)return;const t=this.zi.definition.format,e=this.zi.blade.getOptions(),i=this.Ri.buttonElement.dataset.defaultLabel??"copy to clipboard";this.Ri.setDisabled(!0),this.Ri.setLabel("copying…");try{switch(t){case"txt":await this.Mi.$copy("txt",e);break;case"json":await this.Mi.$copy("json",e);break;case"svg":await this.Mi.$copy("svg",e);break;case"image":await this.Mi.$copy("image",e);break;default:return}this.Ri.setLabel("copied!")}catch(r){console.error("[textmode-export] Failed to copy to clipboard",r),this.Ri.setLabel("copy failed!")}finally{window.setTimeout(()=>{this.Ri.setLabel(i),this.Ri.setDisabled(!1)},1200)}}nr(){if(!this.zi)return;const t=this.zi.definition.format;if(ns(this.zi.blade)){const e=this.zi.blade,i="gif"===t?this.wi.snapshot.gifProgress:this.wi.snapshot.videoProgress;if(e.isRecording())if(this.Ui.setDisabled(!0),i?.totalFrames){const e=i.frameIndex??0,r="encoding"===i.state?"encoding":"recording";this.Ui.setLabel("gif"===t?`${r} ${e}/${i.totalFrames}`:`recording ${e}/${i.totalFrames} frames`)}else this.Ui.setLabel("encoding"===i?.state?"encoding…":"recording…");else this.Ui.setDisabled(!1),this.Ui.setLabel("start recording");return}const e=this.wi.snapshot.isBusy;this.Ui.setDisabled(e),this.Ui.setLabel(e?"exporting…":"download file")}};var ls=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob"],ds=class{api;C;ar=/* @__PURE__ */new Set;hr;cr;Y=!1;constructor(t,e){this.C=e;const i={saveCanvas:async(e={})=>(this.lr(),(new w).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.lr(),(new w).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.lr(),(new w).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.lr(),(new p).$saveSVG(t,e)},saveStrings:(e={})=>{this.lr(),(new b).$saveTXT(t,e)},toSVG:(e={})=>(this.lr(),(new p).$generateSVG(t,e)),toString:(e={})=>(this.lr(),(new b).$generateTXT(t,e)),toJSON:(e={})=>(this.lr(),(new no).$generateJSONData(t,e)),toJSONString:(e={})=>(this.lr(),(new no).$generateJSONString(t,e)),saveJSON:(e={})=>{this.lr(),(new no).$saveJSON(t,e)},saveGIF:(e={})=>this.dr(e.signal,i=>new A(t,t=>this.C(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.dr(e.signal,i=>new A(t,t=>this.C(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.dr(e.signal,i=>new Zn(t,t=>this.C(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.dr(e.signal,i=>new Zn(t,t=>this.C(t)).$generateVideoBlob({...e,signal:i})),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new hs,n=new cs(t,e,r,function(t,e=(()=>{const t=ss();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new zo({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new jo({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Ko({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Zo({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new is({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new rs({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>h(t),getLayerById:e=>h(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.C(()=>{!this.Y&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.hr=r,this.cr=n,i.exportOverlay=this.ur()}dispose(){if(!this.Y){this.Y=!0;for(const t of this.ar)t.abort();this.ar.clear(),this.cr(),this.hr.$dispose()}}ur(){return{show:()=>{this.lr(),this.hr.show()},hide:()=>{this.lr(),this.hr.hide()},toggle:()=>{this.lr(),this.hr.toggle()},isVisible:()=>(this.lr(),this.hr.isVisible()),resetPosition:()=>{this.lr(),this.hr.resetPosition()},getPosition:()=>(this.lr(),this.hr.getPosition()),setPosition:t=>{this.lr(),this.hr.setPosition(t)},setDefaults:t=>{this.lr(),this.hr.setDefaults(t)},getDefaults:()=>(this.lr(),this.hr.getDefaults()),resetDefaults:t=>{this.lr(),this.hr.resetDefaults(t)}}}dr(t,e){this.lr();const i=new AbortController,r=new AbortController,n=()=>r.abort(),o=()=>r.abort();return t?.addEventListener("abort",n,{once:!0}),i.signal.addEventListener("abort",o,{once:!0}),t?.aborted&&r.abort(),this.ar.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.ar.delete(i)})}lr(){if(this.Y)throw new Error("Textmode export plugin has been disposed.")}},us={name:"textmode.export.js",install(t,e){const i=new ds(t,t=>e.on("postDraw",t));try{for(const t of ls)e.defineExtension("textmodifier",t,{value:i.api[t]});e.defineExtension("textmodifier","exportOverlay",{get:()=>i.api.exportOverlay})}catch(r){throw i.dispose(),r}return()=>i.dispose()}};"undefined"!=typeof window&&(window.ExportPlugin=us);export{us as ExportPlugin};
|
|
1
|
+
import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=class{$downloadFile(t,e){try{const i=this.t(e),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=i,n.style.display="none",n.rel="noopener",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}catch(i){console.error("[textmode-export] Failed to download file:",i)}}t(t){if(!t)return this.i();const e=t.trim();return e&&e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)||this.i()}i(){return`textmode-export-${/* @__PURE__ */(new Date).toISOString().slice(0,19).replace(/:/g,"-")}`}},n=/* @__PURE__ */new WeakMap;function o(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function s(t,e){let i=n.get(t);if(!i){i=/* @__PURE__ */new Map;for(const e of t.characters)i.set(o(e.color),e);n.set(t,i)}return i.get(e)}function a(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function h(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:a(t,e),layer:e}))}function c(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:a(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}function l(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var d=class extends i{o(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=l(t.primaryColorPixels,s),c=l(t.secondaryColorPixels,s);const d=this.$extractCellTransform(t.characterPixels,s);if(d.isInverted){const t=h;h=c,c=t}const u=this.o(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:d,position:u}),r++}return i}},u=class{h(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.l(e,i,r,o)}}l(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.h(h,a,l,d,s).toSVG()||null}},f=class{u;constructor(){this.u=new u}$generateSVGHeader(t){const{width:e,height:i}=t;return`<?xml version="1.0" encoding="UTF-8"?><svg width="${e}" height="${i}" viewBox="0 0 ${e} ${i}" xmlns="http://www.w3.org/2000/svg"><title>textmode.js sketch</title>`}$generateSVGFooter(){return"</g></svg>"}p(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}m(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}v(t,e,i,r){const n=s(i,t.encodedGlyphSlot);if(!n)return"";const o=this.u.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:a,g:h,b:c,a:l}=t.primaryColor,d=`rgba(${a},${h},${c},${l/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.m(t,e,r);o&&n.push(o);const s=this.v(t,e,i,r);if(s){const i=this.p(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},p=class{k(t){return{includeBackgroundRectangles:t.includeBackgroundRectangles??!0,drawMode:t.drawMode??"fill",strokeWidth:t.strokeWidth??1,filename:t.filename,layer:t.layer}}$generateSVG(t,e={}){const i=new d,r=new f,n=this.k(e),o=c(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new r).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}},m={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},w=class{k(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}T(t){if(!(t.format in m))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(/* @__PURE__ */new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},m[e.format])})}async $saveImage(t,e={}){const i=this.k(e);this.T(i);const n=await this.$toImageBlob(t,e);(new r).$downloadFile(n,i.filename)}async $toImageBlob(t,e={}){const i=this.k(e);return this.T(i),this.$generateImageBlob(t,i)}async $copyImageToClipboard(t,e={}){if("undefined"==typeof navigator||!navigator.clipboard||"function"!=typeof navigator.clipboard.write)throw new Error("Clipboard API is not available in this environment");const i=this.k(e);this.T(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[m[i.format]]:r});await navigator.clipboard.write([n])}},b=class{k(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}M(t,e){const r=new i,n=c(t,e.layer),o=r.$extractFramebufferData(n.drawFramebuffer),a=[];let h=0;for(let i=0;i<n.grid.rows;i++){let t="";for(let i=0;i<n.grid.cols;i++){const i=4*h,a=r.$getEncodedCharacterValue(o.characterPixels,i);t+=s(n.font,a)?.character||e.emptyCharacter,h++}e.preserveTrailingSpaces||(t=t.trimEnd()),a.push(t)}return a.join("\n")}$generateTXT(t,e={}){return this.M(t,this.k(e))}$saveTXT(t,e={}){const i=this.k(e),n=this.M(t,i),o=new Blob([n],{type:"text/plain;charset=utf-8"});(new r).$downloadFile(o,i.filename)}},y=/* @__PURE__ */e(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>_,applyPalette:()=>y,default:()=>P,nearestColor:()=>M,nearestColorIndex:()=>k,nearestColorIndexWithDistance:()=>T,prequantize:()=>b,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,b=m,y=(1<<b)-1;const v=1<<p-1,g=v+1;let x=v+2,E=0,k=i[0],T=0;for(let r=l;r<65536;r*=2)++T;T=8-T,s.writeByte(d),_(v);const M=i.length;for(let r=1;r<M;r++)t:{const t=i[r],e=(t<<12)+k;let n=t<<T^k;if(h[n]===e){k=c[n];break t}const o=0===n?1:l-n;for(;h[n]>=0;)if(n-=o,n<0&&(n+=l),h[n]===e){k=c[n];break t}_(k),k=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=v+2,w=!0,_(v))}return _(k),_(g),s.writeByte(0),s.bytesView();function _(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=b;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>y||w)&&(w?(b=m,y=(1<<b)-1,w=!1):(++b,y=12===b?1<<b:(1<<b)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let b=!1!==i.useSqrt;const y="rgba4444"===r,v=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=v.length,x=g-1,E=new Uint32Array(g+1);for(var k=0,T=0;T<g;++T){const t=v[T];if(null!=t){var M=1/t.cnt;y&&(t.ac*=M),t.rc*=M,t.gc*=M,t.bc*=M,v[k++]=t}}var _,C,A;for(l(e)/k<.022&&(b=!1),T=0;T<k-1;++T)v[T].fw=T+1,v[T+1].bk=T,b&&(v[T].cnt=Math.sqrt(v[T].cnt));for(b&&(v[T].cnt=Math.sqrt(v[T].cnt)),T=0;T<k;++T){d(v,T,!1);var S=v[T].err;for(C=++E[0];C>1&&!(v[_=E[A=C>>1]].err<=S);C=A)E[C]=_;E[C]=T}var B=k-e;for(T=0;T<B;){for(var P;;){var I=E[1];if((P=v[I]).tm>=P.mtm&&v[P.nn].mtm<=P.tm)break;for(P.mtm==x?I=E[1]=E[E[0]--]:(d(v,I,!1),P.tm=T),S=v[I].err,C=1;(A=C+C)<=E[0]&&(A<E[0]&&v[E[A]].err>v[E[A+1]].err&&A++,!(S<=v[_=E[A]].err));C=A)E[C]=_;E[C]=I}var F=v[P.nn],$=P.cnt,V=F.cnt;M=1/($+V),y&&(P.ac=M*($*P.ac+V*F.ac)),P.rc=M*($*P.rc+V*F.rc),P.gc=M*($*P.gc+V*F.gc),P.bc=M*($*P.bc+V*F.bc),P.cnt+=F.cnt,P.mtm=++T,v[F.bk].fw=F.fw,v[F.fw].bk=F.bk,F.mtm=x}let U=[];var O=0;for(T=0;;++O){let t=c(Math.round(v[T].rc),0,255),e=c(Math.round(v[T].gc),0,255),i=c(Math.round(v[T].bc),0,255),r=255;y&&(r=c(Math.round(v[T].ac),0,255),m&&(r=r<=("number"==typeof m?m:127)?0:255),n&&r<=f&&(t=e=i=o,r=0));const s=y?[t,e,i,r]:[t,e,i];if(p(U,s)||U.push(s),0==(T=v[T].fw))break}return U}function p(t,e){for(let i=0;i<t.length;i++){const r=t[i];let n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],o=!(r.length>=4&&e.length>=4)||r[3]===e[3];if(n&&o)return!0}return!1}function m(t,e){var i,r=0;for(i=0;i<t.length;i++){const n=t[i]-e[i];r+=n*n}return r}function w(t,e){return e>1?Math.round(t/e)*e:t}function b(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function y(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=v(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function v(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=T(r,i.slice(0,3),m),h=a[0],c=a[1];c>0&&c<=n&&(t[h]=i)}}function E(t){return t*t}function k(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return n}function T(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return[n,r]}function M(t,e,i=m){return t[k(t,e,i)]}function _(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:b=8,dispose:y=-1}=r;let v=!1;if(n?l||(v=!0,d(),l=!0):v=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),v){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|B(r.length)-1;A(t,e),A(t,i),t.writeBytes([o,0,0])}(s,e,i,m,b),C(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),S(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),A(t,e),t.writeByte(0)}(s,w)}const g=Math.round(p/10);!function(t,e,i,r,n){var o,s;t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1),r?(o=1,s=2):(o=0,s=0),e>=0&&(s=7&e),s<<=2,t.writeByte(0|s|o),A(t,i),t.writeByte(n||0),t.writeByte(0)}(s,y,g,u,f);const x=Boolean(m)&&!v;!function(t,e,i,r){if(t.writeByte(44),A(t,0),A(t,0),A(t,e),A(t,i),r){const e=B(r.length)-1;t.writeByte(128|e)}else t.writeByte(0)}(s,e,i,x?m:null),x&&C(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,b,a,h,c)}};function d(){S(s,"GIF89a")}}function C(t,e){const i=1<<B(e.length);for(let r=0;r<i;r++){let i=[0,0,0];r<e.length&&(i=e[r]),t.writeByte(i[0]),t.writeByte(i[1]),t.writeByte(i[2])}}function A(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function S(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function B(t){return Math.max(Math.ceil(Math.log2(t)),1)}var P=_}),v=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function g(){return new v("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function x(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(g());let s=!1;const a=setTimeout(()=>h(()=>o(function(t){return new v("VIDEO_EXPORT_TIMEOUT",t,void 0)}(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(g()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var E=class{canvas;_;C;A;S;B=null;P=0;I=0;constructor(t,e,i,r){this._=t,this.C=e,this.S=t.canvas,this.canvas=this.F(i,r);const n=this.canvas.getContext("2d");if(!n)throw new Error("Video export requires a 2D canvas context for staging frames.");n.imageSmoothingEnabled=!1,this.A=n}async $render(t){const e=this._,i=Math.max(1,Math.round(t.frameCount)),r=Math.max(1,Math.round(t.frameRate)),n=1e3/r,o=e.isLooping(),s=e.frameCount,a=e.millis,h="secs"in e,c=e.secs,l=this.$(),d=this.V(),u=this.C(()=>{this.U()});try{e.noLoop(),this.P=s,this.I=a,this.O(h),this.D(r,n),this.N();for(let e=0;e<i;e++)this.R(t.signal),this.P=s+e+1,this.I=1e3*e/r,await(t.prepareFrame?.({frameIndex:e,frameCount:i,timeSeconds:e/r,frameRate:r,signal:t.signal})),this.R(t.signal),await this.j(e,t.signal),this.R(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas})}finally{u(),this.B?.reject(/* @__PURE__ */new Error("Video export frame rendering was interrupted.")),this.B=null,this.L(d),this.H(l),e.frameCount=s,e.millis=a,h&&void 0!==c&&(e.secs=c),o?e.loop():e.noLoop()}}j(t,e){if(this.B)throw new Error("A video export frame is already pending.");const i=this._;return x(new Promise((e,r)=>{this.B={frameIndex:t,resolve:e,reject:r};try{i.redraw(1)}catch(n){this.B=null,r(n)}}),`Video export frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.B?.frameIndex===t&&(this.B=null),e})}U(){const t=this.B;if(t)try{this.A.clearRect(0,0,this.canvas.width,this.canvas.height),this.A.drawImage(this.S,0,0,this.S.width,this.S.height,0,0,this.canvas.width,this.canvas.height),this.B=null,t.resolve()}catch(e){this.B=null,t.reject(e)}}F(t,e){const i=document.createElement("canvas");return i.width=Math.max(1,Math.round(t)),i.height=Math.max(1,Math.round(e)),i}$(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),value:this._[t]}))}V(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),descriptor:Object.getOwnPropertyDescriptor(this._,t)}))}O(t){Object.defineProperty(this._,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.P,set:t=>{this.P=t}}),Object.defineProperty(this._,"millis",{configurable:!0,enumerable:!0,get:()=>this.I,set:t=>{this.I=t}}),t&&Object.defineProperty(this._,"secs",{configurable:!0,enumerable:!0,get:()=>this.I/1e3,set:t=>{this.I=1e3*t}})}D(t,e){const i=this._,r=i.frameRate;i.deltaTime=()=>e,i.frameRate=function(e){return void 0===e?t:r.call(this,e)}}N(){this._.resizeCanvas=()=>{}}H(t){const e=this._;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}L(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this._,e.key,e.descriptor):delete this._[e.key]}R(t){if(t?.aborted)throw g()}},k='(function() {\n\tvar r = ((t, r) => () => (r || (t((r = { exports: {} }).exports, r), t = null), r.exports))((t) => {\n\t\tvar r = Object.defineProperty;\n\t\tr(t, "__esModule", { value: !0 }), ((t, e) => {\n\t\t\tfor (var n in e) r(t, n, {\n\t\t\t\tget: e[n],\n\t\t\t\tenumerable: !0\n\t\t\t});\n\t\t})(t, {\n\t\t\tGIFEncoder: () => I,\n\t\t\tapplyPalette: () => b,\n\t\t\tdefault: () => x,\n\t\t\tnearestColor: () => C,\n\t\t\tnearestColorIndex: () => k,\n\t\t\tnearestColorIndexWithDistance: () => U,\n\t\t\tprequantize: () => A,\n\t\t\tquantize: () => y,\n\t\t\tsnapColorsToPalette: () => v\n\t\t});\n\t\tvar e = {\n\t\t\tsignature: "GIF",\n\t\t\tversion: "89a",\n\t\t\ttrailer: 59,\n\t\t\textensionIntroducer: 33,\n\t\t\tapplicationExtensionLabel: 255,\n\t\t\tgraphicControlExtensionLabel: 249,\n\t\t\timageSeparator: 44,\n\t\t\tsignatureSize: 3,\n\t\t\tversionSize: 3,\n\t\t\tglobalColorTableFlagMask: 128,\n\t\t\tcolorResolutionMask: 112,\n\t\t\tsortFlagMask: 8,\n\t\t\tglobalColorTableSizeMask: 7,\n\t\t\tapplicationIdentifierSize: 8,\n\t\t\tapplicationAuthCodeSize: 3,\n\t\t\tdisposalMethodMask: 28,\n\t\t\tuserInputFlagMask: 2,\n\t\t\ttransparentColorFlagMask: 1,\n\t\t\tlocalColorTableFlagMask: 128,\n\t\t\tinterlaceFlagMask: 64,\n\t\t\tidSortFlagMask: 32,\n\t\t\tlocalColorTableSizeMask: 7\n\t\t};\n\t\tfunction n(t = 256) {\n\t\t\tlet r = 0, e = new Uint8Array(t);\n\t\t\treturn {\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn e.buffer;\n\t\t\t\t},\n\t\t\t\treset() {\n\t\t\t\t\tr = 0;\n\t\t\t\t},\n\t\t\t\tbytesView: () => e.subarray(0, r),\n\t\t\t\tbytes: () => e.slice(0, r),\n\t\t\t\twriteByte(t) {\n\t\t\t\t\tn(r + 1), e[r] = t, r++;\n\t\t\t\t},\n\t\t\t\twriteBytes(t, o = 0, a = t.length) {\n\t\t\t\t\tn(r + a);\n\t\t\t\t\tfor (let n = 0; n < a; n++) e[r++] = t[n + o];\n\t\t\t\t},\n\t\t\t\twriteBytesView(t, o = 0, a = t.byteLength) {\n\t\t\t\t\tn(r + a), e.set(t.subarray(o, o + a), r), r += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction n(t) {\n\t\t\t\tvar n = e.length;\n\t\t\t\tif (n >= t) return;\n\t\t\t\tt = Math.max(t, n * (n < 1048576 ? 2 : 1.125) >>> 0), 0 != n && (t = Math.max(t, 256));\n\t\t\t\tconst o = e;\n\t\t\t\te = new Uint8Array(t), r > 0 && e.set(o.subarray(0, r), 0);\n\t\t\t}\n\t\t}\n\t\tvar o = [\n\t\t\t0,\n\t\t\t1,\n\t\t\t3,\n\t\t\t7,\n\t\t\t15,\n\t\t\t31,\n\t\t\t63,\n\t\t\t127,\n\t\t\t255,\n\t\t\t511,\n\t\t\t1023,\n\t\t\t2047,\n\t\t\t4095,\n\t\t\t8191,\n\t\t\t16383,\n\t\t\t32767,\n\t\t\t65535\n\t\t], a = function(t, r, e, a, i = n(512), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003)) {\n\t\t\tconst s = c.length, u = Math.max(2, a);\n\t\t\tl.fill(0), f.fill(0), c.fill(-1);\n\t\t\tlet p = 0, y = 0;\n\t\t\tconst h = u + 1, w = h;\n\t\t\tlet d = !1, A = w, b = (1 << A) - 1;\n\t\t\tconst M = 1 << h - 1, g = M + 1;\n\t\t\tlet v = M + 2, m = 0, k = e[0], U = 0;\n\t\t\tfor (let n = s; n < 65536; n *= 2) ++U;\n\t\t\tU = 8 - U, i.writeByte(u), I(M);\n\t\t\tconst C = e.length;\n\t\t\tfor (let n = 1; n < C; n++) t: {\n\t\t\t\tconst t = e[n], r = (t << 12) + k;\n\t\t\t\tlet o = t << U ^ k;\n\t\t\t\tif (c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tconst a = 0 === o ? 1 : s - o;\n\t\t\t\tfor (; c[o] >= 0;) if (o -= a, o < 0 && (o += s), c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tI(k), k = t, v < 4096 ? (f[o] = v++, c[o] = r) : (c.fill(-1), v = M + 2, d = !0, I(M));\n\t\t\t}\n\t\t\treturn I(k), I(g), i.writeByte(0), i.bytesView();\n\t\t\tfunction I(t) {\n\t\t\t\tfor (p &= o[y], y > 0 ? p |= t << y : p = t, y += A; y >= 8;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\tif ((v > b || d) && (d ? (A = w, b = (1 << A) - 1, d = !1) : (++A, b = 12 === A ? 1 << A : (1 << A) - 1)), t == g) {\n\t\t\t\t\tfor (; y > 0;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\t\tm > 0 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfunction i(t, r, e) {\n\t\t\treturn t << 8 & 63488 | r << 2 & 992 | e >> 3;\n\t\t}\n\t\tfunction l(t, r, e, n) {\n\t\t\treturn t >> 4 | 240 & r | (240 & e) << 4 | (240 & n) << 8;\n\t\t}\n\t\tfunction c(t, r, e) {\n\t\t\treturn t >> 4 << 8 | 240 & r | e >> 4;\n\t\t}\n\t\tfunction f(t, r, e) {\n\t\t\treturn t < r ? r : t > e ? e : t;\n\t\t}\n\t\tfunction s(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction u(t, r, e) {\n\t\t\tvar n = 0, o = 1e100;\n\t\t\tconst a = t[r], i = a.cnt, l = a.ac, c = a.rc, f = a.gc, u = a.bc;\n\t\t\tfor (var p = a.fw; 0 != p; p = t[p].fw) {\n\t\t\t\tconst r = t[p], a = r.cnt, h = i * a / (i + a);\n\t\t\t\tif (!(h >= o)) {\n\t\t\t\t\tvar y = 0;\n\t\t\t\t\te && (y += h * s(r.ac - l)) >= o || (y += h * s(r.rc - c)) >= o || (y += h * s(r.gc - f)) >= o || (y += h * s(r.bc - u)) >= o || (o = y, n = p);\n\t\t\t\t}\n\t\t\t}\n\t\t\ta.err = o, a.nn = n;\n\t\t}\n\t\tfunction p() {\n\t\t\treturn {\n\t\t\t\tac: 0,\n\t\t\t\trc: 0,\n\t\t\t\tgc: 0,\n\t\t\t\tbc: 0,\n\t\t\t\tcnt: 0,\n\t\t\t\tnn: 0,\n\t\t\t\tfw: 0,\n\t\t\t\tbk: 0,\n\t\t\t\ttm: 0,\n\t\t\t\tmtm: 0,\n\t\t\t\terr: 0\n\t\t\t};\n\t\t}\n\t\tfunction y(t, r, e = {}) {\n\t\t\tconst { format: n = "rgb565", clearAlpha: o = !0, clearAlphaColor: a = 0, clearAlphaThreshold: y = 0, oneBitAlpha: w = !1 } = e;\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tconst d = new Uint32Array(t.buffer);\n\t\t\tlet A = !1 !== e.useSqrt;\n\t\t\tconst b = "rgba4444" === n, M = function(t, r) {\n\t\t\t\tconst e = new Array("rgb444" === r ? 4096 : 65536), n = t.length;\n\t\t\t\tif ("rgba4444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 24 & 255, a = r >> 16 & 255, i = r >> 8 & 255, c = 255 & r, f = l(c, i, a, n);\n\t\t\t\t\tlet s = f in e ? e[f] : e[f] = p();\n\t\t\t\t\ts.rc += c, s.gc += i, s.bc += a, s.ac += n, s.cnt++;\n\t\t\t\t}\n\t\t\t\telse if ("rgb444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, i = 255 & r, l = c(i, a, n);\n\t\t\t\t\tlet f = l in e ? e[l] : e[l] = p();\n\t\t\t\t\tf.rc += i, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\telse for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, l = 255 & r, c = i(l, a, n);\n\t\t\t\t\tlet f = c in e ? e[c] : e[c] = p();\n\t\t\t\t\tf.rc += l, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}(d, n), g = M.length, v = g - 1, m = new Uint32Array(g + 1);\n\t\t\tfor (var k = 0, U = 0; U < g; ++U) {\n\t\t\t\tconst t = M[U];\n\t\t\t\tif (null != t) {\n\t\t\t\t\tvar C = 1 / t.cnt;\n\t\t\t\t\tb && (t.ac *= C), t.rc *= C, t.gc *= C, t.bc *= C, M[k++] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar I, F, z;\n\t\t\tfor (s(r) / k < .022 && (A = !1), U = 0; U < k - 1; ++U) M[U].fw = U + 1, M[U + 1].bk = U, A && (M[U].cnt = Math.sqrt(M[U].cnt));\n\t\t\tfor (A && (M[U].cnt = Math.sqrt(M[U].cnt)), U = 0; U < k; ++U) {\n\t\t\t\tu(M, U, !1);\n\t\t\t\tvar B = M[U].err;\n\t\t\t\tfor (F = ++m[0]; F > 1 && !(M[I = m[z = F >> 1]].err <= B); F = z) m[F] = I;\n\t\t\t\tm[F] = U;\n\t\t\t}\n\t\t\tvar E = k - r;\n\t\t\tfor (U = 0; U < E;) {\n\t\t\t\tfor (var x;;) {\n\t\t\t\t\tvar G = m[1];\n\t\t\t\t\tif ((x = M[G]).tm >= x.mtm && M[x.nn].mtm <= x.tm) break;\n\t\t\t\t\tfor (x.mtm == v ? G = m[1] = m[m[0]--] : (u(M, G, !1), x.tm = U), B = M[G].err, F = 1; (z = F + F) <= m[0] && (z < m[0] && M[m[z]].err > M[m[z + 1]].err && z++, !(B <= M[I = m[z]].err)); F = z) m[F] = I;\n\t\t\t\t\tm[F] = G;\n\t\t\t\t}\n\t\t\t\tvar S = M[x.nn], T = x.cnt, q = S.cnt;\n\t\t\t\tC = 1 / (T + q), b && (x.ac = C * (T * x.ac + q * S.ac)), x.rc = C * (T * x.rc + q * S.rc), x.gc = C * (T * x.gc + q * S.gc), x.bc = C * (T * x.bc + q * S.bc), x.cnt += S.cnt, x.mtm = ++U, M[S.bk].fw = S.fw, M[S.fw].bk = S.bk, S.mtm = v;\n\t\t\t}\n\t\t\tlet R = [];\n\t\t\tvar P = 0;\n\t\t\tfor (U = 0;; ++P) {\n\t\t\t\tlet t = f(Math.round(M[U].rc), 0, 255), r = f(Math.round(M[U].gc), 0, 255), e = f(Math.round(M[U].bc), 0, 255), n = 255;\n\t\t\t\tb && (n = f(Math.round(M[U].ac), 0, 255), w && (n = n <= ("number" == typeof w ? w : 127) ? 0 : 255), o && n <= y && (t = r = e = a, n = 0));\n\t\t\t\tconst i = b ? [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te,\n\t\t\t\t\tn\n\t\t\t\t] : [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te\n\t\t\t\t];\n\t\t\t\tif (h(R, i) || R.push(i), 0 == (U = M[U].fw)) break;\n\t\t\t}\n\t\t\treturn R;\n\t\t}\n\t\tfunction h(t, r) {\n\t\t\tfor (let e = 0; e < t.length; e++) {\n\t\t\t\tconst n = t[e];\n\t\t\t\tlet o = n[0] === r[0] && n[1] === r[1] && n[2] === r[2], a = !(n.length >= 4 && r.length >= 4) || n[3] === r[3];\n\t\t\t\tif (o && a) return !0;\n\t\t\t}\n\t\t\treturn !1;\n\t\t}\n\t\tfunction w(t, r) {\n\t\t\tvar e, n = 0;\n\t\t\tfor (e = 0; e < t.length; e++) {\n\t\t\t\tconst o = t[e] - r[e];\n\t\t\t\tn += o * o;\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\t\tfunction d(t, r) {\n\t\t\treturn r > 1 ? Math.round(t / r) * r : t;\n\t\t}\n\t\tfunction A(t, { roundRGB: r = 5, roundAlpha: e = 10, oneBitAlpha: n = null } = {}) {\n\t\t\tconst o = new Uint32Array(t.buffer);\n\t\t\tfor (let a = 0; a < o.length; a++) {\n\t\t\t\tconst t = o[a];\n\t\t\t\tlet i = t >> 24 & 255, l = t >> 16 & 255, c = t >> 8 & 255, f = 255 & t;\n\t\t\t\ti = d(i, e), n && (i = i <= ("number" == typeof n ? n : 127) ? 0 : 255), f = d(f, r), c = d(c, r), l = d(l, r), o[a] = i << 24 | l << 16 | c << 8 | f;\n\t\t\t}\n\t\t}\n\t\tfunction b(t, r, e = "rgb565") {\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (r.length > 256) throw new Error("applyPalette() only works with 256 colors or less");\n\t\t\tconst n = new Uint32Array(t.buffer), o = n.length, a = "rgb444" === e ? 4096 : 65536, f = new Uint8Array(o), s = new Array(a);\n\t\t\tif ("rgba4444" === e) for (let i = 0; i < o; i++) {\n\t\t\t\tconst t = n[i], e = t >> 24 & 255, o = t >> 16 & 255, a = t >> 8 & 255, c = 255 & t, u = l(c, a, o, e);\n\t\t\t\tf[i] = u in s ? s[u] : s[u] = M(c, a, o, e, r);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst t = "rgb444" === e ? c : i;\n\t\t\t\tfor (let e = 0; e < o; e++) {\n\t\t\t\t\tconst o = n[e], a = o >> 16 & 255, i = o >> 8 & 255, l = 255 & o, c = t(l, i, a);\n\t\t\t\t\tf[e] = c in s ? s[c] : s[c] = g(l, i, a, r);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f;\n\t\t}\n\t\tfunction M(t, r, e, n, o) {\n\t\t\tlet a = 0, i = 1e100;\n\t\t\tfor (let l = 0; l < o.length; l++) {\n\t\t\t\tconst c = o[l];\n\t\t\t\tlet f = m(c[3] - n);\n\t\t\t\tf > i || (f += m(c[0] - t), f > i || (f += m(c[1] - r), f > i || (f += m(c[2] - e), f > i || (i = f, a = l))));\n\t\t\t}\n\t\t\treturn a;\n\t\t}\n\t\tfunction g(t, r, e, n) {\n\t\t\tlet o = 0, a = 1e100;\n\t\t\tfor (let i = 0; i < n.length; i++) {\n\t\t\t\tconst l = n[i];\n\t\t\t\tlet c = m(l[0] - t);\n\t\t\t\tc > a || (c += m(l[1] - r), c > a || (c += m(l[2] - e), c > a || (a = c, o = i)));\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction v(t, r, e = 5) {\n\t\t\tif (!t.length || !r.length) return;\n\t\t\tconst n = t.map((t) => t.slice(0, 3)), o = e * e, a = t[0].length;\n\t\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\t\tlet e = r[i];\n\t\t\t\te = e.length < a ? [\n\t\t\t\t\te[0],\n\t\t\t\t\te[1],\n\t\t\t\t\te[2],\n\t\t\t\t\t255\n\t\t\t\t] : e.length > a ? e.slice(0, 3) : e.slice();\n\t\t\t\tconst l = U(n, e.slice(0, 3), w), c = l[0], f = l[1];\n\t\t\t\tf > 0 && f <= o && (t[c] = e);\n\t\t\t}\n\t\t}\n\t\tfunction m(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction k(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction U(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn [o, n];\n\t\t}\n\t\tfunction C(t, r, e = w) {\n\t\t\treturn t[k(t, r, e)];\n\t\t}\n\t\tfunction I(t = {}) {\n\t\t\tconst { initialCapacity: r = 4096, auto: o = !0 } = t, i = n(r), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003);\n\t\t\tlet s = !1;\n\t\t\treturn {\n\t\t\t\treset() {\n\t\t\t\t\ti.reset(), s = !1;\n\t\t\t\t},\n\t\t\t\tfinish() {\n\t\t\t\t\ti.writeByte(e.trailer);\n\t\t\t\t},\n\t\t\t\tbytes: () => i.bytes(),\n\t\t\t\tbytesView: () => i.bytesView(),\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn i.buffer;\n\t\t\t\t},\n\t\t\t\tget stream() {\n\t\t\t\t\treturn i;\n\t\t\t\t},\n\t\t\t\twriteHeader: u,\n\t\t\t\twriteFrame(t, r, e, n = {}) {\n\t\t\t\t\tconst { transparent: p = !1, transparentIndex: y = 0, delay: h = 0, palette: w = null, repeat: d = 0, colorDepth: A = 8, dispose: b = -1 } = n;\n\t\t\t\t\tlet M = !1;\n\t\t\t\t\tif (o ? s || (M = !0, u(), s = !0) : M = Boolean(n.first), r = Math.max(0, Math.floor(r)), e = Math.max(0, Math.floor(e)), M) {\n\t\t\t\t\t\tif (!w) throw new Error("First frame must include a { palette } option");\n\t\t\t\t\t\t(function(t, r, e, n, o = 8) {\n\t\t\t\t\t\t\tconst a = o - 1 << 4 | 128 | E(n.length) - 1;\n\t\t\t\t\t\t\tz(t, r), z(t, e), t.writeBytes([\n\t\t\t\t\t\t\t\ta,\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t})(i, r, e, w, A), F(i, w), d >= 0 && function(t, r) {\n\t\t\t\t\t\t\tt.writeByte(33), t.writeByte(255), t.writeByte(11), B(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), z(t, r), t.writeByte(0);\n\t\t\t\t\t\t}(i, d);\n\t\t\t\t\t}\n\t\t\t\t\tconst g = Math.round(h / 10);\n\t\t\t\t\t(function(t, r, e, n, o) {\n\t\t\t\t\t\tvar a, i;\n\t\t\t\t\t\tt.writeByte(33), t.writeByte(249), t.writeByte(4), o < 0 && (o = 0, n = !1), n ? (a = 1, i = 2) : (a = 0, i = 0), r >= 0 && (i = 7 & r), i <<= 2, t.writeByte(0 | i | a), z(t, e), t.writeByte(o || 0), t.writeByte(0);\n\t\t\t\t\t})(i, b, g, p, y);\n\t\t\t\t\tconst v = Boolean(w) && !M;\n\t\t\t\t\t(function(t, r, e, n) {\n\t\t\t\t\t\tif (t.writeByte(44), z(t, 0), z(t, 0), z(t, r), z(t, e), n) {\n\t\t\t\t\t\t\tconst r = E(n.length) - 1;\n\t\t\t\t\t\t\tt.writeByte(128 | r);\n\t\t\t\t\t\t} else t.writeByte(0);\n\t\t\t\t\t})(i, r, e, v ? w : null), v && F(i, w), function(t, r, e, n, o = 8, i, l, c) {\n\t\t\t\t\t\ta(e, n, r, o, t, i, l, c);\n\t\t\t\t\t}(i, t, r, e, A, l, c, f);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction u() {\n\t\t\t\tB(i, "GIF89a");\n\t\t\t}\n\t\t}\n\t\tfunction F(t, r) {\n\t\t\tconst e = 1 << E(r.length);\n\t\t\tfor (let n = 0; n < e; n++) {\n\t\t\t\tlet e = [\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t\t];\n\t\t\t\tn < r.length && (e = r[n]), t.writeByte(e[0]), t.writeByte(e[1]), t.writeByte(e[2]);\n\t\t\t}\n\t\t}\n\t\tfunction z(t, r) {\n\t\t\tt.writeByte(255 & r), t.writeByte(r >> 8 & 255);\n\t\t}\n\t\tfunction B(t, r) {\n\t\t\tfor (var e = 0; e < r.length; e++) t.writeByte(r.charCodeAt(e));\n\t\t}\n\t\tfunction E(t) {\n\t\t\treturn Math.max(Math.ceil(Math.log2(t)), 1);\n\t\t}\n\t\tvar x = I;\n\t})();\n\tconst e = (0, r.GIFEncoder)();\n\tlet n = 1, o = 1, a = 16, i = 0;\n\tconst l = self;\n\tl.addEventListener("message", (t) => {\n\t\tconst c = t.data;\n\t\ttry {\n\t\t\tif ("init" === c.type) return n = c.width ?? n, o = c.height ?? o, a = c.delay ?? a, i = c.repeat ?? i, void l.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "ready"\n\t\t\t});\n\t\t\tif ("frame" === c.type && c.buffer) {\n\t\t\t\tconst t = new Uint8ClampedArray(c.buffer), f = (0, r.quantize)(t, 256, {}), s = (0, r.applyPalette)(t, f);\n\t\t\t\te.writeFrame(s, n, o, {\n\t\t\t\t\tpalette: f,\n\t\t\t\t\tdelay: a,\n\t\t\t\t\trepeat: 0 === c.frameIndex ? i : -1\n\t\t\t\t}), l.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "frame-complete"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ("finish" === c.type) {\n\t\t\t\te.finish();\n\t\t\t\tconst t = e.bytes(), r = t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength);\n\t\t\t\tl.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "complete",\n\t\t\t\t\tbuffer: r\n\t\t\t\t}, [r]);\n\t\t\t}\n\t\t} catch (f) {\n\t\t\tl.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "error",\n\t\t\t\tmessage: f instanceof Error ? f.message : "GIF worker failed"\n\t\t\t});\n\t\t}\n\t});\n})();\n',T="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",k],{type:"text/javascript;charset=utf-8"});function M(t){let e;try{if(e=T&&(self.URL||self.webkitURL).createObjectURL(T),!e)throw"";const i=new Worker(e,{name:t?.name});return i.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),i}catch(i){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(k),{name:t?.name})}}var _=class{G;q=/* @__PURE__ */new Map;W;X=0;Y=!1;constructor(t,e,i,r,n){this.G=new M,this.G.addEventListener("message",this.J),this.G.addEventListener("error",this.K),n?.addEventListener("abort",this.dispose,{once:!0}),this.W=this.Z({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.W,await this.Z({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.W;const t=await this.Z({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.Y){this.Y=!0,this.G.terminate();for(const t of this.q.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.q.clear()}};Z(t,e=[]){if(this.Y)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.X;return new Promise((r,n)=>{this.q.set(i,{resolve:r,reject:n}),this.G.postMessage({...t,id:i},e)})}J=t=>{const e=t.data,i=this.q.get(e.id);i&&(this.q.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};K=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.q.values())i.reject(e);this.q.clear()}},C=y(),A=class{_;C;constructor(t,e){this._=t,this.C=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new r).$downloadFile(e,t.filename)}async $generateGIFBlob(t={}){const e=this.k(t),i=this._.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new E(this._,this.C,r,n),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,C.GIFEncoder)():null,h="undefined"==typeof Worker?null:new _(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.R(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.R(e.signal);const n=s.getImageData(0,0,r.width,r.height);if(h)await h.encodeFrame(n.data.buffer,i);else if(a){const t=n.data,o=(0,C.quantize)(t,256,{}),s=(0,C.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.tt(e.signal)}}),this.R(e.signal),h)i=await h.finish();else{if(!a)throw new Error("No GIF encoder is available.");{a.finish();const t=a.bytes();i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}return t.onProgress?.({state:"completed",totalFrames:e.frameCount}),new Blob([i],{type:"image/gif"})}catch(c){throw t.onProgress?.({state:"error",message:c instanceof Error?c.message:"GIF export failed"}),c}finally{h?.dispose()}}k(t){return{filename:t.filename,frameCount:Math.max(1,Math.abs(Math.round(t.frameCount??300))),frameRate:Math.max(1,Math.abs(t.frameRate??60)),scale:Math.max(Number.EPSILON,Math.abs(t.scale??1)),repeat:Math.max(-1,Math.round(t.repeat??0)),signal:t.signal,prepareFrame:t.prepareFrame}}R(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}tt(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}};function S(t){if(!t)throw new Error("Assertion failed.")}var B,P=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},I=t=>t&&t[t.length-1],F=t=>t>=0&&t<2**32,$=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},V=t=>{const e=$(t);return 1&e?e+1>>1:-(e>>1)},U=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),O=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),D=/* #__PURE__ */new TextEncoder,N={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},R={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},z={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},j=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),L=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),H=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}},G=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},q=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},W=t=>{throw new Error(`Unexpected value: ${t}`)},X=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2);return i?r|n<<8|o<<16:r<<16|n<<8|o},Y=(t,e,i)=>Math.max(e,Math.min(i,t)),Q=(t,e)=>Math.round(t/e)*e,J=(t,e)=>Math.round(t*e)/e,K=(t,e)=>Math.floor(t*e)/e,Z=/^[a-z]{3}$/,tt=1e6*(1+Number.EPSILON),et=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},it=null,rt=()=>null!==it?it:it="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),nt=null,ot=()=>null!==nt?nt:nt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),st=null,at=()=>{if(null!==st)return st;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?st=Number(t[1]):null},ht=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},ct=t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},lt=(t,e)=>{if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},dt=t=>{S(Number.isInteger(t.num)),S(Number.isInteger(t.den)),S(0!==t.den);let e=Math.abs(t.num),i=Math.abs(t.den);for(;0!==i;){const t=e%i;e=i,i=t}const r=e||1;return{num:t.num/r,den:t.den/r}},ut=(t,e)=>{if("object"!=typeof t||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},ft=t=>Array.isArray(t)?t:[t],pt=class{constructor(){this.et=/* @__PURE__ */new Map}on(t,e,i){this.et.has(t)||this.et.set(t,/* @__PURE__ */new Set);const r={fn:e,once:i?.once??!1};return this.et.get(t).add(r),()=>{this.et.get(t)?.delete(r)}}it(...t){const[e,i]=t,r=this.et.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},mt=t=>null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(t=>"string"==typeof t);!function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"}(B||(B={}));var wt=class t{constructor(){}static get level(){return t.rt}static set level(e){if(e!==B.Silent&&e!==B.Errors&&e!==B.Warnings&&e!==B.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.rt=e}static get nt(){return t.ot??=new pt}static on(e,i,r){return t.nt.on(e,i,r)}static st(...e){t.nt.it("error",e),t.rt>=B.Errors&&console.error(...e)}static ht(...e){t.nt.it("warn",e),t.rt>=B.Warnings&&console.warn(...e)}static ct(...e){t.nt.it("info",e),t.rt>=B.Info&&console.info(...e)}};wt.rt=B.Info,wt.ot=null;var bt,yt,vt=class{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof e)throw new TypeError("mimeType must be a string.")}},gt=class{constructor(t,e,i,r){if(this.data=t,this.mimeType=e,this.name=i,this.description=r,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==e&&"string"!=typeof e)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}},xt=class t{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let r=this.pos;r<i;r++){const t=Math.floor(r/8);let n=this.bytes[t];const o=7-(7&r);n&=~(1<<o),n|=(e&1<<i-r-1)>>i-r-1<<o,this.bytes[t]=n}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new t(this.bytes);return e.pos=this.pos,e}},Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],kt=[-1,1,2,3,4,5,6,8],Tt=t=>{let e=Et.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const r=kt.indexOf(t.numberOfChannels);if(-1===r)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),15===e&&(n+=24);const o=Math.ceil(n/8),s=new Uint8Array(o),a=new xt(s);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),15===e&&a.writeBits(24,i),a.writeBits(4,r),s},Mt=["avc","hevc","vp9","av1","vp8","prores"],_t=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Ct=["aac","opus","mp3","vorbis","flac","ac3","eac3"],At=[...Ct,..._t],St=["webvtt"],Bt=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Pt=[{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}],It=[{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}],Ft=[{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}],$t=["ap4x","ap4h","apch","apcn","apcs","apco"],Vt=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Ut=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Bt.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??I(Bt),s=o?o.level:0;return`avc1.${t.toString(16).padStart(2,"0")}00${s.toString(16).padStart(2,"0")}`}if("hevc"===t){const t="",n=1,o="6",s=e*i,a=Pt.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??I(Pt);return`hev1.${t}${n}.${o}.${a.tier}${a.level}.B0`}if("vp8"===t)return"vp8";if("vp9"===t){const t=e*i;return`vp09.00.${(It.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??I(It)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Ft.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??I(Ft);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Vt.filter(t=>t.alpha===n);let s=o[0].fourCc,a=1/0;for(const{fourCc:e,bitrate:i}of o){const n=Math.abs(i*t-r);n<a&&(a=n,s=e)}return s}throw W(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Ot=t=>{const e=t.split("."),i=Number(e[1]),r=e[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(e[3])?0:1)<<6)+0+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},Dt=/^pcm-([usf])(\d+)(be)?$/,Nt=t=>{if(S(_t.includes(t)),"ulaw"===t)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===t)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Dt.exec(t);let i;return S(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},Rt=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...$t],zt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,jt=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Lt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Ht=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Gt=t=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof t)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("object"!=typeof t.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Rt.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 Mediabunny 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(void 0!==t.decoderConfig.displayAspectWidth&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectHeight&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectWidth!=(void 0!==t.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==t.decoderConfig.description&&!L(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(N);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(R);if(null!=e.transfer&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(z);if(null!=e.matrix&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)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(!zt.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(!jt.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("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!Lt.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!Ht.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if($t.some(e=>t.decoderConfig.codec.startsWith(e))&&!$t.some(e=>t.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${$t.join(", ")}.`)},qt=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Wt=t=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!qt.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!L(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!_t.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${_t.join(", ")}).`)},Xt=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof t)throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof t.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof t.config.description)throw new TypeError("Subtitle metadata config description must be a string.")},Yt=[48e3,44100,32e3],Qt=[24e3,22050,16e3];!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(bt||(bt={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(yt||(yt={}));var Jt,Kt=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(-1===r||r>=t.length-2)break;e=r;let n=0;e+3<t.length&&0===t[e+1]&&0===t[e+2]&&1===t[e+3]?n=4:0===t[e+1]&&1===t[e+2]&&(n=3),0!==n?(-1!==i&&e>i&&(yield{offset:i,length:e-i}),i=e+n,e=i):e++}-1!==i&&i<t.length&&(yield{offset:i,length:t.length-i})},Zt=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=X(r,i,!1):(S(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},te=t=>31&t,ee=t=>{const e=[],i=t.length;for(let r=0;r<i;r++)r+2<i&&0===t[r]&&0===t[r+1]&&3===t[r+2]?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},ie=(new Uint8Array([0,0,0,1]),{1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}}),re=t=>{const e=$(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)$(t),$(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},ne=t=>t>>1&63,oe=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=/* @__PURE__ */new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},se=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&V(t);for(let e=0;e<i;e++)V(t)}else $(t)},ae=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=he(t,r,e,i)},he=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-($(t)+1):e-1,t.readBits(1),$(t);const o=r[s]??0;for(let e=0;e<=o;e++)t.readBits(1)||t.readBits(1);n=r[s]}else{const e=$(t),i=$(t);for(let r=0;r<e;r++)$(t),t.readBits(1);for(let r=0;r<i;r++)$(t),t.readBits(1);n=e+i}return n},ce=(t,e)=>{let i=2,r=2,n=2,o=0,s=0,a={num:1,den:1};if(t.readBits(1)){const e=t.readBits(8);if(255===e)a={num:t.readBits(16),den:t.readBits(16)};else{const t=ie[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&($(t),$(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&($(t),$(t),$(t),$(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&$(t),t.readBits(1)&&le(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=$(t),$(t),$(t),$(t),$(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},le=(t,e,i)=>{let r=!1,n=!1,o=!1;e&&(r=1===t.readBits(1),n=1===t.readBits(1),(r||n)&&(o=1===t.readBits(1),o&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),o&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let s=0;s<=i;s++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?$(t):i=1===t.readBits(1);let s=1;i||(s=$(t)+1),r&&de(t,s,o),n&&de(t,s,o)}},de=(t,e,i)=>{for(let r=0;r<e;r++)$(t),$(t),i&&($(t),$(t)),t.readBits(1)};!function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"}(Jt||(Jt={}));var ue,fe=t=>{const e=O(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(ue||(ue={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var pe,me=[1,2,3,6],we=/* #__PURE__ */new Uint8Array(0),be=class t{constructor(t,e,i,r,n=-1,o,s){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=n,t===we&&void 0===o)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===o&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===we}get microsecondTimestamp(){return Math.trunc(tt*this.timestamp)}get microsecondDuration(){return Math.trunc(tt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new t(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!=typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}},ye=class{constructor(t){this.value=t}},ve=class{constructor(t){this.value=t}},ge=class{constructor(t){this.value=t}},xe=class{constructor(t){this.value=t}};!function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"}(pe||(pe={})),pe.EBML,pe.Segment,pe.SeekHead,pe.Info,pe.Cluster,pe.Tracks,pe.Cues,pe.Attachments,pe.Chapters,pe.Tags;var Ee=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,ke=t=>t<256n?1:t<65536n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,Te=t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-1048576&&t<1<<20?3:t>=-134217728&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,Me=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap,this.dataOffsets=/* @__PURE__ */new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Ee(t)){let i=0;switch(e){case 6:this.helperView.setUint8(i++,t/2**40|0);case 5:this.helperView.setUint8(i++,t/2**32|0);case 4:this.helperView.setUint8(i++,t>>24);case 3:this.helperView.setUint8(i++,t>>16);case 2:this.helperView.setUint8(i++,t>>8);case 1:this.helperView.setUint8(i++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(t,e=ke(t)){let i=0;for(let r=e-1;r>=0;r--)this.helperView.setUint8(i++,Number(t>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=Te(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)})(t)){let i=0;switch(e){case 1:this.helperView.setUint8(i++,128|t);break;case 2:this.helperView.setUint8(i++,64|t>>8),this.helperView.setUint8(i++,t);break;case 3:this.helperView.setUint8(i++,32|t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 4:this.helperView.setUint8(i++,16|t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 5:this.helperView.setUint8(i++,8|t/2**32&7),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 6:this.helperView.setUint8(i++,4|t/2**40&3),this.helperView.setUint8(i++,t/2**32|0),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(t=>t.charCodeAt(0))))}writeEBML(t){if(null!==t)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(const e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){const e=this.writer.getPos(),i=-1===t.size?1:t.size??4;-1===t.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(t,r),this.writeEBML(t.data),-1!==t.size){const t=this.writer.getPos()-r,n=this.writer.getPos();this.writer.seek(e),this.writeVarInt(t,i),this.writer.seek(n)}}else if("number"==typeof t.data){const e=t.size??Ee(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??ke(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if("string"==typeof t.data)this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof ye)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof ve)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof ge){const e=t.size??Te(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof xe){const e=D.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else W(t.data)}},_e={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"},Ce=t=>{const e=t.filePos,i=new xt(di(t,9));if(4095!==i.readBits(12))return null;if(i.skipBits(1),0!==i.readBits(2))return null;const r=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const s=i.readBits(3);if(0===s)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const a=i.readBits(13);i.skipBits(11);const h=i.readBits(2)+1;if(1!==h)throw new Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===r?t.filePos-=2:c=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:a,numberOfAacFrames:h,crcCheck:c,startPos:e}},Ae=/* @__PURE__ */e((t,e)=>{e.exports={}}),Se=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});Symbol.dispose??=Symbol("Symbol.dispose");var Be=-1/0,Pe=-1/0,Ie=null;"undefined"!=typeof FinalizationRegistry&&(Ie=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-Be>=1e3&&(wt.st("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Be=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Pe>=1e3&&(wt.st("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Pe=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var Fe=class{constructor(){this.lt=0,this.dt=null}},$e=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ve=new Set($e),Ue=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(tt*this.timestamp)}get microsecondDuration(){return Math.trunc(tt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.ut=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!Ve.has(i.format))throw new TypeError("init.format must be one of: "+$e.join(", "));if(!Number.isInteger(i.codedWidth)||i.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(i.codedHeight)||i.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.layout){if(!Array.isArray(i.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const t of i.layout){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==i.visibleRect&&ut(i.visibleRect,"init.visibleRect"),void 0!==i.displayWidth&&(!Number.isInteger(i.displayWidth)||i.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==i.displayHeight&&(!Number.isInteger(i.displayHeight)||i.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==i.displayWidth!=(void 0!==i.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=i.format,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0;const t=i.layout??qe(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.ft=i.wt?U(e):U(e).slice(),this.bt=t,this.colorSpace=new ze(r)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==i?.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i?.timestamp&&!Number.isFinite(i?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==i?.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==i?.visibleRect&&ut(i.visibleRect,"init.visibleRect"),this.ft=e,this.bt=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6,this.colorSpace=new ze(e.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*tt),duration:Math.trunc((i.duration??0)*tt)||void 0}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=new OffscreenCanvas(r,n),s=o.getContext("2d",{alpha:rt(),willReadFrequently:!0});if(!s)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");s.drawImage(e,0,0),this.ft=o,this.bt=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:r,height:n},this.squarePixelWidth=r,this.squarePixelHeight=n,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new ze({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Fe))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.ft=e,e.lt++,this.format=e.getFormat(),null!==this.format&&!$e.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=i?.encodeOptions??{},this.pixelAspectRatio=dt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ie?.register(this,{type:"video",data:this.ft},this)}clone(){if(this.ut)throw new Error("VideoSample is closed.");return S(null!==this.ft),this.ft instanceof Fe?new t(this.ft,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):je(this.ft)?new t(this.ft.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.ft instanceof Uint8Array?(S(this.bt),new t(this.ft,{format:this.format,layout:this.bt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,wt:!0})):new t(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.ut||(Ie?.unregister(this),this.ft instanceof Fe?(this.ft.lt--,0===this.ft.lt&&this.ft.close()):je(this.ft)?this.ft.close():this.ft=null,this.ut=!0)}allocationSize(t={}){if(Ge(t),this.ut)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot get allocation size when format is null.");return je(this.ft)?this.ft.allocationSize(t):Xe(this,t).allocationSize}async copyTo(e,i={}){if(!L(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ge(i),this.ut)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(S(null!==this.ft),je(this.ft))return this.ft.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format)){if(!(this.ft instanceof Fe)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const t=this.toVideoFrame(),r=await t.copyTo(e,i);return t.close(),r}{const r={stack:[],error:void 0,hasError:!1};try{const n=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e}(r,await this.ft.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},i.colorSpace??"srgb"),!1);if(!(n instanceof t))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return await n.copyTo(e,i)}catch(c){r.error=c,r.hasError=!0}finally{Se(r)}}}const r=Xe(this,i);S(this.format);const n=U(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=We(this.format);let s;if(this.ft instanceof Fe){let t=this.ft.getDataPlanes();if(t instanceof Promise&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.ft instanceof Uint8Array)S(this.bt),S(this.bt.length===o.length),s=this.bt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.ft.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.ft.getContext("2d");S(t),s=[{data:U(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.ut)throw new Error("VideoSample is closed.");if(S(null!==this.ft),this.ft instanceof Fe){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this.ft.getDataPlanes();if(t instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const e=t.reduce((t,e)=>t+e.data.byteLength,0),i=new Uint8Array(e);let r=0;const n=[];for(const o of t)i.set(o.data,r),n.push(r),r+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((t,e)=>({offset:n[e],stride:t.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return je(this.ft)?new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.ft instanceof Uint8Array?(S(this.bt),new VideoFrame(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.bt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.ut)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.yt(c,l,d,u,this.rotation));const b=this.toCanvasImageSource();t.save();const y=f+m/2,v=p+w/2;t.translate(y,v),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(b,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&He(e.crop,"options.");const i=t.canvas.width,r=t.canvas.height,n=e.rotation??this.rotation,[o,s]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a,h,c,l,d=e.crop;d&&(d=Le(d,o,s));const{sx:u,sy:f,sWidth:p,sHeight:m}=this.yt(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??s,n);if("fill"===e.fit)a=0,h=0,c=i,l=r;else{const[t,n]=e.crop?[e.crop.width,e.crop.height]:[o,s],d="contain"===e.fit?Math.min(i/t,r/n):Math.max(i/t,r/n);c=t*d,l=n*d,a=(i-c)/2,h=(r-l)/2}t.save();const w=n%180==0?1:c/l;t.translate(i/2,r/2),t.rotate(n*Math.PI/180),t.scale(1/w,w),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),u,f,p,m,a,h,c,l),t.restore()}yt(t,e,i,r,n){return 90===n?[t,e,i,r]=[e,this.squarePixelHeight-t-i,r,i]:180===n?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-r]:270===n&&([t,e,i,r]=[this.squarePixelWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this.ut)throw new Error("VideoSample is closed.");if(S(null!==this.ft),this.ft instanceof Fe||this.ft instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this.ft}async transform(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&He(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const i=P(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=Le(o,r,n));const s=o?o.width:r,a=o?o.height:n,h=s/a;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/h):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*h):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=a),c=Q(c,e.roundDimensionsTo??1),l=Q(l,e.roundDimensionsTo??1);const d={width:c,height:l,fit:e.fit??"fill",rotation:i,crop:o??{left:0,top:0,width:r,height:n},alpha:e.alpha??"keep"};for(const t of Oe){let e=t(this,d);if(e instanceof Promise&&(e=await e),null!==e)return e}let u=null,f=!1;for(const t of Ne)if(t.canvas.width===d.width&&t.canvas.height===d.height){u=t.canvas,t.age=Re++;break}if(null===u){if("undefined"!=typeof OffscreenCanvas)u=new OffscreenCanvas(d.width,d.height);else{if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");u=document.createElement("canvas"),u.width=d.width,u.height=d.height}f=!0,Ne.length>=De&&Ne.splice(((t,e)=>{let i=-1,r=1/0;for(let n=0;n<t.length;n++){const o=e(t[n]);o<r&&(r=o,i=n)}return i})(Ne,t=>t.age),1),Ne.push({canvas:u,age:Re++})}const p=u.getContext("2d",{alpha:!0});if(!p)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return p.imageSmoothingQuality="high","discard"===d.alpha?(p.fillStyle="black",p.fillRect(0,0,d.width,d.height)):f||p.clearRect(0,0,d.width,d.height),this.drawWithFit(p,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new t(u,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||"object"!=typeof t)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},Oe=[],De=3,Ne=[],Re=0,ze=class{constructor(t){if(void 0!==t){if(!t||"object"!=typeof t)throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(N);if(null!=t.primaries&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(R);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(z);if(null!=t.matrix&&!r.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},je=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,Le=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),o=Math.min(t.width,e-r),s=Math.min(t.height,i-n);return S(o>=0),S(s>=0),{left:r,top:n,width:o,height:s}},He=(t,e)=>{if(!t||"object"!=typeof t)throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Ge=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.colorSpace&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==t.format&&"string"!=typeof t.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!=typeof e)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.rect){if(!t.rect||"object"!=typeof t.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==t.rect.x&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==t.rect.y&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==t.rect.width&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==t.rect.height&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},qe=(t,e,i)=>{const r=We(t),n=[];let o=0;for(const s of r){const t=Math.ceil(e/s.widthDivisor),r=Math.ceil(i/s.heightDivisor),a=t*s.sampleBytes,h=a*r;n.push({offset:o,stride:a}),o+=h}return n},We=t=>{const e=(t,e,i,r,n)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return n&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:W(t),S(!1)}},Xe=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Ye(i,r,t.codedWidth,t.codedHeight,t.format),o=e.layout;let s;if(e.format&&e.format!==t.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(e.format))throw new Error("NotSupportedError: Invalid destination format.");s=e.format}else s=t.format;return Je(n,s,o)},Ye=(t,e,i,r,n)=>{const o={...t};if(void 0!==e){if(0===e.width||0===e.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");o.x=e.x||0,o.y=e.y||0,o.width=e.width||0,o.height=e.height||0}if(!Qe(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Qe=(t,e)=>{if(null===t)return!0;const i=We(t);for(let r=0;r<i.length;r++){const t=i[r],n=t.widthDivisor,o=t.heightDivisor;if((e.x||0)%n!==0)return!1;if((e.y||0)%o!==0)return!1}return!0},Je=(t,e,i)=>{const r=We(e),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let o=0;const s=[],a=[];for(let h=0;h<n;h++){const e=r[h],n=e.sampleBytes,c=e.widthDivisor,l=e.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(t.y||0)/l),d.sourceHeight=Math.ceil(Math.trunc(t.height||0)/l),d.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/c)*n,d.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/c)*n,void 0!==i){const t=i[h];if(t.stride<d.sourceWidthBytes)throw new TypeError(`Stride for plane ${h} is too small.`);d.destinationOffset=t.offset,d.destinationStride=t.stride}else d.destinationOffset=o,d.destinationStride=d.sourceWidthBytes;const u=d.destinationStride*d.sourceHeight+d.destinationOffset;if(u>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(u),o=Math.max(o,u);for(let t=0;t<h;t++){const e=s[t];if(!(a[h]<=e.destinationOffset||a[t]<=d.destinationOffset))throw new TypeError("Planes overlap.")}s.push(d)}return{allocationSize:o,computedLayouts:s}},Ke=/* @__PURE__ */new Map,Ze=(t,e)=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding options must be an object.");if(void 0!==e.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const i=e.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==e.latencyMode&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==e.fullCodecString&&"string"!=typeof e.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==e.fullCodecString&&((r=e.fullCodecString).startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":"vp8"===r?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":$t.includes(r)?"prores":"mp3"===r||"mp4a.69"===r||"mp4a.6B"===r||"mp4a.6b"===r||"mp4a.40.34"===r?"mp3":r.startsWith("mp4a.40.")||"mp4a.67"===r?"aac":"opus"===r?"opus":"vorbis"===r?"vorbis":"flac"===r?"flac":"ac-3"===r||"ac3"===r?"ac3":"ec-3"===r||"eac3"===r?"eac3":"ulaw"===r?"ulaw":"alaw"===r?"alaw":Dt.test(r)?r:"webvtt"===r?"webvtt":null)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);var r;if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==e.contentHint&&"string"!=typeof e.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},ti=t=>{const e=t.bitrateMode,i=t.quality.vt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Ut(t.codec,t.width,t.height,r,"keep"===t.alpha),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:i,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(n=t.codec,"avc"===n?{avc:{format:"avc"}}:"hevc"===n?{hevc:{format:"hevc"}}:{})};var n},n=[];return null!==i.quantizer&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),S(n.length>0),n},ei=class{constructor(t){if("number"!=typeof t&&"string"!=typeof t||(t={quality:t}),!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if("string"==typeof t.quality?!(t.quality in ii):"number"!=typeof t.quality||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(void 0!==t.preferBitrate&&"boolean"!=typeof t.preferBitrate)throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this.gt="string"==typeof t.quality?ii[t.quality]:t.quality,this.xt=t.preferBitrate??!1,this.Et=void 0,this.kt=void 0}else{if(void 0!==t.bitrate&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==t.quantizer&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===t.bitrate&&void 0===t.quantizer)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this.gt=void 0,this.xt=!1,this.Et=t.bitrate,this.kt=t.quantizer}this.Tt=t.bitrateMode}vt(t,e,i,r){const n=ri[t];let o=null,s=this.Tt??r??"variable";if(void 0!==this.kt){if(n)if(this.kt<n.min||this.kt>n.max){if(void 0===this.Et)throw new Error(`Quantizer ${this.kt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.kt,void 0===this.Et&&(s="quantizer");else if(void 0===this.Et)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this.Et&&n&&!this.xt&&(S(void 0!==this.gt),o=Y(Math.round((a=n.worst)+(n.best-a)*this.gt),n.min,n.max));var a;let h;if(void 0!==this.Et)h=this.Et;else{let r=this.gt;void 0===r&&(S(null!==o&&n),r=Y((o-n.worst)/(n.best-n.worst),0,1)),h=oi(t,e,i,ni(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Mt(t,e,i){return void 0!==this.Et?this.Et:(S(void 0!==this.gt),oi(t,e,i,ni(this.gt)))}_t(t){if(_t.includes(t)||"flac"===t)return;if(void 0!==this.Et)return this.Et;if(void 0===this.gt)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const e=ni(this.gt),i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[t];if(!i)throw new Error(`Unhandled codec: ${t}`);let r=i*e;return"aac"===t?r=[96e3,128e3,16e4,192e3].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t):"opus"===t||"vorbis"===t?r=Math.max(6e3,r):"mp3"===t&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t)),1e3*Math.round(r/1e3)}},ii={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},ri={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},ni=t=>.3*Math.exp(2.5538*t),oi=(t,e,i,r)=>{const n=e*i,o=3e6*Math.pow(n/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333}[t]*r;return 1e3*Math.ceil(o/1e3)},si=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void S(!1),ai=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!Mt.includes(t))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(void 0!==n&&!(n instanceof ei))throw new TypeError("quality, when provided, must be a Quality.");if(void 0!==n&&void 0!==o)throw new TypeError("quality and bitrate cannot both be provided.");if(void 0!==o&&!(o instanceof ei)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Ze(t,s);const a=hi(n,o)??new ei({bitrate:1e6});let h;try{h=ti({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=Ke.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(ci.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of h)if((await VideoEncoder.isConfigSupported(e)).supported){if(!rt())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?si(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Ke.set(c,d),d},hi=(t,e)=>void 0!==t?t:void 0!==e?e instanceof ei?e:new ei({bitrate:e}):void 0,ci=[],li=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,O(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},di=(t,e)=>{((t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)})(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},ui=class{constructor(t){this.mutex=new H,this.trackTimestampInfo=/* @__PURE__ */new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},fi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,pi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,mi=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")},wi=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);S(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}},bi=/* #__PURE__ */new Uint8Array(8),yi=/* #__PURE__ */new DataView(bi.buffer),vi=t=>[(t%256+256)%256],gi=t=>(yi.setUint16(0,t,!1),[bi[0],bi[1]]),xi=t=>(yi.setInt16(0,t,!1),[bi[0],bi[1]]),Ei=t=>(yi.setUint32(0,t,!1),[bi[1],bi[2],bi[3]]),ki=t=>(yi.setUint32(0,t,!1),[bi[0],bi[1],bi[2],bi[3]]),Ti=t=>(yi.setInt32(0,t,!1),[bi[0],bi[1],bi[2],bi[3]]),Mi=t=>(yi.setUint32(0,Math.floor(t/2**32),!1),yi.setUint32(4,t,!1),[bi[0],bi[1],bi[2],bi[3],bi[4],bi[5],bi[6],bi[7]]),_i=t=>(yi.setInt32(0,Math.floor(t/2**32),!1),yi.setUint32(4,t,!1),[bi[0],bi[1],bi[2],bi[3],bi[4],bi[5],bi[6],bi[7]]),Ci=t=>(yi.setInt16(0,256*t,!1),[bi[0],bi[1]]),Ai=t=>(yi.setInt32(0,65536*t,!1),[bi[0],bi[1],bi[2],bi[3]]),Si=t=>(yi.setInt32(0,2**30*t,!1),[bi[0],bi[1],bi[2],bi[3]]),Bi=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},Pi=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Ii=t=>{const e=t*(Math.PI/180),i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},Fi=/* #__PURE__ */Ii(0),$i=t=>[Ai(t[0]),Ai(t[1]),Si(t[2]),Ai(t[3]),Ai(t[4]),Si(t[5]),Ai(t[6]),Ai(t[7]),Si(t[8])],Vi=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),Ui=(t,e,i,r,n)=>Vi(t,[vi(e),Ei(i),r??[]],n),Oi=()=>Vi("styp",[Pi("iso5"),ki(0),Pi("iso5"),Pi("iso6"),Pi("mp41"),Pi("cmfc"),Pi("dash")]),Di=(t,e)=>{let i=t.maxWrittenEndTimestamp-t.minWrittenTimestamp;return Number.isFinite(i)||(i=0),Ui("sidx",1,0,[ki(1),ki(cn),Mi(dn(t.minWrittenTimestamp,cn)),Mi(0),gi(0),gi(1),ki(2147483647&e),ki(dn(i,cn)),ki(0)])},Ni=t=>({type:"mdat",largeSize:t}),Ri=t=>Vi("moov",void 0,[zi(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Li(e,t.creationTime)),t.isFragmented?_r(t.trackDatas):null,Nr(t)]),zi=(t,e)=>{const i=Math.max(0,...e.map(t=>dn(ji(t),cn)+dn(t.startTimestampOffset??0,cn))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!F(t)||!F(i),o=n?Mi:ki;return Ui("mvhd",+n,0,[o(t),o(t),ki(cn),o(i),Ai(1),Ci(1),Array(10).fill(0),$i(Fi),Array(24).fill(0),ki(r)])},ji=t=>{if(0===t.samples.length)return 0;let e=1/0,i=-1/0;for(let r=0;r<t.samples.length;r++){const n=t.samples[r];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>i&&(i=n.timestamp+n.duration)}return e===1/0?0:i-e},Li=(t,e)=>{const i=ln(t),r=null!==t.startTimestampOffset&&t.startTimestampOffset>0;return Vi("trak",void 0,[Hi(t,e),r?Gi(t,t.startTimestampOffset):null,qi(t,e),void 0!==i.name?Vi("udta",void 0,[Vi("name",[...D.encode(i.name)])]):null])},Hi=(t,e)=>{const i=dn(ji(t),cn)+dn(t.startTimestampOffset??0,cn),r=!F(e)||!F(i),n=r?Mi:ki;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=Ii(e??0)}else o=Fi;let s=2;!1!==t.track.metadata.disposition?.default&&(s|=1);const a="video"===t.type?0:"audio"===t.type?1:"subtitle"===t.type?2:W(t);return Ui("tkhd",+r,s,[n(e),n(e),ki(t.track.id),ki(0),n(i),Array(8).fill(0),gi(0),gi(a),Ci("audio"===t.type?1:0),gi(0),$i(o),Ai("video"===t.type?t.info.width:0),Ai("video"===t.type?t.info.height:0)])},Gi=(t,e)=>{const i=dn(e,cn),r=dn(ji(t),cn),n=!F(i)||!F(r),o=n?Mi:ki,s=n?_i:Ti;return Vi("edts",void 0,[Ui("elst",n?1:0,0,[ki(2),o(i),s(-1),Ai(1),o(r),s(0),Ai(1)])])},qi=(t,e)=>Vi("mdia",void 0,[Wi(t,e),Qi(!0,Xi[t.type],Yi[t.type]),Ji(t)]),Wi=(t,e)=>{const i=dn(ji(t),t.timescale),r=!F(e)||!F(i),n=r?Mi:ki;return Ui("mdhd",+r,0,[n(e),n(e),ki(t.timescale),n(i),gi(Zr(t.track.metadata.languageCode??"und")),gi(0)])},Xi={video:"vide",audio:"soun",subtitle:"text"},Yi={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Qi=(t,e,i,r="\0\0\0\0")=>Ui("hdlr",0,0,[t?Pi("mhlr"):ki(0),Pi(e),Pi(r),ki(0),ki(0),Pi(i,!0)]),Ji=t=>Vi("minf",void 0,[Ki[t.type](),Zi(),ir(t)]),Ki={video:()=>Ui("vmhd",0,1,[gi(0),gi(0),gi(0),gi(0)]),audio:()=>Ui("smhd",0,0,[gi(0),gi(0)]),subtitle:()=>Ui("nmhd",0,0)},Zi=()=>Vi("dinf",void 0,[tr()]),tr=()=>Ui("dref",0,0,[ki(1)],[er()]),er=()=>Ui("url ",0,1),ir=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return Vi("stbl",void 0,[rr(t),vr(t),e?Tr(t):null,e?Mr(t):null,xr(t),Er(t),kr(t),gr(t)])},rr=t=>{let e;if("video"===t.type)e=nr(Wr(t.track.source.Ct,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Yr(t.track.source.Ct,t.muxer.isQuickTime);S(i),e=hr(i,t)}else"subtitle"===t.type&&(e=yr(Jr[t.track.source.Ct],t));return S(e),Ui("stsd",0,0,[ki(1)],[e])},nr=(t,e)=>Vi(t,[Array(6).fill(0),gi(1),gi(0),gi(0),Array(12).fill(0),gi(e.info.width),gi(e.info.height),ki(4718592),ki(4718592),ki(0),gi(1),vi(10),Pi("Mediabunny"),Array(21).fill(0),gi(e.info.hasAlphaChannel?32:24),xi(65535)],[Xr[e.track.source.Ct]?.(e)??null,or(e),j(e.info.decoderConfig.colorSpace)?sr(e):null]),or=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:Vi("pasp",[ki(t.info.pixelAspectRatio.num),ki(t.info.pixelAspectRatio.den)]),sr=t=>Vi("colr",[Pi(t.muxer.isQuickTime?"nclc":"nclx"),gi(N[t.info.decoderConfig.colorSpace.primaries]),gi(R[t.info.decoderConfig.colorSpace.transfer]),gi(z[t.info.decoderConfig.colorSpace.matrix]),t.muxer.isQuickTime?[]:vi((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),ar=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),s=i[5]?Number(i[5]):e.colorSpace?.primaries?N[e.colorSpace.primaries]:2,a=i[6]?Number(i[6]):e.colorSpace?.transfer?R[e.colorSpace.transfer]:2,h=i[7]?Number(i[7]):e.colorSpace?.matrix?z[e.colorSpace.matrix]:2;return Ui("vpcC",1,0,[vi(r),vi(n),vi(o),vi(s),vi(a),vi(h),gi(0)])},hr=(t,e)=>{let i,r=0,n=16;const o=_t.includes(e.track.source.Ct);if(o){const t=e.track.source.Ct,{sampleSize:i}=Nt(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),gi(1),gi(r),gi(0),ki(0),gi(e.info.numberOfChannels),gi(n),gi(0),gi(0),gi(e.info.sampleRate<65536?e.info.sampleRate:0),gi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),gi(1),gi(r),gi(0),ki(0),gi(e.info.numberOfChannels),gi(Math.min(n,16)),xi(t),gi(0),gi(e.info.sampleRate<65536?e.info.sampleRate:0),gi(0),o?[ki(1),ki(n/8),ki(e.info.numberOfChannels*n/8)]:[ki(0),ki(0),ki(0)],ki(2)]}return Vi(t,i,[Qr(e.track.source.Ct,e.muxer.isQuickTime)?.(e)??null])},cr=t=>{let e;switch(t.track.source.Ct){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source.Ct}`)}let i=[...vi(e),...vi(21),...Ei(0),...ki(0),...ki(0)];if(t.info.decoderConfig.description){const e=U(t.info.decoderConfig.description);i=[...i,...vi(5),...Bi(e.byteLength),...e]}return i=[...gi(1),...vi(0),...vi(4),...Bi(i.length),...i,...vi(6),...vi(1),...vi(2)],i=[...vi(3),...Bi(i.length),...i],Ui("esds",0,0,i)},lr=t=>Vi("wave",void 0,[dr(t),ur(t),Vi("\0\0\0\0")]),dr=t=>Vi("frma",[Pi(Yr(t.track.source.Ct,t.muxer.isQuickTime))]),ur=t=>{const{littleEndian:e}=Nt(t.track.source.Ct);return Vi("enda",[gi(+e)])},fr=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=/* @__PURE__ */new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){S(a.byteLength>=18);const t=fe(U(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return Vi("dOps",[vi(0),vi(e),gi(i),ki(r),xi(n),vi(o),...s])},pr=t=>{const e=t.info.decoderConfig?.description;S(e);const i=U(e);return Ui("dfLa",0,0,[...i.subarray(4)])},mr=t=>{const{littleEndian:e,sampleSize:i}=Nt(t.track.source.Ct);return Ui("pcmC",0,0,[vi(+e),vi(8*i)])},wr=t=>{const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new xt(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=/* @__PURE__ */new Uint8Array(3),r=new xt(i);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),Vi("dac3",[...i])},br=t=>{const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new xt(t);e.skipBits(16);const i=e.readBits(2);if(e.skipBits(3),0!==i&&2!==i)return null;const r=e.readBits(11),n=e.readBits(2);let o,s=0;3===n?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),h=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const l=me[o];let d;return d=n<3?Yt[n]/1e3:Qt[s]/1e3,{dataRate:Math.round((r+1)*d/(16*l)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:h,numDepSub:0,chanLoc:0}]}})(t.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let i=16;for(const s of e.substreams)i+=23,s.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),n=new Uint8Array(r),o=new xt(n);o.writeBits(13,e.dataRate),o.writeBits(3,e.substreams.length-1);for(const s of e.substreams)o.writeBits(2,s.fscod),o.writeBits(5,s.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,s.bsmod),o.writeBits(3,s.acmod),o.writeBits(1,s.lfeon),o.writeBits(3,0),o.writeBits(4,s.numDepSub),s.numDepSub>0?o.writeBits(9,s.chanLoc):o.writeBits(1,0);return Vi("dec3",[...n])},yr=(t,e)=>Vi(t,[Array(6).fill(0),gi(1)],[Kr[e.track.source.Ct](e)]),vr=t=>Ui("stts",0,0,[ki(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[ki(t.sampleCount),ki(t.sampleDelta)])]),gr=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return Ui("stss",0,0,[ki(e.length),e.map(([t])=>ki(t+1))])},xr=t=>Ui("stsc",0,0,[ki(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[ki(t.firstChunk),ki(t.samplesPerChunk),ki(1)])]),Er=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=Nt(t.track.source.Ct);return Ui("stsz",0,0,[ki(e*t.info.numberOfChannels),ki(t.samples.reduce((e,i)=>e+dn(i.duration,t.timescale),0))])}return Ui("stsz",0,0,[ki(0),ki(t.samples.length),t.samples.map(t=>ki(t.size))])},kr=t=>t.finalizedChunks.length>0&&I(t.finalizedChunks).offset>=2**32?Ui("co64",0,0,[ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>Mi(t.offset))]):Ui("stco",0,0,[ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>ki(t.offset))]),Tr=t=>Ui("ctts",1,0,[ki(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[ki(t.sampleCount),Ti(t.sampleCompositionTimeOffset)])]),Mr=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;S(t.compositionTimeOffsetTable.length>0),S(t.samples.length>0);for(let s=0;s<t.compositionTimeOffsetTable.length;s++){const r=t.compositionTimeOffsetTable[s];e=Math.min(e,r.sampleCompositionTimeOffset),i=Math.max(i,r.sampleCompositionTimeOffset)}for(let s=0;s<t.samples.length;s++){const e=t.samples[s];r=Math.min(r,dn(e.timestamp,t.timescale)),n=Math.max(n,dn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:Ui("cslg",0,0,[Ti(o),Ti(e),Ti(i),Ti(r),Ti(n)])},_r=t=>Vi("mvex",void 0,t.map(Cr)),Cr=t=>Ui("trex",0,0,[ki(t.track.id),ki(1),ki(0),ki(0),ki(0)]),Ar=(t,e)=>Vi("moof",void 0,[Sr(t),...e.map(Pr)]),Sr=t=>Ui("mfhd",0,0,[ki(t)]),Br=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},Pr=t=>Vi("traf",void 0,[Ir(t),Fr(t),$r(t)]),Ir=t=>{S(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Br(i)};return Ui("tfhd",0,131128,[ki(t.track.id),ki(r.duration),ki(r.size),ki(r.flags)])},Fr=t=>(S(t.currentChunk),Ui("tfdt",1,0,[Mi(dn(t.currentChunk.startTimestamp,t.timescale))])),$r=t=>{S(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(Br),n=t.currentChunk.samples.map(e=>dn(e.timestamp-e.decodeTimestamp,t.timescale)),o=new Set(e),s=new Set(i),a=new Set(r),h=new Set(n),c=2===a.size&&r[0]!==r[1],l=o.size>1,d=s.size>1,u=!c&&a.size>1,f=h.size>1||[...h].some(t=>0!==t);let p=0;return p|=1,p|=4*+c,p|=256*+l,p|=512*+d,p|=1024*+u,p|=2048*+f,Ui("trun",1,p,[ki(t.currentChunk.samples.length),ki(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?ki(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?ki(e[o]):[],d?ki(i[o]):[],u?ki(r[o]):[],f?Ti(n[o]):[]])])},Vr=(t,e)=>Ui("tfra",1,0,[ki(t.track.id),ki(63),ki(t.finalizedChunks.length),t.finalizedChunks.map(i=>[Mi(dn(i.samples[0].timestamp,t.timescale)),Mi(i.moofOffset),ki(e+1),ki(1),ki(1)])]),Ur=()=>Vi("vtte"),Or=(t,e,i,r,n)=>Vi("vttc",void 0,[null!==n?Vi("vsid",[Ti(n)]):null,null!==i?Vi("iden",[...D.encode(i)]):null,null!==e?Vi("ctim",[...D.encode(mi(e))]):null,null!==r?Vi("sttg",[...D.encode(r)]):null,Vi("payl",[...D.encode(t)])]),Dr=t=>Vi("vtta",[...D.encode(t)]),Nr=t=>{const e=[],i=t.format.At.metadataFormat??"auto",r=t.output.St;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=Hr(r);t&&e.push(t)}else if("mdta"===i){const t=Gr(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&Rr(e,t.output.St);return 0===e.length?null:Vi("udta",void 0,e)},Rr=(t,e)=>{for(const{key:i,value:r}of ht(e))switch(i){case"title":t.push(zr("©nam",r));break;case"description":t.push(zr("©des",r));break;case"artist":t.push(zr("©ART",r));break;case"album":t.push(zr("©alb",r));break;case"albumArtist":t.push(zr("albr",r));break;case"genre":t.push(zr("©gen",r));break;case"date":t.push(zr("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(zr("©cmt",r));break;case"lyrics":t.push(zr("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:W(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(zr(i,r)):r instanceof Uint8Array&&t.push(Vi(i,Array.from(r))))}},zr=(t,e)=>{const i=D.encode(e);return Vi(t,[gi(i.length),gi(Zr("und")),Array.from(i)])},jr={"image/jpeg":13,"image/png":14,"image/bmp":27},Lr=(t,e)=>{const i=[];for(const{key:r,value:n}of ht(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:qr(n)});break;case"description":i.push({key:e?"description":"©des",value:qr(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:qr(n)});break;case"album":i.push({key:e?"album":"©alb",value:qr(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:qr(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:qr(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:qr(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:qr(n)});break;case"date":i.push({key:e?"date":"©day",value:qr(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:Vi("data",[ki(jr[t.mimeType]??0),ki(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:qr(e)})}else i.push({key:"trkn",value:Vi("data",[ki(0),ki(0),gi(0),gi(n),gi(t.tracksTotal??0),gi(0)])});break;case"discNumber":e||i.push({key:"disc",value:Vi("data",[ki(0),ki(0),gi(0),gi(n),gi(t.discsTotal??0),gi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:W(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];null==n||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof n?i.push({key:r,value:qr(n)}):n instanceof Uint8Array?i.push({key:r,value:Vi("data",[ki(0),ki(0),Array.from(n)])}):n instanceof vt&&i.push({key:r,value:Vi("data",[ki(jr[n.mimeType]??0),ki(0),Array.from(n.data)])}))}return i},Hr=t=>{const e=Lr(t,!1);return 0===e.length?null:Ui("meta",0,0,void 0,[Qi(!1,"mdir","","appl"),Vi("ilst",void 0,e.map(t=>Vi(t.key,void 0,[t.value])))])},Gr=t=>{const e=Lr(t,!0);return 0===e.length?null:Vi("meta",void 0,[Qi(!1,"mdta",""),Ui("keys",0,0,[ki(e.length)],e.map(t=>Vi("mdta",[...D.encode(t.key)]))),Vi("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...ki(e+1));return Vi(i,void 0,[t.value])}))])},qr=t=>Vi("data",[ki(1),ki(0),...D.encode(t)]),Wr=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Xr={avc:t=>t.info.decoderConfig&&Vi("avcC",[...U(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&Vi("hvcC",[...U(t.info.decoderConfig.description)]),vp8:ar,vp9:ar,av1:t=>Vi("av1C",Ot(t.info.decoderConfig.codec)),prores:null},Yr=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Qr=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return cr;case"opus":return fr;case"flac":return pr;case"ac3":return wr;case"eac3":return br}if(e)switch(t){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return lr}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return mr}return null},Jr={webvtt:"wvtt"},Kr={webvtt:t=>Vi("vttC",[...D.encode(t.info.config.description)])},Zr=t=>{S(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},tn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Bt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.Pt(e),t.Bt=!0}start(){S(!this.started),this.target.It(),this.started=!0}write(t){S(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.Ft(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return S(this.started&&!this.finalized),this.target.$t()}async finalize(){S(this.started&&!this.finalized),await this.target.Vt(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},en=(Ae(),class extends pt{constructor(){super(...arguments),this.Bt=!1,this.Ut=null,this.onwrite=null}Pt(t){!1!==this.Ut&&(this.Ut=t)}Ot(t,e){this.onwrite?.(t,e),this.it("write",{start:t,end:e})}slice(t){if(!Number.isInteger(t)||t<0)throw new TypeError("offset must be a non-negative integer.");return new an(this,t)}}),rn=65536,nn=2**32,on=class extends en{constructor(t={}){if(super(),this.buffer=null,this.Dt=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.At=t,this.Nt="resize"in/* @__PURE__ */new ArrayBuffer(0),this.Nt)try{this.Rt=new ArrayBuffer(rn,{maxByteLength:nn})}catch{this.Rt=new ArrayBuffer(rn),this.Nt=!1}else this.Rt=new ArrayBuffer(rn);this.zt=new Uint8Array(this.Rt)}jt(t){let e=this.Rt.byteLength;for(;e<t;)e*=2;if(e!==this.Rt.byteLength){if(e>nn)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.Nt)this.Rt.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.zt,0),this.Rt=t,this.zt=i}}}It(){}Ft(t,e){this.jt(e+t.byteLength),this.zt.set(t,e),this.Dt=Math.max(this.Dt,e+t.byteLength),this.Ot(e,e+t.byteLength)}async $t(){}async Vt(){this.buffer=this.Rt.slice(0,this.Dt),this.At.onFinalize&&await this.At.onFinalize(this.buffer),this.it("finalized")}async Lt(){}Ht(t,e){return this.zt.slice(t,e)}},sn=class extends en{constructor(t,e={}){if(super(),this.Gt=[],this.qt=0,this.Wt=0,this.Xt=null,this.Yt=null,this.Qt=[],!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this.Jt=t,this.At=e,this.Kt=e.chunked??!1,this.Zt=e.chunkSize??16777216}It(){this.Xt=this.Jt.getWriter()}Ft(t,e){if(e>this.qt){const t=e-this.qt;this.Ft(new Uint8Array(t),this.qt)}this.Gt.push({data:t.slice(),start:e}),this.qt=Math.max(this.qt,e+t.byteLength),this.Ot(e,e+t.byteLength)}async $t(){if(null!==this.Yt)throw this.Yt;if(S(this.Xt),0===this.Gt.length)return;const t=[],e=[...this.Gt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Gt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.Xt.desiredSize&&this.Xt.desiredSize<=0&&await this.Xt.ready,this.Kt)this.te(i.data,i.start),this.ee();else{if(!0===this.Ut&&i.start!==this.Wt)throw new Error("Internal error: Monotonicity violation.");this.Xt.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.Yt??=t}),this.Wt=i.start+i.data.byteLength}}this.Gt.length=0}te(t,e){let i=this.Qt.findIndex(t=>t.start<=e&&e<t.start+this.Zt);-1===i&&(i=this.ie(e));const r=this.Qt[i],n=e-r.start,o=t.subarray(0,Math.min(this.Zt-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.re(r,s),0===r.written[0].start&&r.written[0].end===this.Zt&&(r.shouldFlush=!0),this.Qt.length>2){for(let t=0;t<this.Qt.length-1;t++)this.Qt[t].shouldFlush=!0;this.ee()}o.byteLength<t.byteLength&&this.te(t.subarray(o.byteLength),e+o.byteLength)}re(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){const o=Math.floor(i+(r-i+1)/2);t.written[o].start<=e.start?(i=o+1,n=o):r=o-1}for(t.written.splice(n+1,0,e),(-1===n||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)}ie(t){const e={start:Math.floor(t/this.Zt)*this.Zt,data:new Uint8Array(this.Zt),written:[],shouldFlush:!1};return this.Qt.push(e),this.Qt.sort((t,e)=>t.start-e.start),this.Qt.indexOf(e)}ee(t=!1){S(this.Xt);for(let e=0;e<this.Qt.length;e++){const i=this.Qt[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Ut&&e!==this.Wt)throw new Error("Internal error: Monotonicity violation.");this.Xt.write({type:"write",data:i.data.subarray(t.start,t.end),position:e}).catch(t=>{this.Yt??=t}),this.Wt=i.start+t.end}this.Qt.splice(e--,1)}}}async Vt(){if(this.Kt&&this.ee(!0),null!==this.Yt)throw this.Yt;S(this.Xt),await this.Xt.ready,await this.Xt.close(),this.it("finalized")}async Lt(){return this.Xt?.close()}},an=class extends en{constructor(t,e){super(),this.ne=t,this.oe=e}It(){}Ft(t,e){this.ne.Ft(t,this.oe+e),this.Ot(e,e+t.byteLength)}$t(){return this.ne.$t()}async Vt(){this.it("finalized")}async Lt(){}Pt(t){super.Pt(t),this.ne.Pt(t)}},hn=class{constructor(t,e){if(this.rootPath=t,this.getTarget=e,"string"!=typeof t)throw new TypeError("rootPath must be a string.");if("function"!=typeof e)throw new TypeError("getTarget must be a function.")}},cn=57600,ln=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},dn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},un=class extends ui{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new on,this.auxWriter=new tn(this.auxTarget,!1),this.auxBoxWriter=new wi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=q(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=e,this.isQuickTime=e instanceof In,this.isCmaf=e instanceof Pn,this.minimumFragmentDuration=e.At.minimumFragmentDuration??(e instanceof Pn?1/0:1),this.auxWriter.start()}async start(){const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output.se(t=>void 0!==this.format.At.fastStart?"fragmented"===this.format.At.fastStart:t instanceof on),this.boxWriter=new wi(this.writer),this.fastStart=this.format.At.fastStart??(this.writer.target instanceof on&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output.ae())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const t=new tn(await this.output.he(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new wi(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.Ct);{const t=this.initBoxWriter??this.boxWriter;if(S(t),this.format.At.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return Vi("ftyp",t.isQuickTime?[Pi("qt "),ki(e),Pi("qt ")]:t.fragmented?t.cmaf?[Pi("iso5"),ki(e),Pi("iso5"),Pi("iso6"),Pi("mp41"),Pi("cmfc"),Pi("dash")]:[Pi("iso5"),ki(e),Pi("iso5"),Pi("iso6"),Pi("mp41")]:[Pi("isom"),ki(e),Pi("isom"),t.holdsAvc?Pi("avc1"):[],Pi("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format.At.onFtyp){const{data:e,start:i}=t.writer.stopTrackingWrites();this.format.At.onFtyp(e,i)}this.ftypSize=t.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output.tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(S(this.writer),S(this.boxWriter),this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ni(!0),this.boxWriter.writeBox(this.mdat));await(this.writer?.flush()),t()}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ct]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings)].join(", ")}"`),e})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Gt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};S(void 0!==n.codedWidth),S(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.Ct||n.description){if("hevc"===t.source.Ct&&!n.description){const t=(t=>{try{const e=[],i=[],r=[],n=[];for(const h of Kt(t)){const o=t.subarray(h.offset,h.offset+h.length),s=ne(o[0]);s===yt.VPS_NUT?e.push(o):s===yt.SPS_NUT?i.push(o):s===yt.PPS_NUT?r.push(o):s!==yt.PREFIX_SEI_NUT&&s!==yt.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new xt(ee(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:h,general_level_idc:c}=oe(e,i);$(e);const l=$(e);let d=0;3===l&&(d=e.readBits(1));const u=$(e),f=$(e);let p=u,m=f;if(e.readBits(1)){const t=$(e),i=$(e),r=$(e),n=$(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}const w=$(e),b=$(e);$(e);const y=e.readBits(1)?0:i;let v=0;for(let t=y;t<=i;t++)$(e),v=$(e),$(e);$(e),$(e),$(e),$(e),$(e),$(e),e.readBits(1)&&e.readBits(1)&&se(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),$(e),$(e),e.skipBits(1));const g=$(e);if(ae(e,g),e.readBits(1)){const t=$(e);for(let i=0;i<t;i++)$(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,k=2,T=0,M=0,_={num:1,den:1};if(e.readBits(1)){const t=ce(e,i);_=t.pixelAspectRatio,x=t.colourPrimaries,E=t.transferCharacteristics,k=t.matrixCoefficients,T=t.fullRangeFlag,M=t.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:_,colourPrimaries:x,transferCharacteristics:E,matrixCoefficients:k,fullRangeFlag:T,maxDecFrameBuffering:v+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:h,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:M}}catch(e){return wt.st("Error parsing HEVC SPS:",e),null}})(i[0]);if(!o)return null;let s=0;if(r.length>0){const t=r[0],e=new xt(ee(t));e.skipBits(16),$(e),$(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),$(e),$(e),V(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&$(e),V(e),V(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),n=e.readBits(1);s=i||n?i&&!n?2:!i&&n?3:0:0}const a=[...e.length?[{arrayCompleteness:1,nalUnitType:yt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:yt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:yt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ne(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:s,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:a}}catch(e){return wt.st("Error building HEVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)})(t),o=!0}}else{const t=(t=>{try{const e=[],i=[],r=[];for(const s of Kt(t)){const n=t.subarray(s.offset,s.offset+s.length),o=te(n[0]);o===bt.SPS?e.push(n):o===bt.PPS?i.push(n):o===bt.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=new xt(ee(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),n=e.readAlignedByte();$(e);let o=1,s=0,a=0,h=0;if((100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i)&&(o=$(e),3===o&&(h=e.readBits(1)),s=$(e),a=$(e),e.skipBits(1),e.readBits(1)))for(let t=0;t<(3!==o?8:12);t++)if(e.readBits(1)){const i=t<6?16:64;let r=8,n=8;for(let t=0;t<i;t++)0!==n&&(n=(r+V(e)+256)%256),r=0===n?r:n}$(e);const c=$(e);if(0===c)$(e);else if(1===c){e.skipBits(1),V(e),V(e);const t=$(e);for(let i=0;i<t;i++)V(e)}$(e),e.skipBits(1);const l=$(e),d=$(e),u=16*(l+1),f=16*(d+1);let p=u,m=f;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=$(e),i=$(e),r=$(e),n=$(e);let s,a;0===(0===h?o:0)?(s=1,a=2-w):(s=3===o?1:2,a=(1===o?2:1)*(2-w)),p-=s*(t+i),m-=a*(r+n)}let b=2,y=2,v=2,g=0,x={num:1,den:1},E=null,k=null;if(e.readBits(1)){if(e.readBits(1)){const t=e.readBits(8);if(255===t)x={num:e.readBits(16),den:e.readBits(16)};else{const e=ie[t];e&&(x=e)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),g=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),y=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&($(e),$(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&re(e);const i=e.readBits(1);i&&re(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),$(e),$(e),$(e),$(e),E=$(e),k=$(e))}if(null===E)if(S(null===k),(44===i||86===i||100===i||110===i||122===i||244===i)&&16&r)E=0,k=0;else{const t=l+1,e=(2-w)*(d+1),i=Bt.find(t=>t.level>=n)??I(Bt),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);E=r,k=r}return S(null!==k),{profileIdc:i,constraintFlags:r,levelIdc:n,frameMbsOnlyFlag:w,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:a,codedWidth:u,codedHeight:f,displayWidth:p,displayHeight:m,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:y,fullRangeFlag:g,numReorderFrames:E,maxDecFrameBuffering:k}}catch(e){return wt.st("Error parsing AVC SPS:",e),null}})(e[0]);S(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return wt.st("Error building AVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if(100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication){S(null!==t.chromaFormat),S(null!==t.bitDepthLumaMinus8),S(null!==t.bitDepthChromaMinus8),S(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)})(t),o=!0}const s=(t=>{const e=t<0?-1:1;let i=0,r=1,n=1,o=0,s=t=Math.abs(t);for(;;){const t=Math.floor(s),a=t*n+i,h=t*o+r;if(h>1e6)return{num:e*n,den:o};if(i=n,r=o,n=a,o=h,s=1/(s-t),!isFinite(s))break}return{num:e*n,den:o}})(1/(t.metadata.frameRate??57600)).den,a=n.displayAspectWidth,h=n.displayAspectHeight,c=void 0===a||void 0===h?{num:1,den:1}:dt({num:a*n.codedHeight,den:h*n.codedWidth}),l="ap4h"===n.codec||"ap4x"===n.codec,d={muxer:this,track:t,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:c,decoderConfig:n,requiresAnnexBTransformation:o,hasAlphaChannel:l},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Wt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ct&&!n.description){const t=Ce(li.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Et[t.samplingFrequencyIndex],r=kt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Tt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&_t.includes(t.source.Ct),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:e},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;Xt(e),S(e),S(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...Kt(n)].map(t=>n.subarray(t.offset,t.offset+t.length));if(0===t.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");n=(t=>{const e=t.reduce((t,e)=>t+4+e.byteLength,0),i=new Uint8Array(e);let r=0;for(const n of t){const t=new DataView(i.buffer,i.byteOffset,i.byteLength);t.setUint32(r,n.byteLength,!1),r+=4,i.set(n,r),r+=n.byteLength}return i})(t)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);const o=this.createSampleForTrack(r,n,e.timestamp,e.duration,e.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ce(li.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);let o=e.timestamp,s=e.duration;if(r.info.requiresPcmTransformation){const t=Nt(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(s=n.byteLength/t/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){const t=o-r.info.expectedNextPcmPacketTimestamp;if(t<.01)o=r.info.expectedNextPcmPacketTimestamp;else{const e=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,t);o=r.info.expectedNextPcmPacketTimestamp+e}}r.info.expectedNextPcmPacketTimestamp=o+s}const a=this.createSampleForTrack(r,n,o,s,e.type);await this.registerSample(r,a)}finally{r()}}async padWithSilence(t,e,i){const r=dn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=Nt(t.info.decoderConfig.codec),s=r*t.info.numberOfChannels,a=new Uint8Array(n*s).fill(o),h=this.createSampleForTrack(t,new Uint8Array(a.buffer),e,i,"key");await this.registerSample(t,h)}return i}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0),"webvtt"===t.source.Ct&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=/* @__PURE__ */new Set([]);for(const h of t.cueQueue)S(h.timestamp<=e),S(t.lastCueEndTimestamp<=h.timestamp+h.duration),i.add(Math.max(h.timestamp,t.lastCueEndTimestamp)),i.add(h.timestamp+h.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=Ur();this.auxBoxWriter.writeBox(e);const i=this.auxTarget.Ht(0,this.auxWriter.getPos()),r=this.createSampleForTrack(t,i,t.lastCueEndTimestamp,n-t.lastCueEndTimestamp,"key");await this.registerSample(t,r),t.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let e=0;e<t.cueQueue.length;e++){const i=t.cueQueue[e];if(i.timestamp>=o)break;fi.lastIndex=0;const r=fi.test(i.text),s=i.timestamp+i.duration;let a=t.cueToSourceId.get(i);if(void 0===a&&o<s&&(a=t.nextSourceId++,t.cueToSourceId.set(i,a)),i.notes){const t=Dr(i.notes);this.auxBoxWriter.writeBox(t)}const h=Or(i.text,r?n:null,i.identifier??null,i.settings??null,a??null);this.auxBoxWriter.writeBox(h),s===o&&t.cueQueue.splice(e--,1)}const s=this.auxTarget.Ht(0,this.auxWriter.getPos()),a=this.createSampleForTrack(t,s,n,o-n,"key");await this.registerSample(t,a),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:e,size:e.byteLength,type:n,timescaleUnitsToNextSample:dn(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp);let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=dn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):I(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented||(t.startTimestampOffset??=i[0]);for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=dn(e.timestamp-e.decodeTimestamp,t.timescale),o=dn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){S(t.lastSample);const i=dn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(S(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=I(t.timeToSampleTable);if(S(e),1===e.sampleCount){e.sampleDelta=r;const i=t.timeToSampleTable[t.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,t.timeToSampleTable.pop(),e=i)}else e.sampleDelta!==r&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:r}));e.sampleDelta===o?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=I(t.compositionTimeOffsetTable);S(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=dn(e.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));t.lastSample=e}if(t.timestampProcessingQueue.length=0,S(t.lastSample),S(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){S("key"===e.type);const i=dn(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if(S(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&n&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null}),S(t.currentChunk),t.currentChunk.samples.push(e),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,e.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,e.timestamp+e.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,e.timestamp))}async finalizeCurrentChunk(t){if(S(!this.isFragmented),S(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+dn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&I(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)S(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(S(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.sampleQueue.length&&!n.closed)break t;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(e=n,i=n.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!this.isCmaf){S(this.isFragmented);const e=this.nextFragmentNumber++;if(1===e){const t=this.initBoxWriter??this.boxWriter;S(t),this.format.At.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=Ri(this);if(t.writeBox(e),this.format.At.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.format.At.onMoov(e,i)}if(this.isCmaf){S(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.se(!0),this.boxWriter=new wi(this.writer);const t=this.boxWriter.measureBox(Oi()),e=this.boxWriter.measureBox(Di(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}S(this.writer),S(this.boxWriter);const i=this.trackDatas.filter(t=>t.currentChunk),r=Ar(e,i),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(const u of i){u.currentChunk.offset=s,u.currentChunk.moofOffset=n;for(const t of u.currentChunk.samples)s+=t.size;a=Math.min(a,u.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of i)u.currentChunk.offset+=8;this.format.At.onMoof&&this.writer.startTrackingWrites();const l=Ar(e,i);if(this.boxWriter.writeBox(l),this.format.At.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoof(t,e,a)}S(this.writer.getPos()===o),this.format.At.onMdat&&this.writer.startTrackingWrites();const d=Ni(c);d.size=h,this.boxWriter.writeBox(d),this.writer.seek(o+(c?16:8));for(const u of i)for(const t of u.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}for(const u of i)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){if(S(this.writer),S(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){this.ensureOneEnabledTrack();const t=Ri(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;S(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ni(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const t of i.sampleQueue)await this.addSampleToTrack(i,t);i.sampleQueue.length=0}}await this.addSampleToTrack(t,e)}else t.sampleQueue.push(e)}computeSampleTableSizeUpperBound(){S("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;S(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===t.source.Ct&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}ensureOneEnabledTrack(){for(const t of["video","audio","subtitle"]){const e=this.trackDatas.filter(e=>e.type===t);if(0!==e.length&&!e.some(t=>!1!==t.track.metadata.disposition?.default)){const t=e[0];t.track.metadata.disposition={...t.track.metadata.disposition,default:!0}}}}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source.Ct&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const i of this.trackDatas){await this.finalizeCurrentChunk(i),S(null!==i.startTimestampOffset);for(let t=0;t<i.samples.length;t++){const e=i.samples[t];e.timestamp-=i.startTimestampOffset,e.decodeTimestamp-=i.startTimestampOffset}}if(S(this.writer),S(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=Ni(!1);for(let i=0;i<2;i++){const e=Ri(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)S(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format.At.onMoov&&this.writer.startTrackingWrites();const e=Ri(this);if(this.boxWriter.writeBox(e),this.format.At.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoov(t,e)}this.format.At.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)S(t.data),this.writer.write(t.data),t.data=null;if(this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}}else if(this.isFragmented)if(this.isCmaf){const t=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Oi()),this.boxWriter.writeBox(Di(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,Vi("mfra",void 0,[...e.map(Vr),Ui("mfro",0,0,[ki(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{S(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);S(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.format.At.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMdat(t,e)}const i=Ri(this);if("reserve"===this.fastStart){S(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format.At.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.format.At.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format.At.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onMoov(t,e)}}var e;t()}},fn="Mediabunny",pn={video:1,audio:2,subtitle:17},mn=class extends ui{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=q(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.se(!!this.format.At.appendOnly),this.ebmlWriter=new Me(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format.At.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:pe.EBML,data:[{id:pe.EBMLVersion,data:1},{id:pe.EBMLReadVersion,data:1},{id:pe.EBMLMaxIDLength,data:4},{id:pe.EBMLMaxSizeLength,data:8},{id:pe.DocType,data:this.format instanceof $n?"webm":"matroska"},{id:pe.DocTypeVersion,data:2},{id:pe.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format.At.onEbmlHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onEbmlHeader(t,e)}}maybeCreateSeekHead(t){if(this.format.At.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),s={id:pe.SeekHead,data:[{id:pe.Seek,data:[{id:pe.SeekID,data:e},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:i},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:pe.Seek,data:[{id:pe.SeekID,data:r},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:n},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:pe.Seek,data:[{id:pe.SeekID,data:o},{id:pe.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:pe.Duration,data:new ve(0)};this.segmentDuration=t;const e={id:pe.Info,data:[{id:pe.TimestampScale,data:1e6},{id:pe.MuxingApp,data:fn},{id:pe.WritingApp,data:fn},this.format.At.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:pe.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){const i=_e[e.track.source.Ct];S(i);let r=0;if("audio"===e.type&&"opus"===e.track.source.Ct){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=fe(U(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:pe.TrackEntry,data:[{id:pe.TrackNumber,data:e.track.id},{id:pe.TrackUID,data:e.track.id},{id:pe.TrackType,data:pn[e.type]},!1===e.track.metadata.disposition?.default?{id:pe.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:pe.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:pe.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:pe.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:pe.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:pe.FlagCommentary,data:1}:null,{id:pe.FlagLacing,data:0},{id:pe.Language,data:e.track.metadata.languageCode??"und"},{id:pe.CodecID,data:i},e.codecPrivate?{id:pe.CodecPrivate,data:U(e.codecPrivate)}:null,{id:pe.CodecDelay,data:0},{id:pe.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:pe.Name,data:new xe(e.track.metadata.name)}:null,"video"===e.type?this.videoSpecificTrackInfo(e):null,"audio"===e.type?this.audioSpecificTrackInfo(e):null,"subtitle"===e.type?this.subtitleSpecificTrackInfo(e):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,rotation:i}=t.track.metadata,r=[e?{id:pe.DefaultDuration,data:1e9/e}:null],n=i?P(-i):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,s=t.info.decoderConfig.colorSpace,a={id:pe.Video,data:[{id:pe.PixelWidth,data:t.info.width},{id:pe.PixelHeight,data:t.info.height},o?{id:pe.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:pe.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:pe.DisplayUnit,data:3}:null,t.info.alphaMode?{id:pe.AlphaMode,data:1}:null,j(s)?{id:pe.Colour,data:[{id:pe.MatrixCoefficients,data:z[s.matrix]},{id:pe.TransferCharacteristics,data:R[s.transfer]},{id:pe.Primaries,data:N[s.primaries]},{id:pe.Range,data:s.fullRange?2:1}]}:null,n?{id:pe.Projection,data:[{id:pe.ProjectionType,data:0},{id:pe.ProjectionPoseRoll,data:new ye((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=_t.includes(t.track.source.Ct)?Nt(t.track.source.Ct):null;return[{id:pe.Audio,data:[{id:pe.SamplingFrequency,data:new ye(t.info.sampleRate)},{id:pe.Channels,data:t.info.numberOfChannels},e?{id:pe.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:pe.SimpleTag,data:[{id:pe.TagName,data:new xe(e)},"string"==typeof i?{id:pe.TagString,data:new xe(i)}:{id:pe.TagBinary,data:i}]})},i=this.output.St,r=/* @__PURE__ */new Set;for(const{key:n,value:o}of ht(i))switch(n){case"title":e("TITLE",o),r.add("TITLE");break;case"description":e("DESCRIPTION",o),r.add("DESCRIPTION");break;case"artist":e("ARTIST",o),r.add("ARTIST");break;case"album":e("ALBUM",o),r.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),r.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),r.add("GENRE");break;case"comment":e("COMMENT",o),r.add("COMMENT");break;case"lyrics":e("LYRICS",o),r.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":e("PART_NUMBER",void 0!==i.tracksTotal?`${o}/${i.tracksTotal}`:o.toString()),r.add("PART_NUMBER");break;case"discNumber":e("DISC",void 0!==i.discsTotal?`${o}/${i.discsTotal}`:o.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:W(n)}if(i.raw)for(const n in i.raw){const t=i.raw[n];null==t||r.has(n)||("string"==typeof t||t instanceof Uint8Array)&&e(n,t)}0!==t.length&&(this.tagsElement={id:pe.Tags,data:[{id:pe.Tag,data:[{id:pe.Targets,data:[{id:pe.TargetTypeValue,data:50},{id:pe.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.St,e=[],i=/* @__PURE__ */new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(ct(n.mimeType)??""));;){t=0n;for(let e=0;e<8;e++)t<<=8n,t|=BigInt(Math.floor(256*Math.random()));if(0n!==t&&!i.has(t))break}i.add(t),e.push({id:pe.AttachedFile,data:[void 0!==n.description?{id:pe.FileDescription,data:new xe(n.description)}:null,{id:pe.FileName,data:new xe(r)},{id:pe.FileMediaType,data:n.mimeType},{id:pe.FileData,data:n.data},{id:pe.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof gt&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&<(t.data,o.data))||e.push({id:pe.AttachedFile,data:[void 0!==o.description?{id:pe.FileDescription,data:new xe(o.description)}:null,{id:pe.FileName,data:new xe(o.name??"")},{id:pe.FileMediaType,data:o.mimeType??""},{id:pe.FileData,data:o.data},{id:pe.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:pe.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:pe.Segment,size:this.format.At.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format.At.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format.At.onSegmentHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onSegmentHeader(t,e)}}createCues(){this.cues={id:pe.Cues,data:[]}}get segmentDataOffset(){return S(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ct]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings.filter(Boolean))].join(", ")}"`),e})({isWebM:this.format instanceof $n,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Gt(i),S(i),S(i.decoderConfig),S(void 0!==i.decoderConfig.codedWidth),S(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:dt({num:n,den:o}),a={track:t,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:i.decoderConfig,alphaMode:!!e.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return"vp9"===t.source.Ct?a.codecPrivate=new Uint8Array((t=>{const e=t.split(".");return[1,1,Number(e[1]),2,1,Number(e[2]),3,1,Number(e[3]),4,1,e[4]?Number(e[4]):1]})(a.info.decoderConfig.codec)):"av1"===t.source.Ct?a.codecPrivate=new Uint8Array(Ot(a.info.decoderConfig.codec)):"prores"===t.source.Ct&&(a.codecPrivate=D.encode(i.decoderConfig.codec)),this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Wt(i),S(i),S(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ct&&!n.description){const t=Ce(li.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Et[t.samplingFrequencyIndex],r=kt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Tt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;Xt(e),S(e),S(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:D.encode(e.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if("prores"===t.source.Ct){if(n.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");n=n.subarray(8)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);let s=e.timestamp,a=e.duration;void 0!==t.metadata.frameRate&&(s=J(s,t.metadata.frameRate),a=J(a,t.metadata.frameRate));const h=r.info.alphaMode?e.sideData.alpha??null:null,c=this.createInternalChunk(n,s,a,e.type,h);"vp9"===t.source.Ct&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ce(li.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);const s=this.createInternalChunk(n,e.timestamp,e.duration,e.type);r.chunkQueue.push(s),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0);let n=e.text;const o=Math.round(1e3*e.timestamp);fi.lastIndex=0,n=n.replace(fi,t=>`<${mi((t=>{const e=pi.exec(t);if(!e)throw new Error("Expected match.");return 36e5*Number(e[1]||"0")+6e4*Number(e[2])+1e3*Number(e[3])+Number(e[4])})(t.slice(1,-1))-o)}>`);const s=D.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?D.encode(a):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{r()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.chunkQueue.length&&!n.closed)break t;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(e=n,i=n.chunkQueue[0].timestamp)}if(!e)break;const r=e.chunkQueue.shift();this.writeBlock(e,r)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if("key"!==e.type)return;if(!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new xt(e.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(3===n&&i.skipBits(1),i.readBits(1))return;if(0!==i.readBits(1))return;if(i.skipBits(2),4817730!==i.readBits(24))return;n>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((t,e,i,r)=>{for(let n=e;n<i;n++){const e=Math.floor(n/8);let o=t[e];const s=7-(7&n);o&=~(1<<s),o|=(r&1<<i-n-1)>>i-n-1<<s,t[e]=o}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,r,n=null){return{data:t,type:r,timestamp:e,duration:i,additions:n}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),r=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.closed});let n=!1;if(this.currentCluster){S(null!==this.currentClusterStartMsTimestamp),S(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.At.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const s=/* @__PURE__ */new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:pe.BlockGroup,data:[{id:pe.Block,data:[s,e.data]},"delta"===e.type?{id:pe.ReferenceBlock,data:new ge(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:pe.BlockAdditions,data:[{id:pe.BlockMore,data:[{id:pe.BlockAddID,data:1},{id:pe.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:pe.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:pe.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format.At.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:pe.Cluster,size:this.format.At.appendOnly?-1:5,data:[{id:pe.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(S(this.currentCluster),!this.format.At.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.At.onCluster){S(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=/* @__PURE__ */new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)S(this.cues),this.cues.data.push({id:pe.CuePoint,data:[{id:pe.CueTime,data:r},...n.map(e=>({id:pe.CueTrackPositions,data:[{id:pe.CueTrack,data:e.track.id},{id:pe.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),S(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.At.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new ve(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),S(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},wn=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},bn=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r}),yn=class{constructor(){this.ce=null,this.le=null,this.ut=!1}de(){if(!this.ce)throw new Error("Source is not connected to an output track.");if("canceled"===this.ce.output.state)throw new Error("Output has been canceled.");if("finalizing"===this.ce.output.state||"finalized"===this.ce.output.state)throw new Error("Output has been finalized.");if("pending"===this.ce.output.state)throw new Error("Output has not started.");if(this.ut)throw new Error("Source is closed.")}async It(){}async ue(t){}close(){if(this.le)return;const t=this.ce;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===t.output.state)throw new Error("Cannot call close before output has been started.");this.le=(async()=>{await this.ue(!1),this.ut=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output.fe.onTrackClose(t)})()}async pe(t){return this.le??=(async()=>{await this.ue(t),this.ut=!0})()}},vn=class extends yn{constructor(t){if(super(),this.ce=null,!Mt.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Mt.join(", ")}.`);this.Ct=t}},gn=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},xn=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new et,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.de();const n=this.encodingConfig,o=n.sizeChangeBehavior??"deny";let s=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(s=!0,"deny"===o))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(void 0!==n.transform?.width||void 0!==n.transform?.height||void 0!==n.transform?.rotate||void 0!==n.transform?.crop||!0===n.transform?.force||s&&"passThrough"!==o){let i=n.transform?.width,r=n.transform?.height,a=n.transform?.fit??"fill";s&&"passThrough"!==o&&(S(this.outputWidth),S(this.outputHeight),S("deny"!==o),i=this.outputWidth,r=this.outputHeight,a=o);const h=await t.transform({width:i,height:r,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:a,alpha:n.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const a=n.transform?.frameRate;if(void 0!==a){const n=t.timestamp+t.duration,o=K(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(e instanceof Promise&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof Ue?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new Ue(i)):o.push(new Ue(i,{timestamp:t.timestamp,duration:t.duration}))}catch(n){for(const e of o)e!==t&&e.close();for(const i of e)(i instanceof Ue&&i!==t||"undefined"!=typeof VideoFrame&&i instanceof VideoFrame)&&i.close();throw n}r=o}else r=[t];try{for(const t of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),S(this.encoderInitialized),this.closed)break;const i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(t.timestamp/i),n={...this.defaultEncodeOptions,...t.encodeOptions,...e},o={...n,keyFrame:void 0!==n.keyFrame?n.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,o)).catch(t=>this.setError(t)).finally(()=>{this.customEncoderQueueSize--,e.close()});this.customEncoderQueueSize>=4&&await i}else{S(this.encoder);const e=t.toVideoFrame(),i=G(this.preciseTimings,e.timestamp,t=>t.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===e.timestamp?(r.timestamp!==t.timestamp&&(r.timestampIsValid=!1),r.duration!==t.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:e.timestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(e.format&&!e.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(e,o)}finally{e.close()}}else{this.splitter||(this.splitter=new kn);const{colorFrame:t,alphaFrame:i}=await this.splitter.split(e);this.alphaFrameQueue.push(i);try{this.encoder.encode(t,o)}finally{t.close()}}else try{this.encoder.encode(e,o)}finally{e.close()}this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.lastMuxerPromise}}finally{for(const e of r)e!==t&&e.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;S(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=wn(t,this.frameRateLastSample.clone(),!1);r.setTimestamp(this.frameRateLastTimestamp+o/i),r.setDuration(1/i),await this.processAndEncode(r,e)}catch(n){t.error=n,t.hasError=!0}finally{bn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=hi(this.encodingConfig.quality,this.encodingConfig.bitrate);S(void 0!==e);const i=ti({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source.ce?.metadata.frameRate});let r,n=null;for(const t of i){const e=t.config;if(this.encodingConfig.onEncoderConfig?.(e),r=ci.find(t=>t.supports(this.encodingConfig.codec,e)),r){n=t;break}if("undefined"!=typeof VideoEncoder){if(e.alpha="discard","keep"===this.encodingConfig.alpha&&(e.latencyMode="quality"),!(e.width%2!=1&&e.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if((await VideoEncoder.isConfigSupported(e)).supported){n=t;break}}}if(!n){if("undefined"==typeof VideoEncoder)throw new Error("VideoEncoder is not supported by this browser.");const t=i[0].config,e=i.map(({config:t,quantizer:e})=>null!==e?`quantizer ${e}`:`${t.bitrate} bps`);throw new Error(`This specific encoder configuration (${t.codec}, ${e.join(" / ")}, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`)}const o=n.config;if(null!==n.quantizer&&(this.defaultEncodeOptions=si(this.encodingConfig.codec,n.quantizer)),r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(t,e)=>{if(!(t instanceof be))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");gn(this.source.ce,t),this.encodingConfig.onEncodedPacket?.(t,e),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ce,t,e).catch(t=>{this.setError(t)})},this.customEncoder.onError=t=>{this.setError(t)},await this.customEncoder.init();else{const t=[],e=[];let i=0,r=0;const n=(t,e,i)=>{const r={};if(e){const t=new Uint8Array(e.byteLength);e.copyTo(t),r.alpha=t}let n=be.fromEncodedChunk(t,r);const o=G(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&U(e.description)[4]);return Zt(t,i)}return Kt(t)})(i,e)){const e=i[t.offset],r=te(e);if(r>=bt.NON_IDR_SLICE&&r<=bt.SLICE_DPC)return"delta";if(r===bt.IDR)return"key";if(r===bt.SEI&&(!ot()||at()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=ee(e);let n=1;do{let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}if(6===t){const t=new xt(r);t.pos=8*n;const e=$(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&U(e.description)[21]);return Zt(t,i)}return Kt(t)})(i,e)){const e=ne(i[t.offset]);if(e<yt.BLA_W_LP)return"delta";if(e<=yt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new xt(i);if(2!==t.readBits(2))return null;const e=t.readBits(1);return(t.readBits(1)<<1)+e===3&&t.skipBits(1),t.readBits(1)?null:0===t.readBits(1)?"key":"delta"}case"av1":{let t=!1;for(const{type:e,data:r}of function*(t){const e=new xt(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return t>=2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);S(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}}(i))if(1===e){const e=new xt(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new xt(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:W(t),S(!1)}})(this.encodingConfig.codec,i.decoderConfig,n.data)),(s&&s.microsecondTimestamp===t.timestamp||null!==a)&&(n=n.clone({timestamp:s?.timestampIsValid?s.timestamp:void 0,duration:s?.durationIsValid?s.duration:void 0,type:a??void 0})),gn(this.source.ce,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ce,n,i).catch(t=>{this.setError(t)}),this.emittedEncoderPackets++},s=/* @__PURE__ */new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(o,s)=>{if(!this.alphaEncoder)return void n(o,null,s);const a=this.alphaFrameQueue.shift();S(void 0!==a),a?(this.alphaEncoder.encode(a,{...this.defaultEncodeOptions,keyFrame:"key"===o.type}),r++,a.close(),t.push({chunk:o,meta:s})):0===r?n(o,null,s):(e.push(i+r),t.push({chunk:o,meta:s}))},error:t=>{t.stack=s,this.setError(t)}}),this.encoder.configure(o),"keep"===this.encodingConfig.alpha){const s=/* @__PURE__ */new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(S(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();S(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=s,this.setError(t)}}),this.alphaEncoder.configure(o)}}S(this.source.ce),this.muxer=this.source.ce.output.fe,this.encoderInitialized=!0})()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=K(this.frameRateLastEndTimestamp,t);await this.padFrameRate(e)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await(this.alphaEncoder?.flush()),await new Promise(t=>setTimeout(t,25))))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},En=null,kn=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!En){const t=new Blob([`(${Tn.toString()})()`],{type:"application/javascript"});En=URL.createObjectURL(t)}this.worker=new Worker(En),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=q();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Tn=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",t=>{const{id:r,sourceFrame:n}=t.data;e=e.then(async()=>{try{const{colorFrame:t,alphaFrame:e}=await i(n);self.postMessage({id:r,colorFrame:t,alphaFrame:e},{transfer:[t,e]})}catch(t){self.postMessage({id:r,error:t.message})}finally{n.close()}})});const i=async e=>{const i=e.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=e.allocationSize();if(t&&t.byteLength===o||(t=new Uint8Array(o)),await e.copyTo(t),"RGBA"===i||"BGRA"===i)return r(t,i,e);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return n(t,i,e);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=r*n,s=o+Math.ceil(r/2)*Math.ceil(n/2)*2,a=new Uint8Array(s);for(let l=0,d=3;l<o;l++,d+=4)a[l]=t[d];a.fill(128,o);const h=new VideoFrame(t,{format:"RGBA"===e?"RGBX":"BGRX",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),c={format:"I420",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[a.buffer]};return{colorFrame:h,alphaFrame:new VideoFrame(a,c)}},n=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=e.includes("P10"),s=e.includes("P12"),a=o||s?2:1;let h,c;e.startsWith("I420")?(h=Math.ceil(r/2),c=Math.ceil(n/2)):e.startsWith("I422")?(h=Math.ceil(r/2),c=n):(h=r,c=n);const l=r*n,d=l*a,u=l*a+h*c*a*2,f=e.replace("A",""),p=Math.ceil(r/2)*Math.ceil(n/2),m=new Uint8Array(d+p*a*2),w=u;m.set(t.subarray(w,w+d),0);const b=d,y=o?512:s?2048:128;1===a?m.fill(y,b):new Uint16Array(m.buffer,b,2*p).fill(y);const v=o?"I420P10":s?"I420P12":"I420",g=new VideoFrame(t.subarray(0,u),{format:f,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),x={format:v,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[m.buffer]};return{colorFrame:g,alphaFrame:new VideoFrame(m,x)}}},Mn=class extends vn{constructor(t,e){if(!("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(t=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding config must be an object.");if(!Mt.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Mt.join(", ")}.`);const e=t.bitrate;if(void 0===t.quality&&void 0===e)throw new TypeError("config.quality must be provided.");if(void 0!==t.quality&&void 0!==e)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(void 0!==t.quality&&!(t.quality instanceof ei))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof ei)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==t.keyFrameInterval&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==t.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==t.transform){if("object"!=typeof t.transform||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==t.transform.width&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==t.transform.height&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==t.transform.fit&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.transform.width&&void 0!==t.transform.height&&void 0===t.transform.fit&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==t.transform.fit&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(void 0!==t.transform.rotate&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.transform.crop&&He(t.transform.crop,"config.transform."),void 0!==t.transform.process&&"function"!=typeof t.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.");if(void 0!==t.transform.frameRate&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==t.transform.force&&"boolean"!=typeof t.transform.force)throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(void 0!==t.onEncodedPacket&&"function"!=typeof t.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==t.onEncoderConfig&&"function"!=typeof t.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(void 0!==t.onEncodedSample&&"function"!=typeof t.onEncodedSample)throw new TypeError("config.onEncodedSample, when provided, must be a function.");Ze(t.codec,t)})(e),super(e.codec),this.me=new xn(this,e),this.we=t}add(t,e=0,i){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new Ue(this.we,{timestamp:t,duration:e});return this.me.add(r,!0,i)}ue(t){return this.me.flushAndClose(t)}},_n=class extends yn{constructor(t){if(super(),this.ce=null,!At.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${At.join(", ")}.`);this.Ct=t}},Cn=class extends yn{constructor(t){if(super(),this.ce=null,!St.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${St.join(", ")}.`);this.Ct=t}},An=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Mt.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>At.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>St.includes(t))}be(t){return""}},Sn=class extends An{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this.At=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:1,max:t}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}ye(t){return new un(t,this)}},Bn=class extends Sn{constructor(t){super(t)}get ve(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Mt,...Ct,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...St]}be(t){return(new In).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Pn=class extends Sn{constructor(t){super(t)}get ve(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Mt,...Ct,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...St]}},In=class extends Sn{constructor(t){super(t)}get ve(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Mt,...At]}be(t){return(new Bn).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Fn=class extends An{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.appendOnly&&"boolean"!=typeof t.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==t.minimumClusterDuration&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==t.onEbmlHeader&&"function"!=typeof t.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==t.onSegmentHeader&&"function"!=typeof t.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==t.onCluster&&"function"!=typeof t.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this.At=t}ye(t){return new mn(t,this)}get ve(){return"Matroska"}getSupportedTrackCounts(){const t=127;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:1,max:t}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Mt,...Ct,..._t.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...St]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},$n=class extends Fn{constructor(t){super(t)}getSupportedCodecs(){return[...Mt.filter(t=>["vp8","vp9","av1"].includes(t)),...At.filter(t=>["opus","vorbis"].includes(t)),...St]}get ve(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}be(t){return(new Fn).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},Vn=["video","audio","subtitle"],Un=class t{constructor(t,e,i,r,n){this.id=t,this.output=e,this.type=i,this.source=r,this.metadata=n}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=ft(this.metadata.group),r=ft(e.metadata.group);for(const t of i){if(this.type!==e.type&&r.some(e=>t===e))return!0;if(r.some(e=>t.ge.has(e)))return!0}return!1}},On=class extends Un{constructor(t,e,i,r){super(t,e,"video",i,r)}},Dn=class extends Un{constructor(t,e,i,r){super(t,e,"audio",i,r)}},Nn=class extends Un{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},Rn=class t{constructor(){this.ge=/* @__PURE__ */new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.ge.add(e),e.ge.add(this)}},zn=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&(e=t.languageCode,!Z.test(e)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var e;if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.group&&!(t.group instanceof Rn)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof Rn))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},jn=class extends pt{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.xe)throw new TypeError(t);const e=this.Ee();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Rn,this.tracks=[],this.ke=null,this.Te=/* @__PURE__ */new Set,this.Me=null,this._e=null,this.Ce=null,this.Ae=null,this.Se=new H,this.St={},this.Be=null,this.xe=null,this.Pe=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof An))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof en||t.target instanceof hn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof en&&this.Ie(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof en)&&"function"!=typeof t.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this.Fe=t.target,this.ke=t.onFinalize??null,this.$e=t.initTarget??null,this.$e instanceof en&&this.Ie(this.$e),this.fe=t.format.ye(this)}Ve(t){S(this.Fe instanceof hn);const e=this.Fe.getTarget(t),i=t=>{if(!(t instanceof en))throw new TypeError("getTarget must return a Target.");return t};return e instanceof Promise?e.then(i):i(e)}async Ue(t){S(this.Fe instanceof hn);const e=await this.Ve(t);return this.it("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Lt():this.Ie(e),e}Ie(t){this.Te.add(t),t.on("finalized",()=>this.Te.delete(t),{once:!0})}async he(){if(S(null!==this.$e),this.$e instanceof en)return this.$e;const t=await this.$e();return"canceled"===this.state?await t.Lt():this.Ie(t),t}ae(){return null!==this.$e}Ee(){if(this.Be)return this.Be;if(this.xe)return this.xe;if(this.Fe instanceof en)return this.it("target",{target:this.Fe,request:null,isRoot:!0}),this.Be=this.Fe,this.Fe;const t={path:this.Fe.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this.Ve(t),i=e=>("canceled"===this.state?e.Lt():this.Ie(e),this.it("target",{target:e,request:t,isRoot:!0}),this.Be=e,e);return e instanceof Promise?this.xe=e.then(i):i(e)}se(t){return this.Me??=(async()=>{const e=await this.Ee(),i=new tn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof vn))throw new TypeError("source must be a VideoSource.");if(zn(e),void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&e.rotation)throw new Error(`${this.format.ve} does not support video rotation metadata.`);if(void 0!==e.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);const i={...e};return i.group??=this.defaultTrackGroup,this.Oe(new On(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof _n))throw new TypeError("source must be an AudioSource.");zn(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Oe(new Dn(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Cn))throw new TypeError("source must be a SubtitleSource.");zn(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Oe(new Nn(this.tracks.length+1,this,t,i))}setMetadataTags(t){if((t=>{if(!t||"object"!=typeof t)throw new TypeError("tags must be an object.");if(void 0!==t.title&&"string"!=typeof t.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==t.description&&"string"!=typeof t.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==t.artist&&"string"!=typeof t.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==t.album&&"string"!=typeof t.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==t.albumArtist&&"string"!=typeof t.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==t.trackNumber&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==t.tracksTotal&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==t.discNumber&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==t.discsTotal&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==t.genre&&"string"!=typeof t.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==t.date&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==t.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||e instanceof Uint8Array||e instanceof vt||e instanceof gt||mt(e)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this.St=t}Oe(t){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t.source.ce)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((e,i)=>e+(i.type===t.type?1:0),0),r=e[t.type].max;if(i===r)throw new Error(0===r?`${this.format.ve} does not support ${t.type} tracks.`:`${this.format.ve} does not support more than ${r} ${t.type} track${1===r?"":"s"}.`);const n=e.total.max;if(this.tracks.length===n)throw new Error(`${this.format.ve} does not support more than ${n} tracks${1===n?"":"s"} in total.`);if(t.isVideoTrack()){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support video tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported video codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}else if(t.isAudioTrack()){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support audio tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported audio codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}else if(t.isSubtitleTrack()){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format.ve} does not support subtitle tracks.`+this.format.be(t.source.Ct));if(!e.includes(t.source.Ct))throw new Error(`Codec '${t.source.Ct}' cannot be contained within ${this.format.ve}. Supported subtitle codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.be(t.source.Ct))}return this.tracks.push(t),t.source.ce=t,t}hasEnoughTracks(){const t=this.format.getSupportedTrackCounts();for(const i of Vn)if(this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0)<t[i].min)return!1;const e=t.total.min;return!(this.tracks.length<e)}async start(){const t=this.format.getSupportedTrackCounts();for(const i of Vn){const e=this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0),r=t[i].min;if(e<r)throw new Error(r===t[i].max?`${this.format.ve} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format.ve} requires at least ${r} ${i} track${1===r?"":"s"}.`)}const e=t.total.min;if(this.tracks.length<e)throw new Error(e===t.total.max?`${this.format.ve} requires exactly ${e} track${1===e?"":"s"}.`:`${this.format.ve} requires at least ${e} track${1===e?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this._e?(wt.ht("Output has already been started."),this._e):this._e=(async()=>{this.state="started";const t=this.Se.acquire();try{await this.fe.start();const t=this.tracks.map(t=>t.source.It());await Promise.all(t)}finally{(await t)()}})()}getMimeType(){return this.fe.getMimeType()}async cancel(){return this.Ce?(wt.ht("Output has already been canceled."),this.Ce):"finalizing"!==this.state&&"finalized"!==this.state?this.Ce=(async()=>{this.state="canceled";const t=await this.Se.acquire();try{const t=this.tracks.map(t=>t.source.pe(!0));await Promise.all(t),await Promise.all([...this.Te].map(t=>t.Lt())),this.Te.clear()}finally{t()}})():void("finalized"===this.state&&wt.ht("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this.Ae?(wt.ht("Output has already been finalized."),this.Ae):this.Ae=(async()=>{this.state="finalizing";const t=await this.Se.acquire();try{const t=this.tracks.map(t=>t.source.pe(!1));if(await Promise.all(t),await this.fe.finalize(),this.Me){const t=await this.Me;t.finalized||(await t.flush(),await t.finalize())}this.ke&&await this.ke(),this.state="finalized"}finally{await Promise.all([...this.Te].map(t=>t.Lt().catch(()=>{}))),this.Te.clear(),t()}})()}},Ln={low:"medium",medium:"high",high:"very-high"},Hn=["low","medium","high","ultra"],Gn={medium:.3*Math.exp(1.2769),high:.3*Math.exp(2.5538*.75),"very-high":.3*Math.exp(2.5538)},qn={avc:1,vp9:.6,vp8:1.2};function Wn(t,e,i){const r=e/i;return Math.ceil(t*r*1.1/8+1e6)}function Xn(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new v("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new v("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);const n=t.bitrate,o="string"==typeof n&&Hn.includes(n)?n:null,s="ultra"===o?"ultra":o?"constant-quality":"bitrate",a="number"==typeof n&&Number.isFinite(n)&&n>0?Math.round(n):"ultra"===o?function(t,e,i){return Math.max(1e6,Math.round(t*e*i*.5))}(i,r,t.frameRate):function(t,e,i,r){const n=i*r,o=3e6*Math.pow(n/2073600,.95),s=qn[e]??1;return Math.max(25e4,1e3*Math.ceil(o*s*Gn[Ln[t]]/1e3))}(o??"medium",e,i,r),h=o&&"ultra"!==o?Ln[o]:void 0;return{format:t.format,extension:"mp4"===t.format?".mp4":".webm",mimeType:"mp4"===t.format?"video/mp4":"video/webm",codec:e,bitrate:a,bitrateMode:t.bitrateMode,qualityPreset:o,rateControlIntent:s,qualityLevel:h,contentHint:(c=t.contentHint,""===c||"motion"===c||"detail"===c||"text"===c?c:"text"),estimatedBytes:Wn(a,t.frameCount,t.frameRate),latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:i,height:r,transparent:t.transparent};var c}function Yn(t,e){if(!(e||t.estimatedBytes<=1e8))throw new v("VIDEO_OUTPUT_TOO_LARGE",`The estimated ${function(t){return t>=1e9?`${(t/1e9).toFixed(1)} GB`:`${Math.round(t/1e6)} MB`}(t.estimatedBytes)} video is too large for an in-memory export. Lower the resolution, duration, or quality, or pass allowLargeInMemory: true to toVideoBlob().`)}var Qn=["vp9","vp8"],Jn=["avc"],Kn=class{async $record(t,e,i,r={kind:"blob",allowLargeInMemory:t.allowLargeInMemory??!1}){this.R(t.signal),this.De();const n=await this.Ne(t);this.Re(t,"video export plan",n),"blob"===r.kind&&Yn(n,r.allowLargeInMemory),this.ze(i,"recording","probing",0,n.frameCount,n);const o="mp4"===n.format?new Bn:new $n,s="stream"===r.kind?new sn(r.writable,{chunked:!0}):new on,a=new jn({format:o,target:s}),h=this.je(n);let c;const l=new Mn(e.canvas,{codec:n.codec,quality:h,alpha:n.transparent?"keep":"discard",latencyMode:n.latencyMode,hardwareAcceleration:n.hardwareAcceleration,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:"deny",contentHint:n.contentHint,onEncoderConfig:e=>{c="quantizer"===e.bitrateMode?"quantizer":"ultra"===n.rateControlIntent?"bitrate-fallback":"bitrate",this.Re(t,"video encoder config",e,{rateControl:c})}});a.addVideoTrack(l,{frameRate:n.frameRate});let d=!1,u=!1;const f=()=>{d||(d=!0,l.close())};try{if(await x(a.start(),"Video output did not start within 30000ms.",t.signal,3e4),this.ze(i,"recording","probing",0,n.frameCount,n,c),await e.$render({frameCount:n.frameCount,frameRate:n.frameRate,signal:t.signal,prepareFrame:t.prepareFrame,onFrame:async({frameIndex:e})=>{this.R(t.signal),await this.Le(l.add(e/n.frameRate,1/n.frameRate),t.signal),this.ze(i,"recording","capturing",e+1,n.frameCount,n,c)}}),this.R(t.signal),f(),this.ze(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n,c),await x(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.ze(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n,c),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new v("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(p){f(),await(async()=>{if(!u){u=!0;try{await a.cancel()}catch{}}})();const t=this.He(p);throw i?.({state:"error",message:t.message,estimatedBytes:n.estimatedBytes}),t}}async Ne(t){const e=Xn(t),i="mp4"===t.format?new Bn:new $n,r="mp4"===t.format?Jn:Qn,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t)),o=this.je(e);let s=null;for(const a of n)if(await ai(a,{width:e.width,height:e.height,quality:o,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,contentHint:e.contentHint})){s=a;break}if(!s)throw new v("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${r.join(" or ")} at ${e.width}x${e.height}. Try a browser/device with native WebCodecs encoding support or reduce the export dimensions.`);return Xn(t,s)}je(t){const e=function(t){return"ultra"===t.rateControlIntent?{kind:"ultra",bitrate:t.bitrate}:t.qualityLevel?{kind:"named",level:t.qualityLevel}:{kind:"bitrate",bitrate:t.bitrate,bitrateMode:t.bitrateMode}}(t);return"named"===e.kind?new ei(e.level):"ultra"===e.kind?new ei({bitrate:e.bitrate,bitrateMode:"variable",quantizer:0}):new ei({bitrate:e.bitrate,bitrateMode:e.bitrateMode})}De(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new v("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}Le(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(g());const n=()=>r(g());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}R(t){if(t?.aborted)throw g()}ze(t,e,i,r,n,o,s){t?.({state:e,phase:i,frameIndex:r,frame:r,totalFrames:n,progress:n>0?r/n:0,rateControl:s,estimatedBytes:o.estimatedBytes})}He(t){return t instanceof v?t:new v("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}Re(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Zn=class{Ge;_;C;constructor(t,e){this.Ge=new Kn,this._=t,this.C=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.k(e,t);Yn(Xn(i),!1);const n=await this.qe(i,{kind:"blob",allowLargeInMemory:!1},t.onProgress);if(!n)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new r).$downloadFile(n,this.We(t.filename,`.${e}`))}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.k(e,t);Xn(i);const r=await this.qe(i,{kind:"blob",allowLargeInMemory:Boolean(t.allowLargeInMemory)},t.onProgress);if(!r)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async qe(t,e,i){const r=new E(this._,this.C,t.width,t.height);try{return await this.Ge.$record(t,r,i,e)}catch(n){throw i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n}}k(t,e){const i=this.Xe(e.frameRate,60),r=this.Xe(e.frameCount,300),n=this.Ye(e.pixelDensity,1),o=this.Qe(),s=Math.max(1,Math.round(this._.canvas.width/o*n)),a=Math.max(1,Math.round(this._.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,bitrate:this.Et(e.bitrate),bitrateMode:this.Tt(e.bitrateMode),contentHint:this.Je(e.contentHint),latencyMode:this.Ke(e.latencyMode),hardwareAcceleration:this.Ze(e.hardwareAcceleration),keyFrameInterval:this.ti(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),allowLargeInMemory:Boolean(e.allowLargeInMemory),signal:e.signal,prepareFrame:e.prepareFrame}}Xe(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}Ye(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}Et(t){return"number"==typeof t&&Number.isFinite(t)&&t>0||"low"===t||"medium"===t||"high"===t||"ultra"===t?t:"medium"}Tt(t){return"constant"===t||"variable"===t?t:"variable"}Je(t){return""===t||"motion"===t||"detail"===t||"text"===t?t:"text"}Ke(t){return"quality"===t||"realtime"===t?t:"quality"}Ze(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}ti(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}Qe(){const t=this._.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}We(t,e){if(!t)return;const i=t.trim();return i?i.toLowerCase().endsWith(e)?i:`${i}${e}`:void 0}},to=class extends i{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let a=0;a<r.rows;a++)for(let t=0;t<r.cols;t++){const r=4*o,h=this.$getEncodedCharacterValue(e.characterPixels,r),c=this.$extractCellTransform(e.characterPixels,r),d=s(n,h)?.character??" ";i.push({x:t,y:a,character:d,foreground:l(e.primaryColorPixels,r),background:l(e.secondaryColorPixels,r),transform:{invert:c.isInverted,flipX:c.flipHorizontal,flipY:c.flipVertical,rotation:c.rotation}}),o++}return i}},eo="textmode.document",io="2.0.0",ro={[t.NORMAL]:"normal",[t.ADDITIVE]:"additive",[t.MULTIPLY]:"multiply",[t.SCREEN]:"screen",[t.SUBTRACT]:"subtract",[t.DARKEN]:"darken",[t.LIGHTEN]:"lighten",[t.OVERLAY]:"overlay",[t.SOFT_LIGHT]:"softLight",[t.HARD_LIGHT]:"hardLight",[t.COLOR_DODGE]:"colorDodge",[t.COLOR_BURN]:"colorBurn",[t.DIFFERENCE]:"difference",[t.EXCLUSION]:"exclusion"},no=class{k(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}ei(t){return t.includeMetadata?{createdAt:/* @__PURE__ */(new Date).toISOString(),generator:{name:"textmode.export.js",version:"1.8.0"}}:void 0}ii(t,e){return"rgba"===e?{...t}:`#${[t.r,t.g,t.b,t.a].map(t=>t.toString(16).padStart(2,"0")).join("")}`}ri(t,e,i,r){const n=[];for(let o=0;o<i;o++){const i=o*e,s=t.slice(i,i+e).map(t=>({x:t.x,y:t.y,character:t.character,foreground:this.ii(t.foreground,r),background:this.ii(t.background,r),transform:{...t.transform}}));n.push(s)}return{encoding:"object-rows-v1",rows:n}}ni(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}oi(t,e){const i=(new to).$extractCellData(t);return this.ri(i,t.grid.cols,t.grid.rows,e.colorMode)}si(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:ro[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.ni(t),cells:this.oi(t,e)}}$generateJSONData(e,i={}){const r=this.k(i),n=this.ei(r);if("all"===r.target){const i=function(e){return[e.layers.base,...e.layers.all].map(i=>{const r=c(e,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??t.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(e),o=i[0].grid;return{format:eo,formatVersion:io,target:"all",...n?{metadata:n}:{},canvas:{width:o.width,height:o.height},layers:i.map(t=>this.si(t,r))}}const o=c(e,r.layer);return{format:eo,formatVersion:io,target:"selected",...n?{metadata:n}:{},canvas:{width:o.grid.width,height:o.grid.height},grid:this.ni(o),layer:{id:o.id,cells:this.oi(o,r)}}}$generateJSONString(t,e={}){const i=this.k(e),r=this.$generateJSONData(t,i),n="number"==typeof i.pretty?i.pretty:i.pretty?2:0;return JSON.stringify(r,null,n)}$saveJSON(t,e={}){const i=this.k(e);(new r).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename)}},oo="textmode-export-overlay__stack",so="textmode-export-overlay__stack--dense",ao="textmode-export-overlay__stack--compact",ho="textmode-export-overlay__section",co="textmode-export-overlay--dragging",lo="textmode-export-overlay__label",uo="textmode-export-overlay__field",fo="textmode-export-overlay__field--compact",po="textmode-export-overlay__field--dense",mo="textmode-export-overlay__field--full",wo="textmode-export-overlay__field--channel",bo="textmode-export-overlay__input",yo="textmode-export-overlay__muted",vo="textmode-export-overlay__button--primary",go="textmode-export-overlay__button--secondary",xo="textmode-export-overlay__button--full",Eo="textmode-export-overlay__link-icon",ko=class{element;mounted=!1;destroyed=!1;mount(t){if(this.destroyed)throw new Error("Cannot mount a destroyed component");if(this.mounted)return;const e=this.render();t.appendChild(e),this.element=e,this.onMount(),this.mounted=!0}unmount(){this.mounted&&this.element&&(this.ai(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this.hi(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}ai(){}hi(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}},To=class t extends ko{static ci="http://www.w3.org/2000/svg";li;get dragHandleElement(){if(!this.li)throw new Error("Header drag handle is not mounted yet");return this.li}render(){this.li=void 0;const t=document.createElement("div");t.classList.add(oo,so,"textmode-export-overlay__header");const e=document.createElement("div");e.classList.add("textmode-export-overlay__header-title-row");const i=document.createElement("div");i.classList.add("textmode-export-overlay__header-identity");const r=this.di("Move export overlay","textmode-export-overlay__grab-handle",[{d:"M9 5h.01"},{d:"M15 5h.01"},{d:"M9 12h.01"},{d:"M15 12h.01"},{d:"M9 19h.01"},{d:"M15 19h.01"}]);this.li=r;const n=document.createElement("strong");n.textContent="textmode.export.js",n.classList.add("textmode-export-overlay__title");const o=document.createElement("div");o.classList.add("textmode-export-overlay__header-links");const s=this.ui("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",Eo,[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"}]),a=this.ui("https://code.textmode.art/docs/support","Support textmode.export.js","textmode-export-overlay__support-icon",[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"},{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"},{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"}]);o.appendChild(s),o.appendChild(a),i.appendChild(r),i.appendChild(n),e.appendChild(i),e.appendChild(o);const h=document.createElement("div");return h.classList.add("textmode-export-overlay__divider"),t.appendChild(e),t.appendChild(h),t}di(t,e,i){const r=document.createElement("button");return r.type="button",r.classList.add(e),r.setAttribute("aria-label",t),r.title=t,r.appendChild(this.fi(Eo,i)),r}ui(t,e,i,r){const n=document.createElement("a");return n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("textmode-export-overlay__support-link"),n.setAttribute("aria-label",e),n.appendChild(this.fi(i,r)),n}fi(e,i){const r=document.createElementNS(t.ci,"svg");r.setAttribute("xmlns",t.ci),r.setAttribute("width","18"),r.setAttribute("height","18"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.classList.add(e);for(const n of i){const e=document.createElementNS(t.ci,"path");for(const[t,i]of Object.entries(n))e.setAttribute(t,i);r.appendChild(e)}return r}},Mo=class extends ko{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(uo),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(lo),e.textContent=this.props.label,this.props.labelFor&&(e.htmlFor=this.props.labelFor),t.appendChild(e),this.props.description){const e=document.createElement("span");e.classList.add(yo),e.textContent=this.props.description,t.appendChild(e)}return t}attachControl(t){this.root.appendChild(t)}update(t){this.props=t,super.update(t)}onUpdate(t){const e=this.root;for(;e.firstChild;)e.removeChild(e.firstChild);this.props=t,e.classList.add(uo),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(lo),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(yo),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(fo,po,mo,wo),e){case"compact":t.classList.add(fo);break;case"dense":t.classList.add(po);break;case"full":t.classList.add(mo);break;case"channel":t.classList.add(wo)}}},_o=class extends ko{props;select;handleChange=()=>{this.props.defaultValue=this.select.value};constructor(t){super(),this.props=t}render(){return this.select=document.createElement("select"),this.select.classList.add(bo),this.props.id&&(this.select.id=this.props.id),this.populateOptions(),this.select.addEventListener("change",this.handleChange),this.select}get selectElement(){return this.select}get value(){return this.select.value}set value(t){this.select&&(this.select.value=t),this.props.defaultValue=t}ai(){this.select.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,this.populateOptions(),t.defaultValue&&(this.select.value=t.defaultValue)}update(t){this.props={...this.props,...t},this.select&&(t.id&&(this.select.id=t.id),t.options&&this.populateOptions(),void 0!==t.defaultValue&&(this.select.value=t.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const t of this.props.options){const e=document.createElement("option");e.value=t.value,e.textContent=t.label,this.select.appendChild(e)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}},Co=class extends ko{props;button;constructor(t){super(),this.props=t}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add("textmode-export-overlay__button"),"secondary"===this.props.variant?this.button.classList.add(go):this.button.classList.add(vo),this.props.fullWidth&&this.button.classList.add(xo),this.button.disabled=Boolean(this.props.disabled),this.button}get buttonElement(){return this.button}setLabel(t){this.props.label=t,this.button.textContent=t}setDisabled(t){this.props.disabled=t,this.button.disabled=t}onUpdate(t){this.props=t,this.button.textContent=t.label,this.button.disabled=Boolean(t.disabled),"secondary"===t.variant?(this.button.classList.add(go),this.button.classList.remove(vo)):(this.button.classList.add(vo),this.button.classList.remove(go)),this.button.classList.toggle(xo,Boolean(t.fullWidth))}},Ao=class{et={};pi(t){const e=this.et[t];if(e)return e;const i=/* @__PURE__ */new Set;return this.et[t]=i,i}$on(t,e){const i=this.pi(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.et[t]}}$emit(t,e){const i=this.et[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.et))delete this.et[t]}},So=class{mi;et=/* @__PURE__ */new Set;constructor(t){this.mi=t}get snapshot(){return Object.freeze({...this.mi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.mi[o]!==t[o]){i=!0;break}if(!i)return;this.mi=Object.assign({},this.mi,t);const r=this.snapshot;for(const o of[...this.et])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.et.add(t),t(this.snapshot),()=>{this.et.delete(t)}}$reset(t){this.mi=t;const e=this.snapshot;for(const i of[...this.et])i(e)}},Bo=/* @__PURE__ */new Set(["txt","json","svg","image"]),Po=class{api;constructor(t){this.api=t}async $copy(t,e){switch(t){case"txt":{const t=this.api.toString(e);await navigator.clipboard.writeText(t);break}case"json":{const t=this.api.toJSONString(e);await navigator.clipboard.writeText(t);break}case"svg":{const t=this.api.toSVG(e);await navigator.clipboard.writeText(t);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}static isClipboardFormat(t){return Bo.has(t)}},Io={txt:(t,e)=>Promise.resolve(t.saveStrings(e)),json:(t,e)=>Promise.resolve(t.saveJSON(e)),image:(t,e)=>t.saveCanvas(e),svg:(t,e)=>Promise.resolve(t.saveSVG(e)),gif:(t,e,i)=>{const r={...e,onProgress:i.onGIFProgress};return t.saveGIF(r)},video:(t,e,i)=>{const r={...e,onProgress:i.onVideoProgress};return t.saveVideo(r)}},Fo=class{api;events;constructor(t,e){this.api=t,this.events=e}async $requestExport(t,e,i={}){this.events.$emit("export:request",{format:t});try{const r={onGIFProgress:i.onGIFProgress?e=>{i.onGIFProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"gif"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0,onVideoProgress:i.onVideoProgress?e=>{i.onVideoProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"video"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0};await Io[t](this.api,e,r),this.events.$emit("export:success",{format:t})}catch(r){throw this.events.$emit("export:error",{format:t,error:r}),r}}},$o=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Vo=class{key;constructor(t="textmode.export.overlay.position.v1"){this.key=t}load(){try{const t=window.localStorage.getItem(this.key);if(!t)return;const e=JSON.parse(t);if(1!==e.version||!$o(e.offsetX)||!$o(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if($o(t)&&$o(e))try{const i={version:1,offsetX:t,offsetY:e};window.localStorage.setItem(this.key,JSON.stringify(i))}catch{}}clear(){try{window.localStorage.removeItem(this.key)}catch{}}},Uo=class{modifier;host;surface;storage;animationFrameId=null;handleUpdate;bound=!1;dragHandle;dragState;position;renderedOffset;handlePointerDown=t=>this.onPointerDown(t);handlePointerMove=t=>this.onPointerMove(t);handlePointerUp=t=>this.onPointerUp(t);handleKeyDown=t=>this.onKeyDown(t);constructor(t,e,i=e,r=new Vo){this.modifier=t,this.host=e,this.surface=i,this.storage=r,this.handleUpdate=()=>this.scheduleUpdate();const n=this.storage.load();this.position=n?{mode:"custom",offsetX:n.offsetX,offsetY:n.offsetY}:{mode:"auto",offsetX:8,offsetY:8},this.renderedOffset={offsetX:this.position.offsetX,offsetY:this.position.offsetY}}getPosition(){return Object.freeze({...this.position})}setPosition(t,e={}){Number.isFinite(t.offsetX)&&Number.isFinite(t.offsetY)&&(this.position={mode:"custom",offsetX:t.offsetX,offsetY:t.offsetY},this.scheduleUpdate(),(e.persist??1)&&this.storage.save(this.position.offsetX,this.position.offsetY))}resetPosition(){this.position={mode:"auto",offsetX:8,offsetY:8},this.storage.clear(),this.scheduleUpdate()}scheduleUpdate(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=requestAnimationFrame(()=>this.update())}bind(){this.bound||(window.addEventListener("resize",this.handleUpdate),window.addEventListener("scroll",this.handleUpdate,!0),this.bound=!0,this.handleUpdate())}attachDragHandle(t){this.dragHandle!==t&&(this.detachDragHandle(),this.dragHandle=t,t.addEventListener("pointerdown",this.handlePointerDown),t.addEventListener("keydown",this.handleKeyDown))}detachDragHandle(){this.dragHandle&&(this.dragHandle.removeEventListener("pointerdown",this.handlePointerDown),this.dragHandle.removeEventListener("keydown",this.handleKeyDown),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp),this.dragHandle=void 0,this.dragState=void 0,this.surface.classList.remove(co))}onPointerDown(t){if(0===t.button&&this.dragHandle){t.preventDefault(),this.dragState={pointerId:t.pointerId,startClientX:t.clientX,startClientY:t.clientY,startOffsetX:this.renderedOffset.offsetX,startOffsetY:this.renderedOffset.offsetY},this.surface.classList.add(co),this.dragHandle.addEventListener("pointermove",this.handlePointerMove),this.dragHandle.addEventListener("pointerup",this.handlePointerUp),this.dragHandle.addEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.setPointerCapture?.(t.pointerId)}catch{}}}onPointerMove(t){this.dragState&&t.pointerId===this.dragState.pointerId&&(t.preventDefault(),this.setPosition({offsetX:this.dragState.startOffsetX+t.clientX-this.dragState.startClientX,offsetY:this.dragState.startOffsetY+t.clientY-this.dragState.startClientY},{persist:!1}))}onPointerUp(t){if(this.dragState&&t.pointerId===this.dragState.pointerId&&this.dragHandle){t.preventDefault(),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.hasPointerCapture?.(t.pointerId)&&this.dragHandle.releasePointerCapture?.(t.pointerId)}catch{}this.surface.classList.remove(co),this.dragState=void 0,"custom"===this.position.mode&&this.storage.save(this.position.offsetX,this.position.offsetY)}}onKeyDown(t){const e=t.shiftKey?32:8,i=this.renderedOffset;switch(t.key){case"ArrowUp":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY-e});break;case"ArrowDown":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY+e});break;case"ArrowLeft":t.preventDefault(),this.setPosition({offsetX:i.offsetX-e,offsetY:i.offsetY});break;case"ArrowRight":t.preventDefault(),this.setPosition({offsetX:i.offsetX+e,offsetY:i.offsetY});break;case"Home":t.preventDefault(),this.resetPosition()}}update(){if(this.animationFrameId=null,"none"===this.host.style.display)return;const t=this.modifier.canvas.getBoundingClientRect(),e=this.clampToViewport(t,this.position.offsetX,this.position.offsetY);this.host.style.top=`${t.top+window.scrollY+e.offsetY}px`,this.host.style.left=`${t.left+window.scrollX+e.offsetX}px`,this.renderedOffset=e}clampToViewport(t,e,i){const r=this.surface.getBoundingClientRect(),n=r.width||this.host.getBoundingClientRect().width||0,o=r.height||this.host.getBoundingClientRect().height||0,s=Math.max(8,window.innerWidth-n-8),a=Math.max(8,window.innerHeight-o-8),h=this.clamp(t.left+e,8,s),c=this.clamp(t.top+i,8,a);return{offsetX:h-t.left,offsetY:c-t.top}}clamp(t,e,i){return Math.min(Math.max(t,e),i)}dispose(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1),this.detachDragHandle()}},Oo=class extends ko{capabilities;wi;bi=/* @__PURE__ */new Set;constructor(t,e){super(),this.wi=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}yi(t){return this.bi.add(t),t}ai(){for(const t of this.bi)t.unmount()}hi(){for(const t of this.bi)t.destroy();this.bi.clear()}},Do=class extends ko{props;checkbox;labelElement;handleChange=()=>{this.props.defaultChecked=this.checkbox.checked};constructor(t){super(),this.props=t}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add("textmode-export-overlay__checkbox"),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=Boolean(this.props.defaultChecked),this.checkbox.addEventListener("change",this.handleChange);const t=document.createElement("span");return t.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(t),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(t){this.checkbox.checked=t}ai(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,t.id&&(this.checkbox.id=t.id,this.labelElement.htmlFor=t.id),this.checkbox.checked=Boolean(t.defaultChecked),this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=t.label)}},No=class extends ko{props;input;handleInput=()=>{this.props.defaultValue=this.input.value};constructor(t){super(),this.props=t}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(bo),this.props.id&&(this.input.id=this.props.id),void 0!==this.props.maxLength&&(this.input.maxLength=this.props.maxLength),void 0!==this.props.defaultValue&&(this.input.value=this.props.defaultValue),this.input.addEventListener("input",this.handleInput),this.input}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t}ai(){this.input.removeEventListener("input",this.handleInput)}onUpdate(t){this.props=t,t.id&&(this.input.id=t.id),void 0!==t.maxLength&&(this.input.maxLength=t.maxLength),void 0!==t.defaultValue&&(this.input.value=t.defaultValue)}},Ro=class extends ko{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new Mo({label:"layer",labelFor:t.id,variant:"full"}),this.select=new _o({id:t.id,options:[],defaultValue:t.provider.getDefaultId()})}render(){const t=document.createElement("div");return this.field.mount(t),this.refresh(),this.select.mount(this.field.root),t}get layer(){const t=this.provider.getLayerById(this.select.value);if(t)return t;const e=this.provider.getDefaultId();return this.select.value=e,this.provider.getLayerById(e)}setDisabled(t){this.select.selectElement.disabled=t}refresh(){const t=this.provider.getOptions(),e=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),i=t.some(t=>t.id===e)?e:this.provider.getDefaultId();this.select.update({options:t.map(t=>({value:t.id,label:t.label})),defaultValue:i}),this.select.value=i}ai(){this.select.unmount(),this.field.unmount()}hi(){this.select.destroy(),this.field.destroy()}},zo=class extends Oo{layerTarget;trailingSpaces=this.yi(new Do({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.yi(new No({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.yi(new Ro({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new Mo({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return e.mount(t),this.emptyCharacter.mount(e.root),t}getOptions(){const t=this.wi.defaultOptions,e=this.emptyCharacter.value||t.emptyCharacter;return{layer:this.layerTarget?.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:e}}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.wi.defaultOptions;this.trailingSpaces.checked=t.preserveTrailingSpaces??!1,this.emptyCharacter.value=t.emptyCharacter??" "}},jo=class extends Oo{layerTarget;layerTargetContainer;target=this.yi(new _o({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.yi(new Do({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.yi(new Do({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.yi(new _o({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.yi(new Ro({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Mo({label:"target",labelFor:"textmode-export-json-target",variant:"full"});e.mount(t),this.target.mount(e.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),t.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(t),this.includeMetadata.mount(t);const i=new Mo({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return i.mount(t),this.colorMode.mount(i.root),this.updateLayerTargetVisibility(),t}getOptions(){const t=this.target.value;return{target:t,layer:"selected"===t?this.layerTarget?.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.wi.defaultOptions;this.target.value=t.target??"selected",this.prettyPrint.checked="number"==typeof t.pretty?t.pretty>0:t.pretty??!0,this.includeMetadata.checked=t.includeMetadata??!0,this.colorMode.value=t.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){const t="selected"===this.target.value;this.layerTargetContainer&&(this.layerTargetContainer.style.display=t?"":"none"),this.layerTarget?.setDisabled(!t)}},Lo="textmode-export-number-input",Ho=`${Lo}__field`,Go=`${Lo}__controls`,qo=`${Lo}__control`,Wo=`${Lo}__display`,Xo=`${Wo}--visible`,Yo=t=>{const e=document.createElement("button");return e.type="button",e.className=qo,e.textContent=t>0?"▲":"▼",e},Qo=class extends ko{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=/* @__PURE__ */new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=Lo,this.input=document.createElement("input"),this.input.type="number",this.input.value=this.props.defaultValue,Object.assign(this.input,this.props.attributes),this.input.className=Ho,this.display=document.createElement("div"),this.display.className=Wo;const e=document.createElement("div");return e.className=Go,this.incrementButton=Yo(1),this.decrementButton=Yo(-1),e.appendChild(this.incrementButton),e.appendChild(this.decrementButton),t.appendChild(this.input),t.appendChild(this.display),t.appendChild(e),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(t),this.updateDisplay(),t}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t,this.updateDisplay()}refresh(){this.updateDisplay()}hi(){this.clearHoldTimers(),this.disabledObserver?.disconnect()}bindStepControls(){const t=t=>()=>{if(this.input.disabled)return;const e=this.input.value,i=this.input.getAttribute("step");if(i&&"any"!==i)t>0?this.input.stepUp():this.input.stepDown();else{const e=t>0?1:-1,i=Number.parseFloat(this.input.value||"0"),r=Number.isFinite(i)?i+e:e;this.input.value=String(r)}var r;this.input.value!==e&&((r=this.input).dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},e=t(1),i=t(-1),r=(t,e)=>i=>{if(this.suppressClickAfterPointer.get(t))return this.suppressClickAfterPointer.set(t,!1),void i.preventDefault();e()};this.incrementButton.addEventListener("click",r(this.incrementButton,e)),this.decrementButton.addEventListener("click",r(this.decrementButton,i))}bindHoldBehavior(){const t=(t,e)=>{const i=e>0?()=>this.incrementButton.click():()=>this.decrementButton.click();t.addEventListener("pointerdown",e=>{if(0===e.button){e.preventDefault(),this.suppressClickAfterPointer.set(t,!0),this.activePointerId=e.pointerId;try{t.setPointerCapture(e.pointerId)}catch{}i(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(i,80)},380)}});const r=()=>{if(void 0!==this.activePointerId){try{t.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),r()};t.addEventListener("pointerup",n),t.addEventListener("pointerleave",n),t.addEventListener("pointercancel",n)};t(this.incrementButton,1),t(this.decrementButton,-1)}bindInputListeners(){const t=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",t),this.input.addEventListener("change",t)}observeDisabledState(t){const e=()=>{const e=this.input.disabled;this.incrementButton.disabled=e,this.decrementButton.disabled=e,t.classList.toggle("is-disabled",e),e?(this.display.classList.remove(Xo),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};"undefined"!=typeof MutationObserver&&(this.disabledObserver=new MutationObserver(e),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),e()}updateDisplay(){const t=this.props.formatDisplay;if(!t)return this.display.textContent="",this.display.classList.remove(Xo),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const e=this.input.value,i=Number.parseFloat(e),r=t(Number.isFinite(i)?i:NaN,e,this.input);r?(this.display.textContent=r,this.display.classList.add(Xo),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(Xo),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){void 0!==this.holdTimeoutId&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),void 0!==this.holdIntervalId&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}},Jo=class extends ko{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?oo:void 0,"stackDense"===this.variant?so:void 0,"stackCompact"===this.variant?ao:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?ho:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Ko=class extends Oo{formatSelect=this.yi(new _o({id:"textmode-export-image-format",options:[{value:"png",label:"PNG (.png)"},{value:"jpg",label:"JPG (.jpg)"},{value:"webp",label:"WEBP (.webp)"}],defaultValue:"png"}));scaleInput=this.yi(new Qo({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Mo({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return r.mount(e.root),this.scaleInput.mount(r.root),this.scaleInput.inputElement.id="textmode-export-image-scale",t}getOptions(){const t=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(t)?t:this.wi.defaultOptions?.scale??1}}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const t=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0}applyDefaults(){const t=this.wi.defaultOptions;this.formatSelect.value=t.format??"png",this.scaleInput.value=String(t.scale??1)}},Zo=class extends Oo{layerTarget;includeBackground=this.yi(new Do({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.yi(new _o({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.yi(new Qo({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.yi(new Ro({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(oo),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new Jo("row");e.mount(t);const i=new Mo({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new Mo({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return r.mount(e.root),this.strokeWidth.mount(r.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),t}getOptions(){return{layer:this.layerTarget?.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const t=Number.parseFloat(this.strokeWidth.value);return"stroke"!==this.drawMode.value||Number.isFinite(t)&&t>=0}refreshLayerTargets(){this.layerTarget?.refresh()}updateStrokeControls(){const t="stroke"===this.drawMode.value;this.strokeWidth.inputElement.disabled=!t,this.strokeWidth.refresh()}applyDefaults(){const t=this.wi.defaultOptions;this.includeBackground.checked=t.includeBackgroundRectangles??!0,this.drawMode.value=t.drawMode??"fill",this.strokeWidth.value=String(t.strokeWidth??1),this.strokeWidth.refresh()}},ts={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},es=class extends ko{props;container;messageElement;constructor(t){super(),this.props=t}render(){this.container=document.createElement("div"),this.container.classList.add("textmode-export-overlay__status"),"gif"===this.props.context?this.container.classList.add("textmode-export-overlay__status--gif"):"video"===this.props.context&&this.container.classList.add("textmode-export-overlay__status--video");const t=document.createElement("span");return t.classList.add("textmode-export-overlay__status-title"),t.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add("textmode-export-overlay__status-value"),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(t),this.container.appendChild(this.messageElement),this.container}setMessage(t,e="neutral"){this.messageElement.textContent=t,this.applyVariant(e)}onUpdate(t){this.props=t,this.setMessage(t.message,t.variant??"neutral")}applyVariant(t){this.messageElement.classList.remove(...Object.values(ts)),this.messageElement.classList.add(ts[t])}},is=class extends Oo{frameCountInput=this.yi(new Qo({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.yi(new Qo({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.yi(new Qo({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.yi(new Qo({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(t,e)=>Number.isFinite(t)?0===t?"∞":null:""===e.trim()?null:e}));status=this.yi(new es({title:"status",message:"ready to record",variant:"neutral",context:"gif"}));recordingState="idle";constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});i.mount(e.root),this.frameCountInput.mount(i.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const r=new Mo({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});r.mount(e.root),this.frameRateInput.mount(r.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const n=new Jo("row");n.mount(t);const o=new Mo({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});o.mount(n.root),this.scaleInput.mount(o.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const s=new Mo({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return s.mount(n.root),this.repeatInput.mount(s.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(t),t}getOptions(){const t=this.wi.defaultOptions;return{frameCount:this.safeParseInt(this.frameCountInput.value,t.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,t.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,t.scale??1),repeat:this.safeParseInt(this.repeatInput.value,t.repeat??0)}}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseInt(this.frameRateInput.value,10),i=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;switch(this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.scaleInput.inputElement.disabled=i,this.repeatInput.inputElement.disabled=i,t){case"recording":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`recording ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`encoding ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage(e?.message??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(t){if("recording"!==t.state&&"encoding"!==t.state||!t.totalFrames)"completed"===t.state?this.status.setMessage("GIF saved successfully","active"):"error"===t.state&&this.status.setMessage(t.message??"failed to export GIF","alert");else{const e="recording"===t.state?"recording":"encoding";this.status.setMessage(`${e} ${t.frameIndex??0}/${t.totalFrames}`,"active")}}applyDefaults(){const t=this.wi.defaultOptions;this.frameCountInput.value=String(t.frameCount??300),this.frameRateInput.value=String(t.frameRate??60),this.scaleInput.value=String(t.scale??1),this.repeatInput.value=String(t.repeat??0),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(t,e){const i=Number.parseInt(t,10);return Number.isFinite(i)?i:e}safeParseFloat(t,e){const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}},rs=class extends Oo{formatSelect=this.yi(new _o({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));bitrateSelect=this.yi(new _o({id:"textmode-export-video-bitrate",options:[{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"},{value:"ultra",label:"ultra (near-lossless)"}],defaultValue:"medium"}));frameRateInput=this.yi(new Qo({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.yi(new Qo({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));bitrateModeSelect=this.yi(new _o({id:"textmode-export-video-bitrate-mode",options:[{value:"variable",label:"variable"},{value:"constant",label:"constant"}],defaultValue:"variable"}));latencyModeSelect=this.yi(new _o({id:"textmode-export-video-latency-mode",options:[{value:"quality",label:"quality"},{value:"realtime",label:"realtime"}],defaultValue:"quality"}));hardwareAccelerationSelect=this.yi(new _o({id:"textmode-export-video-hardware-acceleration",options:[{value:"no-preference",label:"no preference"},{value:"prefer-hardware",label:"prefer hardware"},{value:"prefer-software",label:"prefer software"}],defaultValue:"no-preference"}));keyFrameIntervalInput=this.yi(new Qo({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.yi(new Do({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.yi(new es({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.yi(new es({title:"estimate",message:"logical dimensions · duration · size",variant:"neutral",context:"video"}));recordingState="idle";resizeObserver;constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(oo);const e=new Jo("row");e.mount(t);const i=new Mo({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Mo({label:"bitrate preset",labelFor:"textmode-export-video-bitrate",variant:"compact"});r.mount(e.root),this.bitrateSelect.mount(r.root);const n=new Jo("row");n.mount(t);const o=new Mo({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});o.mount(n.root),this.frameCountInput.mount(o.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const s=new Mo({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});s.mount(n.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const a=new Jo("row");a.mount(t);const h=new Mo({label:"bitrate mode",labelFor:"textmode-export-video-bitrate-mode",variant:"compact"});h.mount(a.root),this.bitrateModeSelect.mount(h.root);const c=new Mo({label:"encoder mode",labelFor:"textmode-export-video-latency-mode",variant:"compact"});c.mount(a.root),this.latencyModeSelect.mount(c.root);const l=new Jo("row");l.mount(t);const d=new Mo({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});d.mount(l.root),this.hardwareAccelerationSelect.mount(d.root);const u=new Mo({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return u.mount(l.root),this.keyFrameIntervalInput.mount(u.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(t),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.bitrateSelect.selectElement.addEventListener("change",this.handleBitrateChange),this.frameCountInput.inputElement.addEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.addEventListener("input",this.handleEstimateChange),this.formatSelect.selectElement.addEventListener("change",this.handleEstimateChange),this.estimate.mount(t),this.status.mount(t),this.syncOutputEstimate(),this.wi.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.wi.videoDimensionsTarget)),t}getOptions(){const t=this.wi.defaultOptions,e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),r=Number.parseFloat(this.keyFrameIntervalInput.value),n=this.formatSelect.value,o={format:n,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(r)?r:t.keyFrameInterval??2,frameCount:Number.isFinite(e)?e:t.frameCount??480,frameRate:Number.isFinite(i)?i:t.frameRate??60};return"webm"===n&&(o.transparent=this.transparencyInput.checked),o}setDefaults(t){Object.assign(this.wi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.syncReadyStatus()}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseFloat(this.frameRateInput.value),i=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(t)&&t>=1&&Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;this.formatSelect.selectElement.disabled=i,this.bitrateSelect.selectElement.disabled=i,this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.bitrateModeSelect.selectElement.disabled=i,this.latencyModeSelect.selectElement.disabled=i,this.hardwareAccelerationSelect.selectElement.disabled=i,this.keyFrameIntervalInput.inputElement.disabled=i,this.transparencyInput.inputElement.disabled=i||"webm"!==this.formatSelect.value,this.syncStatus(t,e)}handleProgress(t){this.syncStatus(t.state,t)}syncStatus(t,e){switch(t){case"recording":{const t=e?.frameIndex??0,i=e?.totalFrames??this.resolvePlannedFrameCount();if(i){const e=Math.min(Math.max(0,Math.round(t)),i);this.status.setMessage(`recording ${e}/${i} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(t))} frames`,"active");break}case"encoding":this.status.setMessage("writing"===e?.phase?"writing video to disk":"finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(e?.message?`error: ${e.message}`:"recording failed","alert");break;default:this.syncReadyStatus()}}resolvePlannedFrameCount(){const t=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(t)&&t>0?Math.round(t):void 0}applyDefaults(){const t=this.wi.defaultOptions;this.formatSelect.value=t.format??"mp4",this.bitrateSelect.value=this.resolveBitratePreset(t.bitrate),this.frameCountInput.value=String(t.frameCount??480),this.frameRateInput.value=String(t.frameRate??60),this.bitrateModeSelect.value=t.bitrateMode??"variable",this.latencyModeSelect.value=t.latencyMode??"quality",this.hardwareAccelerationSelect.value=t.hardwareAcceleration??"no-preference",this.keyFrameIntervalInput.value=String(t.keyFrameInterval??2),this.transparencyInput.checked=Boolean(t.transparent),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveBitratePreset(t){return"low"===t||"medium"===t||"high"===t||"ultra"===t?t:"medium"}handleBitrateChange=()=>{this.isRecording()||this.syncReadyStatus(),this.syncOutputEstimate()};handleEstimateChange=()=>this.syncOutputEstimate();syncReadyStatus(){"ultra"===this.bitrateSelect.value?this.status.setMessage("near-lossless; very large files and slower exports","alert"):this.status.setMessage("ready to record","neutral")}handleFormatChange=()=>{this.syncTransparencyAvailability(),this.syncOutputEstimate()};syncOutputEstimate(){if(!this.estimate.isMounted())return;const t=this.wi.videoDimensionsProvider?.(),e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value);if(!t||!Number.isFinite(e)||!Number.isFinite(i)||i<=0)return void this.estimate.setMessage("logical dimensions · duration · size","neutral");const r={format:this.formatSelect.value,frameCount:Math.max(1,Math.round(e)),frameRate:i,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,contentHint:"text",latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.parseFloat(this.keyFrameIntervalInput.value)||2,pixelDensity:1,width:t.width,height:t.height,transparent:"webm"===this.formatSelect.value&&this.transparencyInput.checked,debugLogging:!1};try{const t=Xn(r);this.estimate.setMessage(`${t.width}×${t.height} · ${(t.frameCount/t.frameRate).toFixed(1)}s · ~${this.formatBytes(t.estimatedBytes)}`,"ultra"===this.bitrateSelect.value?"alert":"neutral")}catch{this.estimate.setMessage(`${t.width}×${t.height} · MP4 requires even dimensions`,"alert")}}formatBytes(t){return t>=1e9?`${(t/1e9).toFixed(1)} GB`:`${Math.max(1,Math.round(t/1e6))} MB`}ai(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.bitrateSelect.selectElement.removeEventListener("change",this.handleBitrateChange),this.formatSelect.selectElement.removeEventListener("change",this.handleFormatChange),this.formatSelect.selectElement.removeEventListener("change",this.handleEstimateChange),this.frameCountInput.inputElement.removeEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.removeEventListener("input",this.handleEstimateChange),super.ai()}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const t="webm"===this.formatSelect.value;this.transparencyInput.root.style.display=t?"":"none",this.transparencyInput.inputElement.disabled=!t||this.isRecording(),t||(this.transparencyInput.checked=!1)}};function ns(t){return t.capabilities.recording}var os=Object.freeze({format:"txt",txt:Object.freeze({preserveTrailingSpaces:!1,emptyCharacter:" "}),json:Object.freeze({target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"}),image:Object.freeze({format:"png",scale:1}),svg:Object.freeze({includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1}),gif:Object.freeze({frameCount:300,frameRate:60,scale:1,repeat:0}),video:Object.freeze({format:"mp4",frameCount:480,frameRate:60,bitrate:"medium",bitrateMode:"variable",latencyMode:"quality",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1})});function ss(){return{format:os.format,txt:{...os.txt},json:{...os.json},image:{...os.image},svg:{...os.svg},gif:{...os.gif},video:{...os.video}}}function as(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var hs=class{gi;constructor(){this.gi=ss()}get current(){return this.snapshot()}snapshot(){return{format:(t=this.gi).format,txt:{...t.txt},json:{...t.json},image:{...t.image},svg:{...t.svg},gif:{...t.gif},video:{...t.video}};var t}get(t){return this.gi[t]}merge(t){t.format&&(this.gi.format=t.format),t.txt&&Object.assign(this.gi.txt,t.txt),t.json&&Object.assign(this.gi.json,t.json),t.image&&Object.assign(this.gi.image,t.image),t.svg&&Object.assign(this.gi.svg,t.svg),t.gif&&Object.assign(this.gi.gif,t.gif),t.video&&Object.assign(this.gi.video,t.video)}reset(t){const e=ss();if(!t)return this.gi.format=e.format,as(this.gi.txt,e.txt),as(this.gi.json,e.json),as(this.gi.image,e.image),as(this.gi.svg,e.svg),as(this.gi.gif,e.gif),void as(this.gi.video,e.video);switch(t){case"format":this.gi.format=e.format;break;case"txt":as(this.gi.txt,e.txt);break;case"json":as(this.gi.json,e.json);break;case"image":as(this.gi.image,e.image);break;case"svg":as(this.gi.svg,e.svg);break;case"gif":as(this.gi.gif,e.gif);break;case"video":as(this.gi.video,e.video)}}},cs=class{_;xi;mi;Ei;ki;Ti;Mi;_i=/* @__PURE__ */new Map;Ci=[];Ai;Si;Bi;Pi;Ii;Fi;$i=new To;Vi=new Mo({label:"export format",labelFor:"textmode-export-format",variant:"full"});Ui=new _o({id:"textmode-export-format",options:[]});Oi=new Co({label:"download file",fullWidth:!0,variant:"primary"});Di=new Co({label:"copy to clipboard",fullWidth:!0,variant:"primary"});Ni;Ri;zi=()=>{this.ji(this.Ui.value)};Li=()=>{this.Hi().catch(t=>{console.error("[textmode-export] Export failed",t)})};Gi=()=>{this.qi().catch(t=>{console.error("[textmode-export] Copy failed",t)})};constructor(t,e,i,r){this._=t,this.xi=i;const n=this.Wi(i.current.format,r);this.mi=new So((t=>({format:t,isBusy:!1}))(n)),this.Ei=new Ao,this.ki=new Fo(e,this.Ei),this.Ti=new Po(e),this.Mi=r,this.Ni=n,this.Xi(),this.Yi()}$mount(){this.Qi(),this.Ji(),this.Fi=new Uo(this._,this.Ai,this.Bi),this.Fi.attachDragHandle(this.$i.dragHandleElement),this.Fi.bind(),this.Ki(this.Ni)}show(){this.Ai&&(this.refreshLayerTargets(),this.Ai.style.display="",this.Fi?.scheduleUpdate())}hide(){this.Ai&&(this.Ai.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this.Ai&&"none"!==this.Ai.style.display}refreshLayerTargets(){this.Ri&&this.Ri.blade.capabilities.layerTarget&&this.Ri.blade.refreshLayerTargets()}resetPosition(){this.Fi.resetPosition()}getPosition(){return this.Fi.getPosition()}setPosition(t){this.Fi.setPosition(t)}setDefaults(t){t.format&&this.Zi(t.format),this.xi.merge(t),this.tr(this.er(t)),t.format&&this.ji(t.format)}getDefaults(){return this.xi.current}resetDefaults(t){this.xi.reset(t),"format"!==t?(this.tr(t?[t]:void 0),t||this.ji(this.xi.current.format)):this.ji(this.xi.current.format)}$dispose(){this.Ui.isMounted()&&this.Ui.selectElement.removeEventListener("change",this.zi),this.Oi.isMounted()&&this.Oi.buttonElement.removeEventListener("click",this.Li),this.Di.isMounted()&&this.Di.buttonElement.removeEventListener("click",this.Gi);for(const t of this.Ci)t();this.Ci.length=0,this.Ei.$clear();for(const t of this._i.values())t.blade.destroy();this._i.clear(),this.Ri=void 0,this.Ai?.isConnected&&this.Ai.remove(),this.Fi?.dispose()}tr(t){const e=new Set(t??this._i.keys());for(const[i,r]of this._i)e.has(i)&&(r.blade.isMounted()?(r.blade.reset(),r.needsReset=!1):r.needsReset=!0)}Xi(){for(const t of this.Mi){const e=t.createBlade();this._i.set(t.format,{definition:t,blade:e,initialized:!1,needsReset:!1})}}Wi(t,e){return e.some(e=>e.format===t)?t:e[0]?.format??t}er(t){return this.Mi.map(t=>t.format).filter(e=>void 0!==t[e])}Zi(t){if(!this._i.has(t))throw new Error(`Unknown export format: ${t}`)}Qi(){this.Ai=document.createElement("div"),this.Ai.dataset.plugin="textmode-export-overlay-host",this.Ai.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this.Si=this.Ai.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent="@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg:#141414cc;--overlay-surface:#282828e6;--overlay-border:#ffffff24;--overlay-border-strong:#fff3;--overlay-border-focus:#a0a0a099;--overlay-focus-shadow:0 0 0 1px #8c8c8c47;--overlay-text:#fff;--overlay-muted:#c8c8c8bd;--overlay-radius:.75rem;--overlay-stack-gap:.55rem;gap:var(--overlay-stack-gap);background:var(--overlay-bg);min-width:236px;max-width:236px;color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:auto;z-index:2147483647;flex-direction:column;padding:.65rem .8rem;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;display:flex;position:absolute;top:0;left:0;box-shadow:0 12px 28px #0000004d}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__header-title-row{justify-content:space-between;align-items:center;gap:.4rem;display:flex}.textmode-export-overlay__header-identity{align-items:center;gap:.35rem;min-width:0;display:inline-flex}.textmode-export-overlay__header-links{flex:none;align-items:center;gap:.3rem;display:inline-flex}.textmode-export-overlay__grab-handle{color:#d7d7d7b8;cursor:grab;touch-action:none;background:0 0;border:1px solid #0000;border-radius:.45rem;flex:none;justify-content:center;align-items:center;width:1.45rem;height:1.45rem;padding:0;line-height:0;transition:background .18s,color .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__grab-handle:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__grab-handle:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay--dragging,.textmode-export-overlay--dragging .textmode-export-overlay__grab-handle{cursor:grabbing}.textmode-export-overlay__support-link{color:#d7d7d7d1;background:0 0;border:1px solid #0000;border-radius:.45rem;justify-content:center;align-items:center;padding:.2rem;line-height:0;text-decoration:none;transition:background .18s,color .18s,transform .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{width:1rem;height:1rem;display:block}.textmode-export-overlay__stack{gap:var(--overlay-stack-gap);flex-direction:column;display:flex}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__title{white-space:nowrap;font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{background:#ffffff29;width:100%;height:1px;margin-top:.25rem}.textmode-export-overlay__label{opacity:.9;font-weight:500}.textmode-export-overlay__checkbox{align-items:center;gap:.5rem;display:flex}.textmode-export-overlay__checkbox input[type=checkbox]{accent-color:#646464e6;width:1rem;height:1rem}.textmode-export-overlay__row{flex-wrap:wrap;align-items:flex-start;gap:.6rem;width:100%;display:flex}.textmode-export-overlay__field{flex-direction:column;flex:120px;gap:.3rem;min-width:120px;display:flex}.textmode-export-overlay__field--compact{flex:100px;min-width:100px}.textmode-export-overlay__field--dense{flex:90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{flex:100%;width:100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);width:100%;color:var(--overlay-text);font:inherit;border-radius:.4rem;padding:.35rem .5rem;line-height:1.35;transition:border-color .18s,box-shadow .18s,background .18s}.textmode-export-overlay select.textmode-export-overlay__input{appearance:none;background-image:url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(200, 200, 200, 0.74)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\");background-position:right .5rem center;background-repeat:no-repeat;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb;outline:none}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{opacity:.7;font-size:.75rem;display:block}.textmode-export-overlay__button{cursor:pointer;border:none;border-radius:.45rem;justify-content:center;align-items:center;gap:.35rem;padding:.45rem .7rem;font-weight:600;transition:background .2s,transform .2s,box-shadow .2s;display:inline-flex}.textmode-export-overlay__button--primary{color:#fff;background:#505050}.textmode-export-overlay__button--secondary{color:#fff;background:#606060}.textmode-export-overlay__button--full{width:100%}.textmode-export-overlay__button:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 7px 18px #00000073}.textmode-export-overlay__button--primary:hover:not(:disabled){background:#404040}.textmode-export-overlay__button--secondary:hover:not(:disabled){background:#4a4a4a}.textmode-export-overlay__button:disabled{cursor:default;opacity:.55;box-shadow:none;transform:none}.textmode-export-overlay__status{background:#4646462e;border:1px solid #6e6e6e38;border-radius:.45rem;flex-direction:column;gap:.25rem;padding:.45rem .55rem;display:flex}.textmode-export-overlay__status--gif{background:#5050501f;border-color:#78787840}.textmode-export-overlay__status--video{background:#4646461f;border-color:#6e6e6e40}.textmode-export-overlay__status-title{opacity:.85;text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;font-weight:600}.textmode-export-overlay__status-value{color:#dedede;font-size:.82rem;transition:color .18s}.textmode-export-overlay__status-value--neutral{color:#cfcfcf}.textmode-export-overlay__status-value--active{color:#f5f5f5}.textmode-export-overlay__status-value--alert{color:#b8b8b8}.textmode-export-number-input,.textmode-export-overlay .textmode-export-number-input{background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;align-items:stretch;width:100%;transition:border-color .18s,box-shadow .18s,background .18s;display:flex;position:relative;overflow:hidden}.textmode-export-number-input:focus-within{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-number-input.is-disabled{opacity:.55}.textmode-export-number-input__field{min-width:0;color:var(--overlay-text);font:inherit;appearance:textfield;background:0 0;border:none;flex:auto;padding:.35rem .5rem}.textmode-export-number-input__field::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field:focus{outline:none}.textmode-export-number-input__controls{border-left:1px solid #ffffff1f;flex-direction:column;min-width:1.6rem;display:flex}.textmode-export-number-input__control{color:#d0d0d0;cursor:pointer;background:#32323299;border:none;flex:1;justify-content:center;align-items:center;width:100%;padding:0;font-size:.68rem;line-height:1;transition:background .15s,color .15s;display:flex}.textmode-export-number-input__control:hover:not(:disabled){color:#fff;background:#5a5a5ad9}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;color:#c8c8c866;background:#28282880}.textmode-export-number-input:focus-within .textmode-export-number-input__control{color:#e8e8e8;background:#3c3c3cbf}.textmode-export-number-input__display{pointer-events:none;color:#f8fafc;opacity:0;align-items:center;padding:.4rem .55rem;transition:opacity .14s;display:flex;position:absolute;inset:0}.textmode-export-number-input__display--visible{opacity:1}}",this.Si.appendChild(t),this.Bi=document.createElement("div"),this.Bi.dataset.plugin="textmode-export-overlay",this.Bi.classList.add("textmode-export-overlay",oo),this.Si.appendChild(this.Bi),document.body.appendChild(this.Ai)}Ji(){this.$i.mount(this.Bi);const t=document.createElement("div");t.classList.add(ho),this.Bi.appendChild(t),this.Vi.mount(t),this.ir(),this.Ui.mount(this.Vi.root),this.Ui.selectElement.addEventListener("change",this.zi),this.Pi=document.createElement("div"),this.Pi.classList.add(oo,ao),this.Bi.appendChild(this.Pi),this.Oi.mount(this.Bi),this.Oi.buttonElement.addEventListener("click",this.Li),this.Ii=document.createElement("div"),this.Ii.classList.add(oo,so),this.Bi.appendChild(this.Ii),this.Di.mount(this.Ii),this.Di.buttonElement.dataset.defaultLabel="copy to clipboard",this.Di.buttonElement.addEventListener("click",this.Gi)}ir(){const t=this.Mi.map(t=>({value:t.format,label:t.label}));this.Ui.update({options:t,defaultValue:this.Ni})}Yi(){this.Ci.push(this.Ei.$on("export:request",({format:t})=>{t===this.Ni&&(this.mi.$set({isBusy:!0,error:void 0}),this.rr())}),this.Ei.$on("export:success",({format:t})=>{if(t===this.Ni){const e={isBusy:!1};"gif"===t&&(e.gifProgress=void 0),"video"===t&&(e.videoProgress=void 0),this.mi.$set(e),this.rr()}}),this.Ei.$on("export:error",({format:t,error:e})=>{t===this.Ni&&(this.mi.$set({isBusy:!1,error:e}),this.rr())}),this.Ei.$on("export:progress",({format:t,progress:e})=>{if(e){if("gif"===t){const t=e;this.mi.$set({gifProgress:t}),"gif"===this.Ri?.definition.format&&ns(this.Ri.blade)&&this.Ri.blade.handleProgress(t)}else if("video"===t){const t=e;this.mi.$set({videoProgress:t}),"video"===this.Ri?.definition.format&&ns(this.Ri.blade)&&this.Ri.blade.handleProgress(t)}this.rr()}}))}ji(t){this.Ni=t,this.mi.$set({format:t}),this.Ki(t),this.Ei.$emit("format:change",{format:t})}Ki(t){const e=this._i.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this.Ri&&this.Ri.blade.unmount(),this.Pi.innerHTML="",e.blade.mount(this.Pi),e.initialized&&!e.needsReset||(e.blade.reset(),e.initialized=!0,e.needsReset=!1),this.Ri=e,this.Ui.value=t,this.refreshLayerTargets(),this.nr(),this.rr(),this.Fi?.scheduleUpdate()}nr(){const t=this.Ri?.definition.supportsClipboard??!1;this.Ii.style.display=t?"flex":"none",this.Di.setDisabled(!t)}async Hi(){if(!this.Ri)return;const t=this.Ri.definition.format,e=this.Ri.blade.getOptions();if(this.Ri.blade.validate()){if(ns(this.Ri.blade)){const r=this.Ri.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this.ki.$requestExport(t,e,{onGIFProgress:t=>{r.setRecordingState(t.state,t)},onVideoProgress:t=>{r.setRecordingState(t.state,t)}})}catch(i){throw r.setRecordingState("error"),i}return void window.setTimeout(()=>{r.setRecordingState("idle"),this.rr()},1600)}this.Oi.setDisabled(!0),this.Oi.setLabel("exporting…");try{await this.ki.$requestExport(t,e)}finally{this.Oi.setDisabled(!1),this.Oi.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async qi(){if(!this.Ri||!this.Ri.definition.supportsClipboard)return;const t=this.Ri.definition.format,e=this.Ri.blade.getOptions(),i=this.Di.buttonElement.dataset.defaultLabel??"copy to clipboard";this.Di.setDisabled(!0),this.Di.setLabel("copying…");try{switch(t){case"txt":await this.Ti.$copy("txt",e);break;case"json":await this.Ti.$copy("json",e);break;case"svg":await this.Ti.$copy("svg",e);break;case"image":await this.Ti.$copy("image",e);break;default:return}this.Di.setLabel("copied!")}catch(r){console.error("[textmode-export] Failed to copy to clipboard",r),this.Di.setLabel("copy failed!")}finally{window.setTimeout(()=>{this.Di.setLabel(i),this.Di.setDisabled(!1)},1200)}}rr(){if(!this.Ri)return;const t=this.Ri.definition.format;if(ns(this.Ri.blade)){const e=this.Ri.blade,i="gif"===t?this.mi.snapshot.gifProgress:this.mi.snapshot.videoProgress;if(e.isRecording())if(this.Oi.setDisabled(!0),i?.totalFrames){const e=i.frameIndex??0,r="encoding"===i.state?"encoding":"recording";this.Oi.setLabel("gif"===t?`${r} ${e}/${i.totalFrames}`:`recording ${e}/${i.totalFrames} frames`)}else this.Oi.setLabel("encoding"===i?.state?"encoding…":"recording…");else this.Oi.setDisabled(!1),this.Oi.setLabel("start recording");return}const e=this.mi.snapshot.isBusy;this.Oi.setDisabled(e),this.Oi.setLabel(e?"exporting…":"download file")}};var ls=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob"],ds=class{api;C;sr=/* @__PURE__ */new Set;ar;hr;Y=!1;constructor(t,e){this.C=e;const i={saveCanvas:async(e={})=>(this.cr(),(new w).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.cr(),(new w).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.cr(),(new w).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.cr(),(new p).$saveSVG(t,e)},saveStrings:(e={})=>{this.cr(),(new b).$saveTXT(t,e)},toSVG:(e={})=>(this.cr(),(new p).$generateSVG(t,e)),toString:(e={})=>(this.cr(),(new b).$generateTXT(t,e)),toJSON:(e={})=>(this.cr(),(new no).$generateJSONData(t,e)),toJSONString:(e={})=>(this.cr(),(new no).$generateJSONString(t,e)),saveJSON:(e={})=>{this.cr(),(new no).$saveJSON(t,e)},saveGIF:(e={})=>this.lr(e.signal,i=>new A(t,t=>this.C(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.lr(e.signal,i=>new A(t,t=>this.C(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.lr(e.signal,i=>new Zn(t,t=>this.C(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.lr(e.signal,i=>new Zn(t,t=>this.C(t)).$generateVideoBlob({...e,signal:i})),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new hs,n=new cs(t,e,r,function(t,e=(()=>{const t=ss();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new zo({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new jo({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Ko({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Zo({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new is({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new rs({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>h(t),getLayerById:e=>h(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.C(()=>{!this.Y&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.ar=r,this.hr=n,i.exportOverlay=this.dr()}dispose(){if(!this.Y){this.Y=!0;for(const t of this.sr)t.abort();this.sr.clear(),this.hr(),this.ar.$dispose()}}dr(){return{show:()=>{this.cr(),this.ar.show()},hide:()=>{this.cr(),this.ar.hide()},toggle:()=>{this.cr(),this.ar.toggle()},isVisible:()=>(this.cr(),this.ar.isVisible()),resetPosition:()=>{this.cr(),this.ar.resetPosition()},getPosition:()=>(this.cr(),this.ar.getPosition()),setPosition:t=>{this.cr(),this.ar.setPosition(t)},setDefaults:t=>{this.cr(),this.ar.setDefaults(t)},getDefaults:()=>(this.cr(),this.ar.getDefaults()),resetDefaults:t=>{this.cr(),this.ar.resetDefaults(t)}}}lr(t,e){this.cr();const i=new AbortController,r=new AbortController,n=()=>r.abort(),o=()=>r.abort();return t?.addEventListener("abort",n,{once:!0}),i.signal.addEventListener("abort",o,{once:!0}),t?.aborted&&r.abort(),this.sr.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.sr.delete(i)})}cr(){if(this.Y)throw new Error("Textmode export plugin has been disposed.")}},us={name:"textmode.export.js",install(t,e){const i=new ds(t,t=>e.on("postDraw",t));try{for(const t of ls)e.defineExtension("textmodifier",t,{value:i.api[t]});e.defineExtension("textmodifier","exportOverlay",{get:()=>i.api.exportOverlay})}catch(r){throw i.dispose(),r}return()=>i.dispose()}};"undefined"!=typeof window&&(window.ExportPlugin=us);export{us as ExportPlugin};
|